d81f1f2cefd063b3a56385bf7fed00a68b62d1f7
[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         PortCountChanged(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         PortCountChanged(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         // No destructive MIDI tracks (yet?)
165         _mode = Normal;
166         
167         if ((prop = node.property (X_("note-mode"))) != 0) {
168                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
169         } else {
170                 _note_mode = Sustained;
171         }
172
173         if ((prop = node.property ("diskstream-id")) == 0) {
174                 
175                 /* some old sessions use the diskstream name rather than the ID */
176
177                 if ((prop = node.property ("diskstream")) == 0) {
178                         fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
179                         /*NOTREACHED*/
180                         return -1;
181                 }
182
183                 if (use_diskstream (prop->value())) {
184                         return -1;
185                 }
186
187         } else {
188                 
189                 PBD::ID id (prop->value());
190                 
191                 if (use_diskstream (id)) {
192                         return -1;
193                 }
194         }
195
196
197         XMLNodeList nlist;
198         XMLNodeConstIterator niter;
199         XMLNode *child;
200
201         nlist = node.children();
202         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
203                 child = *niter;
204
205                 if (child->name() == X_("recenable")) {
206                         _rec_enable_control->set_state (*child);
207                         _session.add_controllable (_rec_enable_control);
208                 }
209         }
210
211         pending_state = const_cast<XMLNode*> (&node);
212
213         _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
214
215         return 0;
216 }
217
218 XMLNode& 
219 MidiTrack::state(bool full_state)
220 {
221         XMLNode& root (Route::state(full_state));
222         XMLNode* freeze_node;
223         char buf[64];
224
225         if (_freeze_record.playlist) {
226                 XMLNode* inode;
227
228                 freeze_node = new XMLNode (X_("freeze-info"));
229                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
230                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
231
232                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
233                         inode = new XMLNode (X_("processor"));
234                         (*i)->id.print (buf, sizeof(buf));
235                         inode->add_property (X_("id"), buf);
236                         inode->add_child_copy ((*i)->state);
237                 
238                         freeze_node->add_child_nocopy (*inode);
239                 }
240
241                 root.add_child_nocopy (*freeze_node);
242         }
243
244         /* Alignment: act as a proxy for the diskstream */
245         
246         XMLNode* align_node = new XMLNode (X_("alignment"));
247         AlignStyle as = _diskstream->alignment_style ();
248         align_node->add_property (X_("style"), enum_2_string (as));
249         root.add_child_nocopy (*align_node);
250
251         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
252         
253         /* we don't return diskstream state because we don't
254            own the diskstream exclusively. control of the diskstream
255            state is ceded to the Session, even if we create the
256            diskstream.
257         */
258
259         _diskstream->id().print (buf, sizeof(buf));
260         root.add_property ("diskstream-id", buf);
261         
262         root.add_child_nocopy (_rec_enable_control->get_state());
263
264         return root;
265 }
266
267 void
268 MidiTrack::set_state_part_two ()
269 {
270         XMLNode* fnode;
271         XMLProperty* prop;
272         LocaleGuard lg (X_("POSIX"));
273
274         /* This is called after all session state has been restored but before
275            have been made ports and connections are established.
276         */
277
278         if (pending_state == 0) {
279                 return;
280         }
281
282         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
283
284                 
285                 _freeze_record.have_mementos = false;
286                 _freeze_record.state = Frozen;
287                 
288                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
289                         delete *i;
290                 }
291                 _freeze_record.processor_info.clear ();
292                 
293                 if ((prop = fnode->property (X_("playlist"))) != 0) {
294                         boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
295                         if (pl) {
296                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
297                         } else {
298                                 _freeze_record.playlist.reset();
299                                 _freeze_record.state = NoFreeze;
300                         return;
301                         }
302                 }
303                 
304                 if ((prop = fnode->property (X_("state"))) != 0) {
305                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
306                 }
307                 
308                 XMLNodeConstIterator citer;
309                 XMLNodeList clist = fnode->children();
310                 
311                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
312                         if ((*citer)->name() != X_("processor")) {
313                                 continue;
314                         }
315                         
316                         if ((prop = (*citer)->property (X_("id"))) == 0) {
317                                 continue;
318                         }
319                         
320                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
321                                                                                    boost::shared_ptr<Processor>());
322                         frii->id = prop->value ();
323                         _freeze_record.processor_info.push_back (frii);
324                 }
325         }
326
327         /* Alignment: act as a proxy for the diskstream */
328
329         if ((fnode = find_named_node (*pending_state, X_("alignment"))) != 0) {
330
331                 if ((prop = fnode->property (X_("style"))) != 0) {
332
333                         /* fix for older sessions from before EnumWriter */
334
335                         string pstr;
336
337                         if (prop->value() == "capture") {
338                                 pstr = "CaptureTime";
339                         } else if (prop->value() == "existing") {
340                                 pstr = "ExistingMaterial";
341                         } else {
342                                 pstr = prop->value();
343                         }
344
345                         AlignStyle as = AlignStyle (string_2_enum (pstr, as));
346                         _diskstream->set_persistent_align_style (as);
347                 }
348         }
349         return;
350 }       
351
352 int 
353 MidiTrack::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
354                      bool session_state_changing, bool can_record, bool rec_monitors_input)
355 {
356         if (n_outputs().n_midi() == 0) {
357                 return 0;
358         }
359
360         if (!_active) {
361                 silence (nframes, offset);
362         }
363
364         if (session_state_changing) {
365
366                 /* XXX is this safe to do against transport state changes? */
367
368                 passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
369                 return 0;
370         }
371
372         midi_diskstream()->check_record_status (start_frame, nframes, can_record);
373
374         bool send_silence;
375         
376         if (_have_internal_generator) {
377                 /* since the instrument has no input streams,
378                    there is no reason to send any signal
379                    into the route.
380                 */
381                 send_silence = true;
382         } else {
383
384                 if (Config->get_auto_input()) {
385                         if (Config->get_monitoring_model() == SoftwareMonitoring) {
386                                 send_silence = false;
387                         } else {
388                                 send_silence = true;
389                         }
390                 } else {
391                         if (_diskstream->record_enabled()) {
392                                 if (Config->get_monitoring_model() == SoftwareMonitoring) {
393                                         send_silence = false;
394                                 } else {
395                                         send_silence = true;
396                                 }
397                         } else {
398                                 send_silence = true;
399                         }
400                 }
401         }
402
403         apply_gain_automation = false;
404
405         if (send_silence) {
406                 
407                 /* if we're sending silence, but we want the meters to show levels for the signal,
408                    meter right here.
409                 */
410                 
411                 if (_have_internal_generator) {
412                         passthru_silence (start_frame, end_frame, nframes, offset, 0, true);
413                 } else {
414                         if (_meter_point == MeterInput) {
415                                 just_meter_input (start_frame, end_frame, nframes, offset);
416                         }
417                         passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
418                 }
419
420         } else {
421         
422                 /* we're sending signal, but we may still want to meter the input. 
423                  */
424
425                 passthru (start_frame, end_frame, nframes, offset, 0, (_meter_point == MeterInput));
426         }
427
428         return 0;
429 }
430
431 int
432 MidiTrack::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
433                   bool can_record, bool rec_monitors_input)
434 {
435         int dret;
436         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
437         
438         {
439                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
440                 if (lm.locked()) {
441                         // automation snapshot can also be called from the non-rt context
442                         // and it uses the redirect list, so we take the lock out here
443                         automation_snapshot (start_frame);
444                 }
445         }
446
447         if (n_outputs().n_total() == 0 && _processors.empty()) {
448                 return 0;
449         }
450
451         if (!_active) {
452                 silence (nframes, offset);
453                 return 0;
454         }
455
456         nframes_t transport_frame = _session.transport_frame();
457
458         if ((nframes = check_initial_delay (nframes, offset, transport_frame)) == 0) {
459                 /* need to do this so that the diskstream sets its
460                    playback distance to zero, thus causing diskstream::commit
461                    to do nothing.
462                    */
463                 return diskstream->process (transport_frame, 0, 0, can_record, rec_monitors_input);
464         } 
465
466         _silent = false;
467
468         if ((dret = diskstream->process (transport_frame, nframes, offset, can_record, rec_monitors_input)) != 0) {
469
470                 silence (nframes, offset);
471
472                 return dret;
473         }
474
475         /* special condition applies */
476
477         if (_meter_point == MeterInput) {
478                 just_meter_input (start_frame, end_frame, nframes, offset);
479         }
480
481         if (diskstream->record_enabled() && !can_record && !Config->get_auto_input()) {
482
483                 /* not actually recording, but we want to hear the input material anyway,
484                    at least potentially (depending on monitoring options)
485                    */
486
487                 passthru (start_frame, end_frame, nframes, offset, 0, true);
488
489         } else {
490                 /*
491                    XXX is it true that the earlier test on n_outputs()
492                    means that we can avoid checking it again here? i think
493                    so, because changing the i/o configuration of an IO
494                    requires holding the AudioEngine lock, which we hold
495                    while in the process() tree.
496                    */
497
498
499                 /* copy the diskstream data to all output buffers */
500
501                 //const size_t limit = n_process_buffers().n_audio();
502                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
503
504                 diskstream->get_playback(bufs.get_midi(0), start_frame, end_frame);
505
506                 process_output_buffers (bufs, start_frame, end_frame, nframes, offset,
507                                 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick, (_meter_point != MeterInput));
508         
509         }
510
511         return 0;
512 }
513
514 int
515 MidiTrack::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
516                          bool can_record, bool rec_monitors_input)
517 {
518         if (n_outputs().n_midi() == 0 && _processors.empty()) {
519                 return 0;
520         }
521
522         if (!_active) {
523                 silence (nframes, offset);
524                 return 0;
525         }
526
527         _silent = true;
528         apply_gain_automation = false;
529
530         silence (nframes, offset);
531
532         return midi_diskstream()->process (_session.transport_frame() + offset, nframes, offset, can_record, rec_monitors_input);
533 }
534
535 void
536 MidiTrack::process_output_buffers (BufferSet& bufs,
537                                nframes_t start_frame, nframes_t end_frame, 
538                                nframes_t nframes, nframes_t offset, bool with_processors, int declick,
539                                bool meter)
540 {
541         /* There's no such thing as a MIDI bus for the time being.
542          * We'll do all the MIDI route work here for now, but the long-term goal is to have
543          * Route::process_output_buffers handle everything */
544         
545         if (meter && (_meter_point == MeterInput || _meter_point == MeterPreFader)) {
546                 _meter->run(bufs, start_frame, end_frame, nframes, offset);
547         }
548
549         // Run all processors
550         if (with_processors) {
551                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
552                 if (rm.locked()) {
553                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
554                                 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
555                         }
556                 } 
557         }
558         
559         if (meter && (_meter_point == MeterPostFader)) {
560                 _meter->run(bufs, start_frame, end_frame, nframes, offset);
561         }
562         
563         // Main output stage
564         if (muted()) {
565                 IO::silence(nframes, offset);
566         } else {
567
568                 MidiBuffer& output_buf = bufs.get_midi(0);
569                 write_controller_messages(output_buf, start_frame, end_frame, nframes, offset);
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         
586         Byte buf[3]; // CC = 3 bytes
587         buf[0] = MIDI_CMD_CONTROL;
588         MidiEvent ev(0, 3, buf, false);
589
590         // Write track controller automation
591 #if 0
592         // This now lives in MidiModel.  Any need for track automation like this?
593         // Relative Velocity?
594         if (_session.transport_rolling()) {
595                 for (Controls::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
596                         const boost::shared_ptr<AutomationList> list = (*i).second->list();
597
598                         if ( (!list->automation_playback())
599                                         || (list->parameter().type() != MidiCCAutomation))
600                                 continue;
601
602                         double start = start_frame;
603                         double x, y;
604                         while ((*i).second->list()->rt_safe_earliest_event(start, end_frame, x, y)) {
605                                 assert(x >= start_frame);
606                                 assert(x <= end_frame);
607
608                                 const nframes_t stamp = (nframes_t)floor(x - start_frame);
609                                 assert(stamp < nframes);
610
611                                 assert(y >= 0.0);
612                                 assert(y <= 127.0);
613
614                                 ev.time() = stamp;
615                                 ev.buffer()[1] = (Byte)list->parameter().id();
616                                 ev.buffer()[2] = (Byte)y;
617
618                                 cc_buf.push_back(ev);
619
620                                 start = x + 1; // FIXME?  maybe?
621                         }
622                 }
623         }
624
625         /* FIXME: too much copying! */
626
627         // Merge cc buf into output
628         if (cc_buf.size() > 0) {
629
630                 // Both CC and route, must merge
631                 if (output_buf.size() > 0) {
632
633                         MidiBuffer& mix_buf = mix_buffers.get_midi(1);
634                         mix_buf.merge(output_buf, cc_buf);
635                         output_buf.copy(mix_buf);
636
637                 } else {
638                         output_buf.copy(cc_buf);
639                 }
640         }
641 #endif
642
643         // Append immediate events (UI controls)
644         _immediate_events.read(output_buf, 0, 0, offset + nframes-1); // all stamps = 0
645 }
646
647 int
648 MidiTrack::export_stuff (BufferSet& bufs, nframes_t nframes, nframes_t end_frame)
649 {
650         return -1;
651 }
652
653 void
654 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
655 {
656         Route::set_latency_delay (longest_session_latency);
657         _diskstream->set_roll_delay (_roll_delay);
658 }
659
660 void
661 MidiTrack::bounce (InterThreadInfo& itt)
662 {
663         throw;
664         //vector<MidiSource*> srcs;
665         //_session.write_one_midi_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
666 }
667
668
669 void
670 MidiTrack::bounce_range (nframes_t start, nframes_t end, InterThreadInfo& itt)
671 {
672         throw;
673         //vector<MidiSource*> srcs;
674         //_session.write_one_midi_track (*this, start, end, false, srcs, itt);
675 }
676
677 void
678 MidiTrack::freeze (InterThreadInfo& itt)
679 {
680 }
681
682 void
683 MidiTrack::unfreeze ()
684 {
685         _freeze_record.state = UnFrozen;
686         FreezeChange (); /* EMIT SIGNAL */
687 }
688
689 void
690 MidiTrack::set_note_mode (NoteMode m)
691 {
692         _note_mode = m;
693         midi_diskstream()->set_note_mode(m);
694 }
695
696 /** \return true on success, false on failure (no buffer space left)
697  */
698 bool
699 MidiTrack::write_immediate_event(size_t size, const Byte* buf)
700 {
701         return (_immediate_events.write(0, size, buf) == size);
702 }
703
704 void
705 MidiTrack::MidiControl::set_value(float val)
706 {
707         assert(val >= 0);
708         assert(val <= 127.0);
709
710         if ( ! _list->automation_playback()) {
711                 Byte ev[3] = { MIDI_CMD_CONTROL, _list->parameter().id(), (int)val };
712                 _route->write_immediate_event(3,  ev);
713         }
714
715         AutomationControl::set_value(val);
716
717