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