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