sorta-kinda working latency compensation, latency reporting and capture alignment...
[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
160         if (version >= 3000) {
161                 if ((child = find_named_node (node, X_("Diskstream"))) != 0) {
162                         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *child));
163                         ds->do_refill_with_alloc ();
164                         set_diskstream (ds);
165                 }
166         }
167
168         /* set rec-enable control *AFTER* setting up diskstream, because it may want to operate
169            on the diskstream as it sets its own state
170         */
171
172         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
173                 child = *niter;
174
175                 if (child->name() == Controllable::xml_node_name && (prop = child->property ("name")) != 0) {
176                         if (prop->value() == X_("recenable")) {
177                                 _rec_enable_control->set_state (*child, version);
178                         }
179                 }
180         }
181
182         pending_state = const_cast<XMLNode*> (&node);
183
184         if (_session.state_of_the_state() & Session::Loading) {
185                 _session.StateReady.connect_same_thread (*this, boost::bind (&MidiTrack::set_state_part_two, this));
186         } else {
187                 set_state_part_two ();
188         }
189
190         return 0;
191 }
192
193 XMLNode&
194 MidiTrack::state(bool full_state)
195 {
196         XMLNode& root (Route::state(full_state));
197         XMLNode* freeze_node;
198         char buf[64];
199
200         if (_freeze_record.playlist) {
201                 XMLNode* inode;
202
203                 freeze_node = new XMLNode (X_("freeze-info"));
204                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
205                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
206
207                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
208                         inode = new XMLNode (X_("processor"));
209                         (*i)->id.print (buf, sizeof(buf));
210                         inode->add_property (X_("id"), buf);
211                         inode->add_child_copy ((*i)->state);
212
213                         freeze_node->add_child_nocopy (*inode);
214                 }
215
216                 root.add_child_nocopy (*freeze_node);
217         }
218
219         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
220         root.add_child_nocopy (_rec_enable_control->get_state());
221         root.add_child_nocopy (_diskstream->get_state ());
222
223         root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
224         root.add_property ("note-mode", enum_2_string (_note_mode));
225         root.add_property ("midi-thru", (_midi_thru ? "yes" : "no"));
226         snprintf (buf, sizeof (buf), "%d", (int) _default_channel);
227         root.add_property ("default-channel", buf);
228
229         return root;
230 }
231
232 void
233 MidiTrack::set_state_part_two ()
234 {
235         XMLNode* fnode;
236         XMLProperty* prop;
237         LocaleGuard lg (X_("POSIX"));
238
239         /* This is called after all session state has been restored but before
240            have been made ports and connections are established.
241         */
242
243         if (pending_state == 0) {
244                 return;
245         }
246
247         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
248
249                 _freeze_record.state = Frozen;
250
251                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
252                         delete *i;
253                 }
254                 _freeze_record.processor_info.clear ();
255
256                 if ((prop = fnode->property (X_("playlist"))) != 0) {
257                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
258                         if (pl) {
259                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
260                         } else {
261                                 _freeze_record.playlist.reset();
262                                 _freeze_record.state = NoFreeze;
263                         return;
264                         }
265                 }
266
267                 if ((prop = fnode->property (X_("state"))) != 0) {
268                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
269                 }
270
271                 XMLNodeConstIterator citer;
272                 XMLNodeList clist = fnode->children();
273
274                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
275                         if ((*citer)->name() != X_("processor")) {
276                                 continue;
277                         }
278
279                         if ((prop = (*citer)->property (X_("id"))) == 0) {
280                                 continue;
281                         }
282
283                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
284                                                                                    boost::shared_ptr<Processor>());
285                         frii->id = prop->value ();
286                         _freeze_record.processor_info.push_back (frii);
287                 }
288         }
289
290         if (midi_diskstream ()) {
291                 midi_diskstream()->set_block_size (_session.get_block_size ());
292         }
293
294         return;
295 }
296
297 int
298 MidiTrack::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick,
299                  bool can_record, bool rec_monitors_input, bool& needs_butler)
300 {
301         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
302         if (!lm.locked()) {
303                 return 0;
304         }
305
306         int dret;
307         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
308
309         automation_snapshot (start_frame);
310
311         if (n_outputs().n_total() == 0 && _processors.empty()) {
312                 return 0;
313         }
314
315         if (!_active) {
316                 silence (nframes);
317                 return 0;
318         }
319
320         framepos_t transport_frame = _session.transport_frame();
321
322         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
323                 /* need to do this so that the diskstream sets its
324                    playback distance to zero, thus causing diskstream::commit
325                    to do nothing.
326                    */
327                 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input, needs_butler);
328         }
329
330         _silent = false;
331
332         if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input, needs_butler)) != 0) {
333                 silence (nframes);
334                 return dret;
335         }
336
337         /* special condition applies */
338
339         if (_meter_point == MeterInput) {
340                 _input->process_input (_meter, start_frame, end_frame, nframes);
341         }
342
343         if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
344
345                 /* not actually recording, but we want to hear the input material anyway,
346                    at least potentially (depending on monitoring options)
347                 */
348
349                 passthru (start_frame, end_frame, nframes, 0);
350
351         } else {
352                 /*
353                    XXX is it true that the earlier test on n_outputs()
354                    means that we can avoid checking it again here? i think
355                    so, because changing the i/o configuration of an IO
356                    requires holding the AudioEngine lock, which we hold
357                    while in the process() tree.
358                    */
359
360
361                 /* copy the diskstream data to all output buffers */
362
363                 //const size_t limit = n_process_buffers().n_audio();
364                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
365                 MidiBuffer& mbuf (bufs.get_midi (0));
366
367                 /* we are a MIDI track, so we always start the chain with a single-channel diskstream */
368                 ChanCount c;
369                 c.set_audio (0);
370                 c.set_midi (1);
371                 bufs.set_count (c);
372
373                 diskstream->get_playback (mbuf, start_frame, end_frame);
374
375                 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
376
377                 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
378
379                 /* final argument: don't waste time with automation if we're recording or we've just stopped (yes it can happen) */
380
381                 process_output_buffers (bufs, start_frame, end_frame, nframes,
382                                         (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick,
383                                         (!diskstream->record_enabled() && !_session.transport_stopped()));
384         }
385
386         _main_outs->flush_buffers (nframes, end_frame - start_frame - 1);
387
388         return 0;
389 }
390
391 int
392 MidiTrack::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame,
393                     bool state_changing, bool can_record, bool rec_monitors_input)
394 {
395         int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
396
397         if (ret == 0 && _step_editing) {
398                 push_midi_input_to_step_edit_ringbuffer (nframes);
399         }
400
401         return ret;
402 }
403
404 void
405 MidiTrack::realtime_handle_transport_stopped ()
406 {
407         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
408         if (!lm.locked ()) {
409                 return;
410         }
411
412         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
413                 (*i)->realtime_handle_transport_stopped ();
414         }
415 }
416
417 void
418 MidiTrack::push_midi_input_to_step_edit_ringbuffer (framecnt_t nframes)
419 {
420         PortSet& ports (_input->ports());
421
422         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
423
424                 Buffer& b (p->get_buffer (nframes));
425                 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
426                 assert (mb);
427
428                 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
429
430                         const Evoral::MIDIEvent<framepos_t> ev(*e, false);
431
432                         /* note on, since for step edit, note length is determined
433                            elsewhere 
434                         */
435                         
436                         if (ev.is_note_on()) {
437                                 /* we don't care about the time for this purpose */
438                                 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
439                         }
440                 }
441         }
442 }
443
444 void
445 MidiTrack::write_out_of_band_data (BufferSet& bufs, framepos_t /*start*/, framepos_t /*end*/, framecnt_t nframes)
446 {
447         // Append immediate events
448         MidiBuffer& buf (bufs.get_midi (0));
449         if (_immediate_events.read_space()) {
450                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 has %2 of immediate events to deliver\n", 
451                                                             name(), _immediate_events.read_space()));
452         }
453         _immediate_events.read (buf, 0, 1, nframes-1); // all stamps = 0
454         
455         // MIDI thru: send incoming data "through" output
456         if (_midi_thru && _session.transport_speed() != 0.0f && _input->n_ports().n_midi()) {
457                 buf.merge_in_place (_input->midi(0)->get_midi_buffer(nframes));
458         }
459 }
460
461 int
462 MidiTrack::export_stuff (BufferSet& /*bufs*/, framecnt_t /*nframes*/, framepos_t /*end_frame*/)
463 {
464         return -1;
465 }
466
467 boost::shared_ptr<Region>
468 MidiTrack::bounce (InterThreadInfo& /*itt*/)
469 {
470         throw;
471         // vector<MidiSource*> srcs;
472         // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
473         return boost::shared_ptr<Region> ();
474 }
475
476
477 boost::shared_ptr<Region>
478 MidiTrack::bounce_range (framepos_t /*start*/, framepos_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
479 {
480         throw;
481         //vector<MidiSource*> srcs;
482         //return _session.write_one_track (*this, start, end, false, srcs, itt);
483         return boost::shared_ptr<Region> ();
484 }
485
486 void
487 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
488 {
489 }
490
491 void
492 MidiTrack::unfreeze ()
493 {
494         _freeze_record.state = UnFrozen;
495         FreezeChange (); /* EMIT SIGNAL */
496 }
497
498 void
499 MidiTrack::set_note_mode (NoteMode m)
500 {
501         _note_mode = m;
502         midi_diskstream()->set_note_mode(m);
503 }
504
505 void
506 MidiTrack::midi_panic()
507 {
508         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers panic data\n", name()));
509         for (uint8_t channel = 0; channel <= 0xF; channel++) {
510                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
511                 write_immediate_event(3, ev);
512                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
513                 write_immediate_event(3, ev);
514                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
515                 write_immediate_event(3, ev);
516         }
517 }
518
519 /** \return true on success, false on failure (no buffer space left)
520  */
521 bool
522 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
523 {
524         if (!Evoral::midi_event_is_valid(buf, size)) {
525                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
526                 return false;
527         }
528         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
529         return (_immediate_events.write(0, type, size, buf) == size);
530 }
531
532 void
533 MidiTrack::MidiControl::set_value(double val)
534 {
535         bool valid = false;
536         if (isinf(val)) {
537                 cerr << "MIDIControl value is infinity" << endl;
538         } else if (isnan(val)) {
539                 cerr << "MIDIControl value is NaN" << endl;
540         } else if (val < _list->parameter().min()) {
541                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
542         } else if (val > _list->parameter().max()) {
543                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
544         } else {
545                 valid = true;
546         }
547
548         if (!valid) {
549                 return;
550         }
551
552         assert(val <= _list->parameter().max());
553         if ( ! automation_playback()) {
554                 size_t size = 3;
555                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
556                 switch(_list->parameter().type()) {
557                 case MidiCCAutomation:
558                         ev[0] += MIDI_CMD_CONTROL;
559                         ev[1] = _list->parameter().id();
560                         ev[2] = int(val);
561                         break;
562
563                 case MidiPgmChangeAutomation:
564                         size = 2;
565                         ev[0] += MIDI_CMD_PGM_CHANGE;
566                         ev[1] = int(val);
567                         break;
568
569                 case MidiChannelPressureAutomation:
570                         size = 2;
571                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
572                         ev[1] = int(val);
573                         break;
574
575                 case MidiPitchBenderAutomation:
576                         ev[0] += MIDI_CMD_BENDER;
577                         ev[1] = 0x7F & int(val);
578                         ev[2] = 0x7F & (int(val) >> 7);
579                         break;
580
581                 default:
582                         assert(false);
583                 }
584                 _route->write_immediate_event(size,  ev);
585         }
586
587         AutomationControl::set_value(val);
588 }
589
590 void
591 MidiTrack::set_step_editing (bool yn)
592 {
593         if (_session.record_status() != Session::Disabled) {
594                 return;
595         }
596
597         if (yn != _step_editing) {
598                 _step_editing = yn;
599                 StepEditStatusChange (yn);
600         }
601 }
602
603 void
604 MidiTrack::set_default_channel (uint8_t chn)
605 {
606         _default_channel = std::min ((unsigned int) chn, 15U);
607 }
608
609 void
610 MidiTrack::set_midi_thru (bool yn)
611 {
612         _midi_thru = yn;
613 }
614
615 boost::shared_ptr<SMFSource>
616 MidiTrack::write_source (uint32_t)
617 {
618         return midi_diskstream()->write_source ();
619 }
620
621 void
622 MidiTrack::set_channel_mode (ChannelMode mode, uint16_t mask)
623 {
624         midi_diskstream()->set_channel_mode (mode, mask);
625 }
626
627 ChannelMode
628 MidiTrack::get_channel_mode ()
629 {
630         return midi_diskstream()->get_channel_mode ();
631 }
632
633 uint16_t
634 MidiTrack::get_channel_mask ()
635 {
636         return midi_diskstream()->get_channel_mask ();
637 }
638
639 boost::shared_ptr<MidiPlaylist>
640 MidiTrack::midi_playlist ()
641 {
642         return midi_diskstream()->midi_playlist ();
643 }
644
645 void
646 MidiTrack::diskstream_data_recorded (boost::shared_ptr<MidiBuffer> buf, boost::weak_ptr<MidiSource> src)
647 {
648         DataRecorded (buf, src); /* EMIT SIGNAL */
649 }
650                                
651 bool
652 MidiTrack::should_monitor () const
653 {
654         return true;
655 }
656
657 bool
658 MidiTrack::send_silence () const
659 {
660         return false;
661 }