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