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