Fix 'live' CC sending of bar controllers after loading session (previously only worke...
[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 #include <sigc++/retype.h>
21 #include <sigc++/retype_return.h>
22 #include <sigc++/bind.h>
23
24 #include <pbd/enumwriter.h>
25
26 #include <ardour/midi_track.h>
27 #include <ardour/midi_diskstream.h>
28 #include <ardour/session.h>
29 #include <ardour/io_processor.h>
30 #include <ardour/midi_region.h>
31 #include <ardour/midi_source.h>
32 #include <ardour/route_group_specialized.h>
33 #include <ardour/processor.h>
34 #include <ardour/midi_playlist.h>
35 #include <ardour/panner.h>
36 #include <ardour/utils.h>
37 #include <ardour/buffer_set.h>
38 #include <ardour/meter.h>
39 #include <ardour/midi_events.h>
40
41 #include "i18n.h"
42
43 using namespace std;
44 using namespace ARDOUR;
45 using namespace PBD;
46
47 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
48         : Track (sess, name, flag, mode, DataType::MIDI)
49         , _immediate_events(1024) // FIXME: size?
50 {
51         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
52
53         if (_flags & Hidden) {
54                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
55         } else {
56                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
57         }
58
59         assert(mode != Destructive);
60
61         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name, dflags));
62         _session.add_diskstream (ds);
63
64         set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
65         
66         _declickable = true;
67         _freeze_record.state = NoFreeze;
68         _saved_meter_point = _meter_point;
69         _mode = mode;
70
71         set_input_minimum(ChanCount(DataType::MIDI, 1));
72         set_input_maximum(ChanCount(DataType::MIDI, 1));
73         set_output_minimum(ChanCount(DataType::MIDI, 1));
74         set_output_maximum(ChanCount(DataType::MIDI, 1));
75
76         MoreChannels(ChanCount(DataType::MIDI, 2)); /* EMIT SIGNAL */
77 }
78
79 MidiTrack::MidiTrack (Session& sess, const XMLNode& node)
80         : Track (sess, node)
81         , _immediate_events(1024) // FIXME: size?
82 {
83         _set_state(node, false);
84         
85         set_input_minimum(ChanCount(DataType::MIDI, 1));
86         set_input_maximum(ChanCount(DataType::MIDI, 1));
87         set_output_minimum(ChanCount(DataType::MIDI, 1));
88         set_output_maximum(ChanCount(DataType::MIDI, 1));
89         
90         MoreChannels(ChanCount(DataType::MIDI, 2)); /* EMIT SIGNAL */
91 }
92
93 MidiTrack::~MidiTrack ()
94 {
95 }
96
97
98 int
99 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
100 {
101         _diskstream = ds;
102         _diskstream->set_io (*this);
103         _diskstream->set_destructive (_mode == Destructive);
104
105         _diskstream->set_record_enabled (false);
106         //_diskstream->monitor_input (false);
107
108         ic_connection.disconnect();
109         ic_connection = input_changed.connect (mem_fun (*_diskstream, &MidiDiskstream::handle_input_change));
110
111         DiskstreamChanged (); /* EMIT SIGNAL */
112
113         return 0;
114 }       
115
116 int 
117 MidiTrack::use_diskstream (string name)
118 {
119         boost::shared_ptr<MidiDiskstream> dstream;
120
121         if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream>(_session.diskstream_by_name (name))) == 0) {
122                 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), name) << endmsg;
123                 return -1;
124         }
125         
126         return set_diskstream (dstream);
127 }
128
129 int 
130 MidiTrack::use_diskstream (const PBD::ID& id)
131 {
132         boost::shared_ptr<MidiDiskstream> dstream;
133
134         if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
135                 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
136                 return -1;
137         }
138         
139         return set_diskstream (dstream);
140 }
141
142 boost::shared_ptr<MidiDiskstream>
143 MidiTrack::midi_diskstream() const
144 {
145         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
146 }
147
148 int
149 MidiTrack::set_state (const XMLNode& node)
150 {
151         return _set_state (node, true);
152 }
153
154 int
155 MidiTrack::_set_state (const XMLNode& node, bool call_base)
156 {
157         const XMLProperty *prop;
158         XMLNodeConstIterator iter;
159
160         if (Route::_set_state (node, call_base)) {
161                 return -1;
162         }
163         
164         if ((prop = node.property (X_("mode"))) != 0) {
165                 _mode = TrackMode (string_2_enum (prop->value(), _mode));
166         } else {
167                 _mode = Normal;
168         }
169
170         if ((prop = node.property ("diskstream-id")) == 0) {
171                 
172                 /* some old sessions use the diskstream name rather than the ID */
173
174                 if ((prop = node.property ("diskstream")) == 0) {
175                         fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
176                         /*NOTREACHED*/
177                         return -1;
178                 }
179
180                 if (use_diskstream (prop->value())) {
181                         return -1;
182                 }
183
184         } else {
185                 
186                 PBD::ID id (prop->value());
187                 
188                 if (use_diskstream (id)) {
189                         return -1;
190                 }
191         }
192
193
194         XMLNodeList nlist;
195         XMLNodeConstIterator niter;
196         XMLNode *child;
197
198         nlist = node.children();
199         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
200                 child = *niter;
201
202                 if (child->name() == X_("recenable")) {
203                         _rec_enable_control->set_state (*child);
204                         _session.add_controllable (_rec_enable_control);
205                 }
206         }
207
208         pending_state = const_cast<XMLNode*> (&node);
209
210         _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
211
212         return 0;
213 }
214
215 XMLNode& 
216 MidiTrack::state(bool full_state)
217 {
218         XMLNode& root (Route::state(full_state));
219         XMLNode* freeze_node;
220         char buf[64];
221
222         if (_freeze_record.playlist) {
223                 XMLNode* inode;
224
225                 freeze_node = new XMLNode (X_("freeze-info"));
226                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
227                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
228
229                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
230                         inode = new XMLNode (X_("processor"));
231                         (*i)->id.print (buf, sizeof(buf));
232                         inode->add_property (X_("id"), buf);
233                         inode->add_child_copy ((*i)->state);
234                 
235                         freeze_node->add_child_nocopy (*inode);
236                 }
237
238                 root.add_child_nocopy (*freeze_node);
239         }
240
241         /* Alignment: act as a proxy for the diskstream */
242         
243         XMLNode* align_node = new XMLNode (X_("alignment"));
244         AlignStyle as = _diskstream->alignment_style ();
245         align_node->add_property (X_("style"), enum_2_string (as));
246         root.add_child_nocopy (*align_node);
247
248         root.add_property (X_("mode"), enum_2_string (_mode));
249         
250         /* we don't return diskstream state because we don't
251            own the diskstream exclusively. control of the diskstream
252            state is ceded to the Session, even if we create the
253            diskstream.
254         */
255
256         _diskstream->id().print (buf, sizeof(buf));
257         root.add_property ("diskstream-id", buf);
258         
259         root.add_child_nocopy (_rec_enable_control->get_state());
260
261         return root;
262 }
263
264 void
265 MidiTrack::set_state_part_two ()
266 {
267         XMLNode* fnode;
268         XMLProperty* prop;
269         LocaleGuard lg (X_("POSIX"));
270
271         /* This is called after all session state has been restored but before
272            have been made ports and connections are established.
273         */
274
275         if (pending_state == 0) {
276                 return;
277         }
278
279         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
280
281                 
282                 _freeze_record.have_mementos = false;
283                 _freeze_record.state = Frozen;
284                 
285                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
286                         delete *i;
287                 }
288                 _freeze_record.processor_info.clear ();
289                 
290                 if ((prop = fnode->property (X_("playlist"))) != 0) {
291                         boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
292                         if (pl) {
293                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
294                         } else {
295                                 _freeze_record.playlist.reset();
296                                 _freeze_record.state = NoFreeze;
297                         return;
298                         }
299                 }
300                 
301                 if ((prop = fnode->property (X_("state"))) != 0) {
302                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
303                 }
304                 
305                 XMLNodeConstIterator citer;
306                 XMLNodeList clist = fnode->children();
307                 
308                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
309                         if ((*citer)->name() != X_("processor")) {
310                                 continue;
311                         }
312                         
313                         if ((prop = (*citer)->property (X_("id"))) == 0) {
314                                 continue;
315                         }
316                         
317                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
318                                                                                    boost::shared_ptr<Processor>());
319                         frii->id = prop->value ();
320                         _freeze_record.processor_info.push_back (frii);
321                 }
322         }
323
324         /* Alignment: act as a proxy for the diskstream */
325
326         if ((fnode = find_named_node (*pending_state, X_("alignment"))) != 0) {
327
328                 if ((prop = fnode->property (X_("style"))) != 0) {
329
330                         /* fix for older sessions from before EnumWriter */
331
332                         string pstr;
333
334                         if (prop->value() == "capture") {
335                                 pstr = "CaptureTime";
336                         } else if (prop->value() == "existing") {
337                                 pstr = "ExistingMaterial";
338                         } else {
339                                 pstr = prop->value();
340                         }
341
342                         AlignStyle as = AlignStyle (string_2_enum (pstr, as));
343                         _diskstream->set_persistent_align_style (as);
344                 }
345         }
346         return;
347 }       
348
349 int 
350 MidiTrack::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
351                      bool session_state_changing, bool can_record, bool rec_monitors_input)
352 {
353         if (n_outputs().n_midi() == 0) {
354                 //return 0;
355                 throw; // FIXME
356         }
357
358         if (!_active) {
359                 silence (nframes, offset);
360                 //return 0; // FIXME
361         }
362
363         if (session_state_changing) {
364
365                 /* XXX is this safe to do against transport state changes? */
366
367                 passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
368                 return 0;
369         }
370
371         midi_diskstream()->check_record_status (start_frame, nframes, can_record);
372
373         bool send_silence;
374         
375         if (_have_internal_generator) {
376                 /* since the instrument has no input streams,
377                    there is no reason to send any signal
378                    into the route.
379                 */
380                 send_silence = true;
381         } else {
382
383                 if (Config->get_auto_input()) {
384                         if (Config->get_monitoring_model() == SoftwareMonitoring) {
385                                 send_silence = false;
386                         } else {
387                                 send_silence = true;
388                         }
389                 } else {
390                         if (_diskstream->record_enabled()) {
391                                 if (Config->get_monitoring_model() == SoftwareMonitoring) {
392                                         send_silence = false;
393                                 } else {
394                                         send_silence = true;
395                                 }
396                         } else {
397                                 send_silence = true;
398                         }
399                 }
400         }
401
402         apply_gain_automation = false;
403
404         if (send_silence) {
405                 
406                 /* if we're sending silence, but we want the meters to show levels for the signal,
407                    meter right here.
408                 */
409                 
410                 if (_have_internal_generator) {
411                         passthru_silence (start_frame, end_frame, nframes, offset, 0, true);
412                 } else {
413                         if (_meter_point == MeterInput) {
414                                 just_meter_input (start_frame, end_frame, nframes, offset);
415                         }
416                         passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
417                 }
418
419         } else {
420         
421                 /* we're sending signal, but we may still want to meter the input. 
422                  */
423
424                 passthru (start_frame, end_frame, nframes, offset, 0, (_meter_point == MeterInput));
425         }
426
427         return 0;
428 }
429
430 int
431 MidiTrack::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
432                   bool can_record, bool rec_monitors_input)
433 {
434         int dret;
435         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
436         
437         {
438                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
439                 if (lm.locked()) {
440                         // automation snapshot can also be called from the non-rt context
441                         // and it uses the redirect list, so we take the lock out here
442                         automation_snapshot (start_frame);
443                 }
444         }
445
446         if (n_outputs().n_total() == 0 && _processors.empty()) {
447                 return 0;
448         }
449
450         if (!_active) {
451                 silence (nframes, offset);
452                 return 0;
453         }
454
455         nframes_t transport_frame = _session.transport_frame();
456
457         if ((nframes = check_initial_delay (nframes, offset, transport_frame)) == 0) {
458                 /* need to do this so that the diskstream sets its
459                    playback distance to zero, thus causing diskstream::commit
460                    to do nothing.
461                    */
462                 return diskstream->process (transport_frame, 0, 0, can_record, rec_monitors_input);
463         } 
464
465         _silent = false;
466
467         if ((dret = diskstream->process (transport_frame, nframes, offset, can_record, rec_monitors_input)) != 0) {
468
469                 silence (nframes, offset);
470
471                 return dret;
472         }
473
474         /* special condition applies */
475
476         if (_meter_point == MeterInput) {
477                 just_meter_input (start_frame, end_frame, nframes, offset);
478         }
479
480         if (diskstream->record_enabled() && !can_record && !Config->get_auto_input()) {
481
482                 /* not actually recording, but we want to hear the input material anyway,
483                    at least potentially (depending on monitoring options)
484                    */
485
486                 passthru (start_frame, end_frame, nframes, offset, 0, true);
487
488         } else {
489                 /*
490                    XXX is it true that the earlier test on n_outputs()
491                    means that we can avoid checking it again here? i think
492                    so, because changing the i/o configuration of an IO
493                    requires holding the AudioEngine lock, which we hold
494                    while in the process() tree.
495                    */
496
497
498                 /* copy the diskstream data to all output buffers */
499
500                 //const size_t limit = n_process_buffers().n_audio();
501                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
502
503                 diskstream->get_playback(bufs.get_midi(0), start_frame, end_frame);
504
505                 process_output_buffers (bufs, start_frame, end_frame, nframes, offset,
506                                 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick, (_meter_point != MeterInput));
507         
508         }
509
510         return 0;
511 }
512
513 int
514 MidiTrack::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
515                          bool can_record, bool rec_monitors_input)
516 {
517         if (n_outputs().n_midi() == 0 && _processors.empty()) {
518                 return 0;
519         }
520
521         if (!_active) {
522                 silence (nframes, offset);
523                 return 0;
524         }
525
526         _silent = true;
527         apply_gain_automation = false;
528
529         silence (nframes, offset);
530
531         return midi_diskstream()->process (_session.transport_frame() + offset, nframes, offset, can_record, rec_monitors_input);
532 }
533
534 void
535 MidiTrack::process_output_buffers (BufferSet& bufs,
536                                nframes_t start_frame, nframes_t end_frame, 
537                                nframes_t nframes, nframes_t offset, bool with_processors, int declick,
538                                bool meter)
539 {
540         /* There's no such thing as a MIDI bus for the time being.
541          * We'll do all the MIDI route work here for now, but the long-term goal is to have
542          * Route::process_output_buffers handle everything */
543         
544         if (meter && (_meter_point == MeterInput || _meter_point == MeterPreFader)) {
545                 _meter->run(bufs, start_frame, end_frame, nframes, offset);
546         }
547
548         // Run all processors
549         if (with_processors) {
550                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
551                 if (rm.locked()) {
552                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
553                                 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
554                         }
555                 } 
556         }
557         
558         if (meter && (_meter_point == MeterPostFader)) {
559                 _meter->run(bufs, start_frame, end_frame, nframes, offset);
560         }
561         
562         // Main output stage
563         if (muted()) {
564                 IO::silence(nframes, offset);
565         } else {
566
567                 MidiBuffer& output_buf = bufs.get_midi(0);
568                 write_controller_messages(output_buf, start_frame, end_frame, nframes, offset);
569
570                 deliver_output(bufs, start_frame, end_frame, nframes, offset);
571         }
572 }
573
574 void
575 MidiTrack::write_controller_messages(MidiBuffer& output_buf, nframes_t start_frame, nframes_t end_frame, 
576                                nframes_t nframes, nframes_t offset)
577 {
578         BufferSet& mix_buffers = _session.get_mix_buffers(ChanCount(DataType::MIDI, 2));
579
580         /* FIXME: this could be more realtimey */
581
582         // Write immediate events (UI controls)
583         MidiBuffer& cc_buf = mix_buffers.get_midi(0);
584         cc_buf.silence(nframes, offset);
585         MidiEvent ev;
586         ev.size = 3; // CC = 3 bytes
587         Byte buf[ev.size];
588         buf[0] = MIDI_CMD_CONTROL;
589         ev.buffer = buf;
590
591         // Write controller automation
592         if (_session.transport_rolling()) {
593                 for (Controls::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
594                         const boost::shared_ptr<AutomationList> list = (*i).second->list();
595
596                         if ( (!list->automation_playback())
597                                         || (list->parameter().type() != MidiCCAutomation))
598                                 continue;
599
600                         double start = start_frame;
601                         double x, y;
602                         while ((*i).second->list()->rt_safe_earliest_event(start, end_frame, x, y)) {
603                                 assert(x >= start_frame);
604                                 assert(x <= end_frame);
605
606                                 const nframes_t stamp = (nframes_t)floor(x - start_frame);
607                                 assert(stamp < nframes);
608
609                                 assert(y >= 0.0);
610                                 assert(y <= 127.0);
611
612                                 ev.time = stamp;
613                                 ev.buffer[1] = (Byte)list->parameter().id();
614                                 ev.buffer[2] = (Byte)y;
615
616                                 cc_buf.push_back(ev);
617
618                                 start = x;
619                         }
620                 }
621         }
622
623         /* FIXME: too much copying! */
624
625         // Merge cc buf into output
626         if (cc_buf.size() > 0) {
627
628                 // Both CC and route, must merge
629                 if (output_buf.size() > 0) {
630
631                         MidiBuffer& mix_buf = mix_buffers.get_midi(1);
632                         mix_buf.merge(output_buf, cc_buf);
633                         output_buf.copy(mix_buf);
634
635                 } else {
636                         output_buf.copy(cc_buf);
637                 }
638         }
639
640         // Append immediate events (UI controls)
641         _immediate_events.read(output_buf, 0, 0, offset + nframes-1); // all stamps = 0
642 }
643
644 int
645 MidiTrack::export_stuff (BufferSet& bufs, nframes_t nframes, nframes_t end_frame)
646 {
647         return -1;
648 }
649
650 void
651 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
652 {
653         Route::set_latency_delay (longest_session_latency);
654         _diskstream->set_roll_delay (_roll_delay);
655 }
656
657 void
658 MidiTrack::bounce (InterThreadInfo& itt)
659 {
660         throw;
661         //vector<MidiSource*> srcs;
662         //_session.write_one_midi_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
663 }
664
665
666 void
667 MidiTrack::bounce_range (nframes_t start, nframes_t end, InterThreadInfo& itt)
668 {
669         throw;
670         //vector<MidiSource*> srcs;
671         //_session.write_one_midi_track (*this, start, end, false, srcs, itt);
672 }
673
674 void
675 MidiTrack::freeze (InterThreadInfo& itt)
676 {
677 }
678
679 void
680 MidiTrack::unfreeze ()
681 {
682         _freeze_record.state = UnFrozen;
683         FreezeChange (); /* EMIT SIGNAL */
684 }
685
686 int
687 MidiTrack::set_mode (TrackMode m)
688 {
689         assert(_diskstream);
690
691         if (m != _mode) {
692
693                 if (_diskstream->set_destructive (m == Destructive)) {
694                         return -1;
695                 }
696
697                 _mode = m;
698                 
699                 TrackModeChanged (); /* EMIT SIGNAL */
700         }
701
702         return 0;
703 }
704         
705 /** \return true on success, false on failure (no buffer space left)
706  */
707 bool
708 MidiTrack::write_immediate_event(size_t size, const Byte* buf)
709 {
710         return (_immediate_events.write(0, size, buf) == size);
711 }
712
713 void
714 MidiTrack::MidiControl::set_value(float val)
715 {
716         assert(val >= 0);
717         assert(val <= 127.0);
718
719         if ( ! _list->automation_playback()) {
720                 Byte ev[3] = { MIDI_CMD_CONTROL, _list->parameter().id(), (int)val };
721                 _route->write_immediate_event(3,  ev);
722         }
723
724         AutomationControl::set_value(val);
725
726