Thought-to-be-fix for #2794; fix route process order sorting.
[ardour.git] / libs / ardour / midi_track.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3         By Dave Robillard, 2006
4
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.
9
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.
14
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.
18 */
19 #include "pbd/error.h"
20
21 #include "pbd/enumwriter.h"
22 #include "pbd/convert.h"
23 #include "midi++/events.h"
24 #include "evoral/midi_util.h"
25
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"
45
46 #include "i18n.h"
47
48 using namespace std;
49 using namespace ARDOUR;
50 using namespace PBD;
51
52 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
53         : Track (sess, name, flag, mode, DataType::MIDI)
54         , _immediate_events(1024) // FIXME: size?
55         , _step_edit_ring_buffer(64) // FIXME: size?
56         , _note_mode(Sustained)
57         , _step_editing (false)
58         , _default_channel (0)
59         , _midi_thru (true)
60 {
61 }
62
63 MidiTrack::~MidiTrack ()
64 {
65 }
66
67 void
68 MidiTrack::use_new_diskstream ()
69 {
70         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
71
72         if (_flags & Hidden) {
73                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
74         } else {
75                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
76         }
77
78         assert(_mode != Destructive);
79
80         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
81         ds->do_refill_with_alloc ();
82         ds->set_block_size (_session.get_block_size ());
83
84         set_diskstream (ds);
85 }
86
87 void
88 MidiTrack::set_record_enabled (bool yn, void *src)
89 {
90         if (_step_editing) {
91                 return;
92         }
93
94         Track::set_record_enabled (yn, src);
95 }
96
97 void
98 MidiTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
99 {
100         Track::set_diskstream (ds);
101         
102         _diskstream->set_track (this);
103         _diskstream->set_destructive (_mode == Destructive);
104
105         _diskstream->set_record_enabled (false);
106         //_diskstream->monitor_input (false);
107
108         _diskstream_data_recorded_connection.disconnect ();
109         boost::shared_ptr<MidiDiskstream> mds = boost::dynamic_pointer_cast<MidiDiskstream> (ds);
110         mds->DataRecorded.connect_same_thread (_diskstream_data_recorded_connection, boost::bind (&MidiTrack::diskstream_data_recorded, this, _1, _2));
111
112         DiskstreamChanged (); /* EMIT SIGNAL */
113 }
114
115 boost::shared_ptr<MidiDiskstream>
116 MidiTrack::midi_diskstream() const
117 {
118         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
119 }
120
121 int
122 MidiTrack::set_state (const XMLNode& node, int version)
123 {
124         return _set_state (node, version, true);
125 }
126
127 int
128 MidiTrack::_set_state (const XMLNode& node, int version, bool call_base)
129 {
130         const XMLProperty *prop;
131         XMLNodeConstIterator iter;
132
133         if (Route::_set_state (node, version, call_base)) {
134                 return -1;
135         }
136
137         // No destructive MIDI tracks (yet?)
138         _mode = Normal;
139
140         if ((prop = node.property (X_("note-mode"))) != 0) {
141                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
142         } else {
143                 _note_mode = Sustained;
144         }
145
146         if ((prop = node.property ("midi-thru")) != 0) {
147                 set_midi_thru (prop->value() == "yes");
148         }
149
150         if ((prop = node.property ("default-channel")) != 0) {
151                 set_default_channel ((uint8_t) atoi (prop->value()));
152         }
153
154         XMLNodeList nlist;
155         XMLNodeConstIterator niter;
156         XMLNode *child;
157
158         nlist = node.children();
159         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
160                 child = *niter;
161
162                 if (child->name() == X_("recenable")) {
163                         _rec_enable_control->set_state (*child, version);
164                         _session.add_controllable (_rec_enable_control);
165                 }
166         }
167
168         if (version >= 3000) {
169                 if ((child = find_named_node (node, X_("Diskstream"))) != 0) {
170                         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *child));
171                         ds->do_refill_with_alloc ();
172                         set_diskstream (ds);
173                 }
174         }
175
176         pending_state = const_cast<XMLNode*> (&node);
177
178         if (_session.state_of_the_state() & Session::Loading) {
179                 _session.StateReady.connect_same_thread (*this, boost::bind (&MidiTrack::set_state_part_two, this));
180         } else {
181                 set_state_part_two ();
182         }
183
184         return 0;
185 }
186
187 XMLNode&
188 MidiTrack::state(bool full_state)
189 {
190         XMLNode& root (Route::state(full_state));
191         XMLNode* freeze_node;
192         char buf[64];
193
194         if (_freeze_record.playlist) {
195                 XMLNode* inode;
196
197                 freeze_node = new XMLNode (X_("freeze-info"));
198                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
199                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
200
201                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
202                         inode = new XMLNode (X_("processor"));
203                         (*i)->id.print (buf, sizeof(buf));
204                         inode->add_property (X_("id"), buf);
205                         inode->add_child_copy ((*i)->state);
206
207                         freeze_node->add_child_nocopy (*inode);
208                 }
209
210                 root.add_child_nocopy (*freeze_node);
211         }
212
213         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
214         root.add_child_nocopy (_rec_enable_control->get_state());
215         root.add_child_nocopy (_diskstream->get_state ());
216
217         root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
218         root.add_property ("note-mode", enum_2_string (_note_mode));
219         root.add_property ("midi-thru", (_midi_thru ? "yes" : "no"));
220         snprintf (buf, sizeof (buf), "%d", (int) _default_channel);
221         root.add_property ("default-channel", buf);
222
223         return root;
224 }
225
226 void
227 MidiTrack::set_state_part_two ()
228 {
229         XMLNode* fnode;
230         XMLProperty* prop;
231         LocaleGuard lg (X_("POSIX"));
232
233         /* This is called after all session state has been restored but before
234            have been made ports and connections are established.
235         */
236
237         if (pending_state == 0) {
238                 return;
239         }
240
241         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
242
243                 _freeze_record.state = Frozen;
244
245                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
246                         delete *i;
247                 }
248                 _freeze_record.processor_info.clear ();
249
250                 if ((prop = fnode->property (X_("playlist"))) != 0) {
251                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
252                         if (pl) {
253                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
254                         } else {
255                                 _freeze_record.playlist.reset();
256                                 _freeze_record.state = NoFreeze;
257                         return;
258                         }
259                 }
260
261                 if ((prop = fnode->property (X_("state"))) != 0) {
262                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
263                 }
264
265                 XMLNodeConstIterator citer;
266                 XMLNodeList clist = fnode->children();
267
268                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
269                         if ((*citer)->name() != X_("processor")) {
270                                 continue;
271                         }
272
273                         if ((prop = (*citer)->property (X_("id"))) == 0) {
274                                 continue;
275                         }
276
277                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
278                                                                                    boost::shared_ptr<Processor>());
279                         frii->id = prop->value ();
280                         _freeze_record.processor_info.push_back (frii);
281                 }
282         }
283
284         if ((fnode = find_named_node (*pending_state, X_("Diskstream"))) != 0) {
285                 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *fnode));
286                 ds->do_refill_with_alloc ();
287                 ds->set_block_size (_session.get_block_size ());
288                 set_diskstream (ds);
289         }
290
291         return;
292 }
293
294 int
295 MidiTrack::roll (nframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick,
296                  bool can_record, bool rec_monitors_input, bool& needs_butler)
297 {
298         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
299         if (!lm.locked()) {
300                 return 0;
301         }
302
303         int dret;
304         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
305
306         automation_snapshot (start_frame);
307
308         if (n_outputs().n_total() == 0 && _processors.empty()) {
309                 return 0;
310         }
311
312         if (!_active) {
313                 silence (nframes);
314                 return 0;
315         }
316
317         nframes_t transport_frame = _session.transport_frame();
318
319
320         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
321                 /* need to do this so that the diskstream sets its
322                    playback distance to zero, thus causing diskstream::commit
323                    to do nothing.
324                    */
325                 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input, needs_butler);
326         }
327
328         _silent = false;
329
330         if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input, needs_butler)) != 0) {
331                 silence (nframes);
332                 return dret;
333         }
334
335         /* special condition applies */
336
337         if (_meter_point == MeterInput) {
338                 _input->process_input (_meter, start_frame, end_frame, nframes);
339         }
340
341         if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
342
343                 /* not actually recording, but we want to hear the input material anyway,
344                    at least potentially (depending on monitoring options)
345                 */
346
347                 passthru (start_frame, end_frame, nframes, 0);
348
349         } else {
350                 /*
351                    XXX is it true that the earlier test on n_outputs()
352                    means that we can avoid checking it again here? i think
353                    so, because changing the i/o configuration of an IO
354                    requires holding the AudioEngine lock, which we hold
355                    while in the process() tree.
356                    */
357
358
359                 /* copy the diskstream data to all output buffers */
360
361                 //const size_t limit = n_process_buffers().n_audio();
362                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
363                 MidiBuffer& mbuf (bufs.get_midi (0));
364
365                 /* we are a MIDI track, so we always start the chain with a single-channel diskstream */
366                 ChanCount c;
367                 c.set_audio (0);
368                 c.set_midi (1);
369                 bufs.set_count (c);
370
371                 diskstream->get_playback (mbuf, start_frame, end_frame);
372
373                 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
374
375                 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
376
377                 process_output_buffers (bufs, start_frame, end_frame, nframes,
378                                         (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
379
380         }
381
382         _main_outs->flush_buffers (nframes, end_frame - start_frame - 1);
383
384         return 0;
385 }
386
387 int
388 MidiTrack::no_roll (nframes_t nframes, framepos_t start_frame, framepos_t end_frame,
389                     bool state_changing, bool can_record, bool rec_monitors_input)
390 {
391         int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
392
393         if (ret == 0 && _step_editing) {
394                 push_midi_input_to_step_edit_ringbuffer (nframes);
395         }
396
397         return ret;
398 }
399
400 void
401 MidiTrack::handle_transport_stopped (bool abort, bool did_locate, bool flush_processors)
402 {
403         Route::handle_transport_stopped (abort, did_locate, flush_processors);
404 }
405
406 void
407 MidiTrack::push_midi_input_to_step_edit_ringbuffer (nframes_t nframes)
408 {
409         PortSet& ports (_input->ports());
410
411         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
412
413                 Buffer& b (p->get_buffer (nframes));
414                 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
415                 assert (mb);
416
417                 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
418
419                         const Evoral::MIDIEvent<nframes_t> ev(*e, false);
420
421                         /* note on, since for step edit, note length is determined
422                            elsewhere 
423                         */
424                         
425                         if (ev.is_note_on()) {
426                                 /* we don't care about the time for this purpose */
427                                 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
428                         }
429                 }
430         }
431 }
432
433 void
434 MidiTrack::write_out_of_band_data (BufferSet& bufs, framepos_t /*start*/, framepos_t /*end*/, nframes_t nframes)
435 {
436         // Append immediate events
437         MidiBuffer& buf (bufs.get_midi (0));
438         if (_immediate_events.read_space()) {
439                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 has %2 of immediate events to deliver\n", 
440                                                             name(), _immediate_events.read_space()));
441         }
442         _immediate_events.read (buf, 0, 1, nframes-1); // all stamps = 0
443         
444         // MIDI thru: send incoming data "through" output
445         if (_midi_thru && _session.transport_speed() != 0.0f && _input->n_ports().n_midi()) {
446                 buf.merge_in_place (_input->midi(0)->get_midi_buffer(nframes));
447         }
448 }
449
450 int
451 MidiTrack::export_stuff (BufferSet& /*bufs*/, nframes_t /*nframes*/, framepos_t /*end_frame*/)
452 {
453         return -1;
454 }
455
456 void
457 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
458 {
459         Route::set_latency_delay (longest_session_latency);
460         _diskstream->set_roll_delay (_roll_delay);
461 }
462
463 boost::shared_ptr<Region>
464 MidiTrack::bounce (InterThreadInfo& /*itt*/)
465 {
466         throw;
467         // vector<MidiSource*> srcs;
468         // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
469         return boost::shared_ptr<Region> ();
470 }
471
472
473 boost::shared_ptr<Region>
474 MidiTrack::bounce_range (nframes_t /*start*/, nframes_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
475 {
476         throw;
477         //vector<MidiSource*> srcs;
478         //return _session.write_one_track (*this, start, end, false, srcs, itt);
479         return boost::shared_ptr<Region> ();
480 }
481
482 void
483 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
484 {
485 }
486
487 void
488 MidiTrack::unfreeze ()
489 {
490         _freeze_record.state = UnFrozen;
491         FreezeChange (); /* EMIT SIGNAL */
492 }
493
494 void
495 MidiTrack::set_note_mode (NoteMode m)
496 {
497         _note_mode = m;
498         midi_diskstream()->set_note_mode(m);
499 }
500
501 void
502 MidiTrack::midi_panic()
503 {
504         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers panic data\n", name()));
505         for (uint8_t channel = 0; channel <= 0xF; channel++) {
506                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
507                 write_immediate_event(3, ev);
508                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
509                 write_immediate_event(3, ev);
510                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
511                 write_immediate_event(3, ev);
512         }
513 }
514
515 /** \return true on success, false on failure (no buffer space left)
516  */
517 bool
518 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
519 {
520         if (!Evoral::midi_event_is_valid(buf, size)) {
521                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
522                 return false;
523         }
524         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
525         return (_immediate_events.write(0, type, size, buf) == size);
526 }
527
528 void
529 MidiTrack::MidiControl::set_value(double val)
530 {
531         bool valid = false;
532         if (isinf(val)) {
533                 cerr << "MIDIControl value is infinity" << endl;
534         } else if (isnan(val)) {
535                 cerr << "MIDIControl value is NaN" << endl;
536         } else if (val < _list->parameter().min()) {
537                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
538         } else if (val > _list->parameter().max()) {
539                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
540         } else {
541                 valid = true;
542         }
543
544         if (!valid) {
545                 return;
546         }
547
548         assert(val <= _list->parameter().max());
549         if ( ! automation_playback()) {
550                 size_t size = 3;
551                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
552                 switch(_list->parameter().type()) {
553                 case MidiCCAutomation:
554                         ev[0] += MIDI_CMD_CONTROL;
555                         ev[1] = _list->parameter().id();
556                         ev[2] = int(val);
557                         break;
558
559                 case MidiPgmChangeAutomation:
560                         size = 2;
561                         ev[0] += MIDI_CMD_PGM_CHANGE;
562                         ev[1] = int(val);
563                         break;
564
565                 case MidiChannelPressureAutomation:
566                         size = 2;
567                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
568                         ev[1] = int(val);
569                         break;
570
571                 case MidiPitchBenderAutomation:
572                         ev[0] += MIDI_CMD_BENDER;
573                         ev[1] = 0x7F & int(val);
574                         ev[2] = 0x7F & (int(val) >> 7);
575                         break;
576
577                 default:
578                         assert(false);
579                 }
580                 _route->write_immediate_event(size,  ev);
581         }
582
583         AutomationControl::set_value(val);
584 }
585
586 void
587 MidiTrack::set_step_editing (bool yn)
588 {
589         if (_session.record_status() != Session::Disabled) {
590                 return;
591         }
592
593         if (yn != _step_editing) {
594                 _step_editing = yn;
595                 StepEditStatusChange (yn);
596         }
597 }
598
599 void
600 MidiTrack::set_default_channel (uint8_t chn)
601 {
602         _default_channel = std::min ((unsigned int) chn, 15U);
603 }
604
605 void
606 MidiTrack::set_midi_thru (bool yn)
607 {
608         _midi_thru = yn;
609 }
610
611 boost::shared_ptr<SMFSource>
612 MidiTrack::write_source (uint32_t)
613 {
614         return midi_diskstream()->write_source ();
615 }
616
617 void
618 MidiTrack::set_channel_mode (ChannelMode mode, uint16_t mask)
619 {
620         midi_diskstream()->set_channel_mode (mode, mask);
621 }
622
623 ChannelMode
624 MidiTrack::get_channel_mode ()
625 {
626         return midi_diskstream()->get_channel_mode ();
627 }
628
629 uint16_t
630 MidiTrack::get_channel_mask ()
631 {
632         return midi_diskstream()->get_channel_mask ();
633 }
634
635 boost::shared_ptr<MidiPlaylist>
636 MidiTrack::midi_playlist ()
637 {
638         return midi_diskstream()->midi_playlist ();
639 }
640
641 void
642 MidiTrack::diskstream_data_recorded (boost::shared_ptr<MidiBuffer> buf, boost::weak_ptr<MidiSource> src)
643 {
644         DataRecorded (buf, src); /* EMIT SIGNAL */
645 }
646