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