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