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