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