2 Copyright (C) 2006 Paul Davis
3 By Dave Robillard, 2006
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 #include "pbd/error.h"
21 #include "pbd/enumwriter.h"
22 #include "pbd/convert.h"
23 #include "midi++/events.h"
24 #include "evoral/midi_util.h"
26 #include "ardour/amp.h"
27 #include "ardour/buffer_set.h"
28 #include "ardour/debug.h"
29 #include "ardour/delivery.h"
30 #include "ardour/io_processor.h"
31 #include "ardour/meter.h"
32 #include "ardour/midi_diskstream.h"
33 #include "ardour/midi_playlist.h"
34 #include "ardour/midi_port.h"
35 #include "ardour/midi_region.h"
36 #include "ardour/midi_source.h"
37 #include "ardour/midi_track.h"
38 #include "ardour/panner.h"
39 #include "ardour/port.h"
40 #include "ardour/processor.h"
41 #include "ardour/route_group_specialized.h"
42 #include "ardour/session.h"
43 #include "ardour/session_playlists.h"
44 #include "ardour/utils.h"
49 using namespace ARDOUR;
52 PBD::Signal1<void,bool> MidiTrack::StepEditStatusChange;
54 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
55 : Track (sess, name, flag, mode, DataType::MIDI)
56 , _immediate_events(1024) // FIXME: size?
57 , _step_edit_ring_buffer(64) // FIXME: size?
58 , _note_mode(Sustained)
59 , _step_editing (false)
60 , _default_channel (0)
65 MidiTrack::~MidiTrack ()
70 MidiTrack::use_new_diskstream ()
72 MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
74 if (_flags & Hidden) {
75 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
77 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
80 assert(_mode != Destructive);
82 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
83 ds->do_refill_with_alloc ();
84 ds->set_block_size (_session.get_block_size ());
90 MidiTrack::set_record_enabled (bool yn, void *src)
96 Track::set_record_enabled (yn, src);
100 MidiTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
102 Track::set_diskstream (ds);
104 _diskstream->set_track (this);
105 _diskstream->set_destructive (_mode == Destructive);
107 _diskstream->set_record_enabled (false);
108 //_diskstream->monitor_input (false);
110 DiskstreamChanged (); /* EMIT SIGNAL */
113 boost::shared_ptr<MidiDiskstream>
114 MidiTrack::midi_diskstream() const
116 return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
120 MidiTrack::set_state (const XMLNode& node, int version)
122 return _set_state (node, version, true);
126 MidiTrack::_set_state (const XMLNode& node, int version, bool call_base)
128 const XMLProperty *prop;
129 XMLNodeConstIterator iter;
131 if (Route::_set_state (node, version, call_base)) {
135 // No destructive MIDI tracks (yet?)
138 if ((prop = node.property (X_("note-mode"))) != 0) {
139 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
141 _note_mode = Sustained;
144 if ((prop = node.property ("midi-thru")) != 0) {
145 set_midi_thru (prop->value() == "yes");
148 if ((prop = node.property ("default-channel")) != 0) {
149 set_default_channel ((uint8_t) atoi (prop->value()));
153 XMLNodeConstIterator niter;
156 nlist = node.children();
157 for (niter = nlist.begin(); niter != nlist.end(); ++niter){
160 if (child->name() == X_("recenable")) {
161 _rec_enable_control->set_state (*child, version);
162 _session.add_controllable (_rec_enable_control);
166 if (version >= 3000) {
167 if ((child = find_named_node (node, X_("Diskstream"))) != 0) {
168 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *child));
169 ds->do_refill_with_alloc ();
174 pending_state = const_cast<XMLNode*> (&node);
176 if (_session.state_of_the_state() & Session::Loading) {
177 _session.StateReady.connect_same_thread (*this, boost::bind (&MidiTrack::set_state_part_two, this));
179 set_state_part_two ();
186 MidiTrack::state(bool full_state)
188 XMLNode& root (Route::state(full_state));
189 XMLNode* freeze_node;
192 if (_freeze_record.playlist) {
195 freeze_node = new XMLNode (X_("freeze-info"));
196 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
197 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
199 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
200 inode = new XMLNode (X_("processor"));
201 (*i)->id.print (buf, sizeof(buf));
202 inode->add_property (X_("id"), buf);
203 inode->add_child_copy ((*i)->state);
205 freeze_node->add_child_nocopy (*inode);
208 root.add_child_nocopy (*freeze_node);
211 root.add_property (X_("note-mode"), enum_2_string (_note_mode));
212 root.add_child_nocopy (_rec_enable_control->get_state());
213 root.add_child_nocopy (_diskstream->get_state ());
215 root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
216 root.add_property ("note-mode", enum_2_string (_note_mode));
217 root.add_property ("midi-thru", (_midi_thru ? "yes" : "no"));
218 snprintf (buf, sizeof (buf), "%d", (int) _default_channel);
219 root.add_property ("default-channel", buf);
225 MidiTrack::set_state_part_two ()
229 LocaleGuard lg (X_("POSIX"));
231 /* This is called after all session state has been restored but before
232 have been made ports and connections are established.
235 if (pending_state == 0) {
239 if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
241 _freeze_record.state = Frozen;
243 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
246 _freeze_record.processor_info.clear ();
248 if ((prop = fnode->property (X_("playlist"))) != 0) {
249 boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
251 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
253 _freeze_record.playlist.reset();
254 _freeze_record.state = NoFreeze;
259 if ((prop = fnode->property (X_("state"))) != 0) {
260 _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
263 XMLNodeConstIterator citer;
264 XMLNodeList clist = fnode->children();
266 for (citer = clist.begin(); citer != clist.end(); ++citer) {
267 if ((*citer)->name() != X_("processor")) {
271 if ((prop = (*citer)->property (X_("id"))) == 0) {
275 FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
276 boost::shared_ptr<Processor>());
277 frii->id = prop->value ();
278 _freeze_record.processor_info.push_back (frii);
282 if ((fnode = find_named_node (*pending_state, X_("Diskstream"))) != 0) {
283 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *fnode));
284 ds->do_refill_with_alloc ();
285 ds->set_block_size (_session.get_block_size ());
293 MidiTrack::roll (nframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick,
294 bool can_record, bool rec_monitors_input, bool& needs_butler)
296 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
302 boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
304 automation_snapshot (start_frame);
306 if (n_outputs().n_total() == 0 && _processors.empty()) {
315 nframes_t transport_frame = _session.transport_frame();
318 if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
319 /* need to do this so that the diskstream sets its
320 playback distance to zero, thus causing diskstream::commit
323 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input, needs_butler);
328 if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input, needs_butler)) != 0) {
333 /* special condition applies */
335 if (_meter_point == MeterInput) {
336 _input->process_input (_meter, start_frame, end_frame, nframes);
339 if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
341 /* not actually recording, but we want to hear the input material anyway,
342 at least potentially (depending on monitoring options)
345 passthru (start_frame, end_frame, nframes, 0);
349 XXX is it true that the earlier test on n_outputs()
350 means that we can avoid checking it again here? i think
351 so, because changing the i/o configuration of an IO
352 requires holding the AudioEngine lock, which we hold
353 while in the process() tree.
357 /* copy the diskstream data to all output buffers */
359 //const size_t limit = n_process_buffers().n_audio();
360 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
361 MidiBuffer& mbuf (bufs.get_midi (0));
363 /* we are a MIDI track, so we always start the chain with a single-channel diskstream */
369 diskstream->get_playback (mbuf, start_frame, end_frame);
371 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
373 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
375 process_output_buffers (bufs, start_frame, end_frame, nframes,
376 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
380 _main_outs->flush (nframes, end_frame - start_frame - 1);
386 MidiTrack::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
387 bool state_changing, bool can_record, bool rec_monitors_input)
389 int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
391 if (ret == 0 && _step_editing) {
392 push_midi_input_to_step_edit_ringbuffer (nframes);
399 MidiTrack::handle_transport_stopped (bool abort, bool did_locate, bool flush_processors)
402 _main_outs->transport_stopped ();
403 Route::handle_transport_stopped (abort, did_locate, flush_processors);
408 MidiTrack::push_midi_input_to_step_edit_ringbuffer (nframes_t nframes)
410 PortSet& ports (_input->ports());
412 for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
414 Buffer& b (p->get_buffer (nframes));
415 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
418 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
420 const Evoral::MIDIEvent<nframes_t> ev(*e, false);
422 /* we don't care about the time for this purpose */
424 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
430 MidiTrack::write_out_of_band_data (BufferSet& bufs, sframes_t /*start*/, sframes_t /*end*/, nframes_t nframes)
432 // Append immediate events
433 MidiBuffer& buf (bufs.get_midi (0));
434 if (_immediate_events.read_space()) {
435 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 has %2 of immediate events to deliver\n",
436 name(), _immediate_events.read_space()));
438 _immediate_events.read (buf, 0, 1, nframes-1); // all stamps = 0
440 // MIDI thru: send incoming data "through" output
441 if (_midi_thru && _session.transport_speed() != 0.0f && _input->n_ports().n_midi()) {
442 buf.merge_in_place (_input->midi(0)->get_midi_buffer(nframes));
447 MidiTrack::export_stuff (BufferSet& /*bufs*/, nframes_t /*nframes*/, sframes_t /*end_frame*/)
453 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
455 Route::set_latency_delay (longest_session_latency);
456 _diskstream->set_roll_delay (_roll_delay);
459 boost::shared_ptr<Region>
460 MidiTrack::bounce (InterThreadInfo& /*itt*/)
463 // vector<MidiSource*> srcs;
464 // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
465 return boost::shared_ptr<Region> ();
469 boost::shared_ptr<Region>
470 MidiTrack::bounce_range (nframes_t /*start*/, nframes_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
473 //vector<MidiSource*> srcs;
474 //return _session.write_one_track (*this, start, end, false, srcs, itt);
475 return boost::shared_ptr<Region> ();
479 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
484 MidiTrack::unfreeze ()
486 _freeze_record.state = UnFrozen;
487 FreezeChange (); /* EMIT SIGNAL */
491 MidiTrack::set_note_mode (NoteMode m)
494 midi_diskstream()->set_note_mode(m);
498 MidiTrack::midi_panic()
500 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers panic data\n", name()));
501 for (uint8_t channel = 0; channel <= 0xF; channel++) {
502 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
503 write_immediate_event(3, ev);
504 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
505 write_immediate_event(3, ev);
506 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
507 write_immediate_event(3, ev);
511 /** \return true on success, false on failure (no buffer space left)
514 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
516 if (!Evoral::midi_event_is_valid(buf, size)) {
517 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
520 const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
521 return (_immediate_events.write(0, type, size, buf) == size);
525 MidiTrack::MidiControl::set_value(float val)
529 cerr << "MIDIControl value is infinity" << endl;
530 } else if (isnan(val)) {
531 cerr << "MIDIControl value is NaN" << endl;
532 } else if (val < _list->parameter().min()) {
533 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
534 } else if (val > _list->parameter().max()) {
535 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
544 assert(val <= _list->parameter().max());
545 if ( ! automation_playback()) {
547 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
548 switch(_list->parameter().type()) {
549 case MidiCCAutomation:
550 ev[0] += MIDI_CMD_CONTROL;
551 ev[1] = _list->parameter().id();
555 case MidiPgmChangeAutomation:
557 ev[0] += MIDI_CMD_PGM_CHANGE;
561 case MidiChannelPressureAutomation:
563 ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
567 case MidiPitchBenderAutomation:
568 ev[0] += MIDI_CMD_BENDER;
569 ev[1] = 0x7F & int(val);
570 ev[2] = 0x7F & (int(val) >> 7);
576 _route->write_immediate_event(size, ev);
579 AutomationControl::set_value(val);
583 MidiTrack::set_step_editing (bool yn)
585 if (_session.record_status() != Session::Disabled) {
589 if (yn != _step_editing) {
591 StepEditStatusChange (yn);
596 MidiTrack::set_default_channel (uint8_t chn)
598 _default_channel = std::min ((unsigned int) chn, 15U);
602 MidiTrack::set_midi_thru (bool yn)
607 boost::shared_ptr<SMFSource>
608 MidiTrack::write_source (uint32_t n)
610 return midi_diskstream()->write_source ();
614 MidiTrack::set_channel_mode (ChannelMode mode, uint16_t mask)
616 midi_diskstream()->set_channel_mode (mode, mask);
620 MidiTrack::get_channel_mode ()
622 return midi_diskstream()->get_channel_mode ();
626 MidiTrack::get_channel_mask ()
628 return midi_diskstream()->get_channel_mask ();
631 boost::shared_ptr<MidiPlaylist>
632 MidiTrack::midi_playlist ()
634 return midi_diskstream()->midi_playlist ();