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