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