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