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