52a0cac27e24c8160a83fa66c42e0fbb3455b08f
[ardour.git] / libs / ardour / midi_track.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3     Author: David Robillard
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
20 #include "pbd/error.h"
21
22 #include "pbd/enumwriter.h"
23 #include "pbd/convert.h"
24 #include "midi++/events.h"
25 #include "evoral/midi_util.h"
26
27 #include "ardour/amp.h"
28 #include "ardour/buffer_set.h"
29 #include "ardour/debug.h"
30 #include "ardour/delivery.h"
31 #include "ardour/io_processor.h"
32 #include "ardour/meter.h"
33 #include "ardour/midi_diskstream.h"
34 #include "ardour/midi_playlist.h"
35 #include "ardour/midi_port.h"
36 #include "ardour/midi_region.h"
37 #include "ardour/midi_source.h"
38 #include "ardour/midi_track.h"
39 #include "ardour/panner.h"
40 #include "ardour/port.h"
41 #include "ardour/processor.h"
42 #include "ardour/route_group_specialized.h"
43 #include "ardour/session.h"
44 #include "ardour/session_playlists.h"
45 #include "ardour/utils.h"
46
47 #include "i18n.h"
48
49 using namespace std;
50 using namespace ARDOUR;
51 using namespace PBD;
52
53 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
54         : Track (sess, name, flag, mode, DataType::MIDI)
55         , _immediate_events(1024) // FIXME: size?
56         , _step_edit_ring_buffer(64) // FIXME: size?
57         , _note_mode(Sustained)
58         , _step_editing (false)
59         , _midi_thru (true)
60 {
61 }
62
63 MidiTrack::~MidiTrack ()
64 {
65 }
66
67 void
68 MidiTrack::use_new_diskstream ()
69 {
70         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
71
72         if (_flags & Hidden) {
73                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
74         } else {
75                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
76         }
77
78         assert(_mode != Destructive);
79
80         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
81         ds->do_refill_with_alloc ();
82         ds->set_block_size (_session.get_block_size ());
83
84         set_diskstream (ds);
85 }
86
87 void
88 MidiTrack::set_record_enabled (bool yn, void *src)
89 {
90         if (_step_editing) {
91                 return;
92         }
93
94         Track::set_record_enabled (yn, src);
95 }
96
97 void
98 MidiTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
99 {
100         Track::set_diskstream (ds);
101
102         _diskstream->set_track (this);
103         _diskstream->set_destructive (_mode == Destructive);
104
105         _diskstream->set_record_enabled (false);
106         //_diskstream->monitor_input (false);
107
108         _diskstream_data_recorded_connection.disconnect ();
109         boost::shared_ptr<MidiDiskstream> mds = boost::dynamic_pointer_cast<MidiDiskstream> (ds);
110         mds->DataRecorded.connect_same_thread (
111                 _diskstream_data_recorded_connection,
112                 boost::bind (&MidiTrack::diskstream_data_recorded, this, _1, _2));
113
114         DiskstreamChanged (); /* EMIT SIGNAL */
115 }
116
117 boost::shared_ptr<MidiDiskstream>
118 MidiTrack::midi_diskstream() const
119 {
120         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
121 }
122
123 int
124 MidiTrack::set_state (const XMLNode& node, int version)
125 {
126         return _set_state (node, version, true);
127 }
128
129 int
130 MidiTrack::_set_state (const XMLNode& node, int version, bool call_base)
131 {
132         const XMLProperty *prop;
133         XMLNodeConstIterator iter;
134
135         if (Route::_set_state (node, version, call_base)) {
136                 return -1;
137         }
138
139         // No destructive MIDI tracks (yet?)
140         _mode = Normal;
141
142         if ((prop = node.property (X_("note-mode"))) != 0) {
143                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
144         } else {
145                 _note_mode = Sustained;
146         }
147
148         if ((prop = node.property ("midi-thru")) != 0) {
149                 set_midi_thru (prop->value() == "yes");
150         }
151
152         XMLNodeList nlist;
153         XMLNodeConstIterator niter;
154         XMLNode *child;
155
156         nlist = node.children();
157
158         if (version >= 3000) {
159                 if ((child = find_named_node (node, X_("Diskstream"))) != 0) {
160                         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *child));
161                         ds->do_refill_with_alloc ();
162                         set_diskstream (ds);
163                 }
164         }
165
166         /* set rec-enable control *AFTER* setting up diskstream, because it may
167            want to operate on the diskstream as it sets its own state
168         */
169
170         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
171                 child = *niter;
172
173                 if (child->name() == Controllable::xml_node_name && (prop = child->property ("name")) != 0) {
174                         if (prop->value() == X_("recenable")) {
175                                 _rec_enable_control->set_state (*child, version);
176                         }
177                 }
178         }
179
180         pending_state = const_cast<XMLNode*> (&node);
181
182         if (_session.state_of_the_state() & Session::Loading) {
183                 _session.StateReady.connect_same_thread (
184                         *this, boost::bind (&MidiTrack::set_state_part_two, this));
185         } else {
186                 set_state_part_two ();
187         }
188
189         return 0;
190 }
191
192 XMLNode&
193 MidiTrack::state(bool full_state)
194 {
195         XMLNode& root (Route::state(full_state));
196         XMLNode* freeze_node;
197         char buf[64];
198
199         if (_freeze_record.playlist) {
200                 XMLNode* inode;
201
202                 freeze_node = new XMLNode (X_("freeze-info"));
203                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
204                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
205
206                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
207                         inode = new XMLNode (X_("processor"));
208                         (*i)->id.print (buf, sizeof(buf));
209                         inode->add_property (X_("id"), buf);
210                         inode->add_child_copy ((*i)->state);
211
212                         freeze_node->add_child_nocopy (*inode);
213                 }
214
215                 root.add_child_nocopy (*freeze_node);
216         }
217
218         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
219         root.add_child_nocopy (_rec_enable_control->get_state());
220         root.add_child_nocopy (_diskstream->get_state ());
221
222         root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
223         root.add_property ("note-mode", enum_2_string (_note_mode));
224         root.add_property ("midi-thru", (_midi_thru ? "yes" : "no"));
225
226         return root;
227 }
228
229 void
230 MidiTrack::set_state_part_two ()
231 {
232         XMLNode* fnode;
233         XMLProperty* prop;
234         LocaleGuard lg (X_("POSIX"));
235
236         /* This is called after all session state has been restored but before
237            have been made ports and connections are established.
238         */
239
240         if (pending_state == 0) {
241                 return;
242         }
243
244         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
245
246                 _freeze_record.state = Frozen;
247
248                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
249                         delete *i;
250                 }
251                 _freeze_record.processor_info.clear ();
252
253                 if ((prop = fnode->property (X_("playlist"))) != 0) {
254                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
255                         if (pl) {
256                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
257                         } else {
258                                 _freeze_record.playlist.reset();
259                                 _freeze_record.state = NoFreeze;
260                         return;
261                         }
262                 }
263
264                 if ((prop = fnode->property (X_("state"))) != 0) {
265                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
266                 }
267
268                 XMLNodeConstIterator citer;
269                 XMLNodeList clist = fnode->children();
270
271                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
272                         if ((*citer)->name() != X_("processor")) {
273                                 continue;
274                         }
275
276                         if ((prop = (*citer)->property (X_("id"))) == 0) {
277                                 continue;
278                         }
279
280                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
281                                                                                    boost::shared_ptr<Processor>());
282                         frii->id = prop->value ();
283                         _freeze_record.processor_info.push_back (frii);
284                 }
285         }
286
287         if (midi_diskstream ()) {
288                 midi_diskstream()->set_block_size (_session.get_block_size ());
289         }
290
291         return;
292 }
293
294 int
295 MidiTrack::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick,
296                  bool can_record, bool rec_monitors_input, bool& needs_butler)
297 {
298         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
299         if (!lm.locked()) {
300                 return 0;
301         }
302
303         int dret;
304         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
305
306         automation_snapshot (start_frame);
307
308         if (n_outputs().n_total() == 0 && _processors.empty()) {
309                 return 0;
310         }
311
312         if (!_active) {
313                 silence (nframes);
314                 return 0;
315         }
316
317         framepos_t transport_frame = _session.transport_frame();
318
319         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
320                 /* need to do this so that the diskstream sets its
321                    playback distance to zero, thus causing diskstream::commit
322                    to do nothing.
323                    */
324                 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input, needs_butler);
325         }
326
327         _silent = false;
328
329         if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input, needs_butler)) != 0) {
330                 silence (nframes);
331                 return dret;
332         }
333
334         /* special condition applies */
335
336         if (_meter_point == MeterInput) {
337                 _input->process_input (_meter, start_frame, end_frame, nframes);
338         }
339
340         if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
341
342                 /* not actually recording, but we want to hear the input material anyway,
343                    at least potentially (depending on monitoring options)
344                 */
345
346                 passthru (start_frame, end_frame, nframes, 0);
347
348         } else {
349                 /*
350                    XXX is it true that the earlier test on n_outputs()
351                    means that we can avoid checking it again here? i think
352                    so, because changing the i/o configuration of an IO
353                    requires holding the AudioEngine lock, which we hold
354                    while in the process() tree.
355                    */
356
357
358                 /* copy the diskstream data to all output buffers */
359
360                 //const size_t limit = n_process_buffers().n_audio();
361                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
362                 MidiBuffer& mbuf (bufs.get_midi (0));
363
364                 /* we are a MIDI track, so we always start the chain with a single-channel diskstream */
365                 ChanCount c;
366                 c.set_audio (0);
367                 c.set_midi (1);
368                 bufs.set_count (c);
369
370                 diskstream->get_playback (mbuf, start_frame, end_frame);
371
372                 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
373
374                 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
375
376                 /* final argument: don't waste time with automation if we're recording or we've just stopped (yes it can happen) */
377
378                 process_output_buffers (bufs, start_frame, end_frame, nframes,
379                                         (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick,
380                                         (!diskstream->record_enabled() && !_session.transport_stopped()));
381         }
382
383         _main_outs->flush_buffers (nframes, end_frame - start_frame - 1);
384
385         return 0;
386 }
387
388 int
389 MidiTrack::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame,
390                     bool state_changing, bool can_record, bool rec_monitors_input)
391 {
392         int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
393
394         if (ret == 0 && _step_editing) {
395                 push_midi_input_to_step_edit_ringbuffer (nframes);
396         }
397
398         return ret;
399 }
400
401 void
402 MidiTrack::realtime_locate ()
403 {
404         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
405         if (!lm.locked ()) {
406                 return;
407         }
408
409         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
410                 (*i)->realtime_locate ();
411         }
412 }
413
414 void
415 MidiTrack::realtime_handle_transport_stopped ()
416 {
417         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
418         if (!lm.locked ()) {
419                 return;
420         }
421
422         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
423                 (*i)->realtime_handle_transport_stopped ();
424         }
425 }
426
427 void
428 MidiTrack::push_midi_input_to_step_edit_ringbuffer (framecnt_t nframes)
429 {
430         PortSet& ports (_input->ports());
431
432         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
433
434                 Buffer& b (p->get_buffer (nframes));
435                 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
436                 assert (mb);
437
438                 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
439
440                         const Evoral::MIDIEvent<framepos_t> ev(*e, false);
441
442                         /* note on, since for step edit, note length is determined
443                            elsewhere
444                         */
445
446                         if (ev.is_note_on()) {
447                                 /* we don't care about the time for this purpose */
448                                 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
449                         }
450                 }
451         }
452 }
453
454 void
455 MidiTrack::write_out_of_band_data (BufferSet& bufs, framepos_t /*start*/, framepos_t /*end*/, framecnt_t nframes)
456 {
457         MidiBuffer& buf (bufs.get_midi (0));
458
459         // Append immediate events
460
461         if (_immediate_events.read_space()) {
462
463                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 has %2 of immediate events to deliver\n",
464                                                             name(), _immediate_events.read_space()));
465
466                 /* write as many of the immediate events as we can, but give "true" as
467                  * the last argument ("stop on overflow in destination") so that we'll
468                  * ship the rest out next time.
469                  *
470                  * the (nframes-1) argument puts all these events at the last
471                  * possible position of the output buffer, so that we do not
472                  * violate monotonicity when writing.
473                  */
474
475                 _immediate_events.read (buf, 0, 1, nframes-1, true);
476         }
477
478         // MIDI thru: send incoming data "through" output
479         if (_midi_thru && _session.transport_speed() != 0.0f && _input->n_ports().n_midi()) {
480                 buf.merge_in_place (_input->midi(0)->get_midi_buffer(nframes));
481         }
482 }
483
484 int
485 MidiTrack::export_stuff (BufferSet& /*bufs*/, framecnt_t /*nframes*/, framepos_t /*end_frame*/)
486 {
487         return -1;
488 }
489
490 boost::shared_ptr<Region>
491 MidiTrack::bounce (InterThreadInfo& /*itt*/)
492 {
493         throw;
494         // vector<MidiSource*> srcs;
495         // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
496         return boost::shared_ptr<Region> ();
497 }
498
499
500 boost::shared_ptr<Region>
501 MidiTrack::bounce_range (framepos_t /*start*/, framepos_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
502 {
503         throw;
504         //vector<MidiSource*> srcs;
505         //return _session.write_one_track (*this, start, end, false, srcs, itt);
506         return boost::shared_ptr<Region> ();
507 }
508
509 void
510 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
511 {
512 }
513
514 void
515 MidiTrack::unfreeze ()
516 {
517         _freeze_record.state = UnFrozen;
518         FreezeChange (); /* EMIT SIGNAL */
519 }
520
521 void
522 MidiTrack::set_note_mode (NoteMode m)
523 {
524         _note_mode = m;
525         midi_diskstream()->set_note_mode(m);
526 }
527
528 void
529 MidiTrack::midi_panic()
530 {
531         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers panic data\n", name()));
532         for (uint8_t channel = 0; channel <= 0xF; channel++) {
533                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
534                 write_immediate_event(3, ev);
535                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
536                 write_immediate_event(3, ev);
537                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
538                 write_immediate_event(3, ev);
539         }
540 }
541
542 /** \return true on success, false on failure (no buffer space left)
543  */
544 bool
545 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
546 {
547         if (!Evoral::midi_event_is_valid(buf, size)) {
548                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
549                 return false;
550         }
551         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
552         return (_immediate_events.write(0, type, size, buf) == size);
553 }
554
555 void
556 MidiTrack::MidiControl::set_value(double val)
557 {
558         bool valid = false;
559         if (isinf(val)) {
560                 cerr << "MIDIControl value is infinity" << endl;
561         } else if (isnan(val)) {
562                 cerr << "MIDIControl value is NaN" << endl;
563         } else if (val < _list->parameter().min()) {
564                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
565         } else if (val > _list->parameter().max()) {
566                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
567         } else {
568                 valid = true;
569         }
570
571         if (!valid) {
572                 return;
573         }
574
575         assert(val <= _list->parameter().max());
576         if ( ! automation_playback()) {
577                 size_t size = 3;
578                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
579                 switch(_list->parameter().type()) {
580                 case MidiCCAutomation:
581                         ev[0] += MIDI_CMD_CONTROL;
582                         ev[1] = _list->parameter().id();
583                         ev[2] = int(val);
584                         break;
585
586                 case MidiPgmChangeAutomation:
587                         size = 2;
588                         ev[0] += MIDI_CMD_PGM_CHANGE;
589                         ev[1] = int(val);
590                         break;
591
592                 case MidiChannelPressureAutomation:
593                         size = 2;
594                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
595                         ev[1] = int(val);
596                         break;
597
598                 case MidiPitchBenderAutomation:
599                         ev[0] += MIDI_CMD_BENDER;
600                         ev[1] = 0x7F & int(val);
601                         ev[2] = 0x7F & (int(val) >> 7);
602                         break;
603
604                 default:
605                         assert(false);
606                 }
607                 _route->write_immediate_event(size,  ev);
608         }
609
610         AutomationControl::set_value(val);
611 }
612
613 void
614 MidiTrack::set_step_editing (bool yn)
615 {
616         if (_session.record_status() != Session::Disabled) {
617                 return;
618         }
619
620         if (yn != _step_editing) {
621                 _step_editing = yn;
622                 StepEditStatusChange (yn);
623         }
624 }
625
626 void
627 MidiTrack::set_midi_thru (bool yn)
628 {
629         _midi_thru = yn;
630 }
631
632 boost::shared_ptr<SMFSource>
633 MidiTrack::write_source (uint32_t)
634 {
635         return midi_diskstream()->write_source ();
636 }
637
638 void
639 MidiTrack::set_channel_mode (ChannelMode mode, uint16_t mask)
640 {
641         midi_diskstream()->set_channel_mode (mode, mask);
642 }
643
644 ChannelMode
645 MidiTrack::get_channel_mode ()
646 {
647         return midi_diskstream()->get_channel_mode ();
648 }
649
650 uint16_t
651 MidiTrack::get_channel_mask ()
652 {
653         return midi_diskstream()->get_channel_mask ();
654 }
655
656 boost::shared_ptr<MidiPlaylist>
657 MidiTrack::midi_playlist ()
658 {
659         return midi_diskstream()->midi_playlist ();
660 }
661
662 void
663 MidiTrack::diskstream_data_recorded (boost::shared_ptr<MidiBuffer> buf, boost::weak_ptr<MidiSource> src)
664 {
665         DataRecorded (buf, src); /* EMIT SIGNAL */
666 }
667
668 bool
669 MidiTrack::should_monitor () const
670 {
671         return true;
672 }
673
674 bool
675 MidiTrack::send_silence () const
676 {
677         return false;
678 }