Remove unused with_processors parameter to
[ardour.git] / libs / ardour / midi_track.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3     Author: David Robillard
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
20 #include "pbd/error.h"
21
22 #include "pbd/enumwriter.h"
23 #include "pbd/convert.h"
24 #include "midi++/events.h"
25 #include "evoral/midi_util.h"
26
27 #include "ardour/amp.h"
28 #include "ardour/buffer_set.h"
29 #include "ardour/debug.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/session_playlists.h"
45 #include "ardour/utils.h"
46
47 #include "i18n.h"
48
49 using namespace std;
50 using namespace ARDOUR;
51 using namespace PBD;
52
53 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
54         : Track (sess, name, flag, mode, DataType::MIDI)
55         , _immediate_events(1024) // FIXME: size?
56         , _step_edit_ring_buffer(64) // FIXME: size?
57         , _note_mode(Sustained)
58         , _step_editing (false)
59         , _midi_thru (true)
60         , _input_active (true)
61 {
62 }
63
64 MidiTrack::~MidiTrack ()
65 {
66 }
67
68 int
69 MidiTrack::init ()
70 {
71         if (Track::init ()) {
72                 return -1;
73         }
74
75         _input->changed.connect_same_thread (*this, boost::bind (&MidiTrack::track_input_active, this, _1, _2));
76
77         return 0;
78 }
79
80 void
81 MidiTrack::use_new_diskstream ()
82 {
83         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
84
85         if (_flags & Hidden) {
86                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
87         } else {
88                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
89         }
90
91         assert(_mode != Destructive);
92
93         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
94         ds->do_refill_with_alloc ();
95         ds->set_block_size (_session.get_block_size ());
96
97         set_diskstream (ds);
98 }
99
100 void
101 MidiTrack::set_record_enabled (bool yn, void *src)
102 {
103         if (_step_editing) {
104                 return;
105         }
106
107         Track::set_record_enabled (yn, src);
108 }
109
110 void
111 MidiTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
112 {
113         Track::set_diskstream (ds);
114
115         _diskstream->set_track (this);
116         _diskstream->set_destructive (_mode == Destructive);
117
118         _diskstream->set_record_enabled (false);
119         //_diskstream->monitor_input (false);
120
121         _diskstream_data_recorded_connection.disconnect ();
122         boost::shared_ptr<MidiDiskstream> mds = boost::dynamic_pointer_cast<MidiDiskstream> (ds);
123         mds->DataRecorded.connect_same_thread (
124                 _diskstream_data_recorded_connection,
125                 boost::bind (&MidiTrack::diskstream_data_recorded, this, _1));
126
127         DiskstreamChanged (); /* EMIT SIGNAL */
128 }
129
130 boost::shared_ptr<MidiDiskstream>
131 MidiTrack::midi_diskstream() const
132 {
133         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
134 }
135
136 int
137 MidiTrack::set_state (const XMLNode& node, int version)
138 {
139         const XMLProperty *prop;
140
141         if (Track::set_state (node, version)) {
142                 return -1;
143         }
144
145         // No destructive MIDI tracks (yet?)
146         _mode = Normal;
147
148         if ((prop = node.property (X_("note-mode"))) != 0) {
149                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
150         } else {
151                 _note_mode = Sustained;
152         }
153
154         if ((prop = node.property ("midi-thru")) != 0) {
155                 set_midi_thru (string_is_affirmative (prop->value()));
156         }
157
158         if ((prop = node.property ("input-active")) != 0) {
159                 set_input_active (string_is_affirmative (prop->value()));
160         }
161
162         pending_state = const_cast<XMLNode*> (&node);
163
164         if (_session.state_of_the_state() & Session::Loading) {
165                 _session.StateReady.connect_same_thread (
166                         *this, boost::bind (&MidiTrack::set_state_part_two, this));
167         } else {
168                 set_state_part_two ();
169         }
170
171         return 0;
172 }
173
174 XMLNode&
175 MidiTrack::state(bool full_state)
176 {
177         XMLNode& root (Track::state(full_state));
178         XMLNode* freeze_node;
179         char buf[64];
180
181         if (_freeze_record.playlist) {
182                 XMLNode* inode;
183
184                 freeze_node = new XMLNode (X_("freeze-info"));
185                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
186                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
187
188                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
189                         inode = new XMLNode (X_("processor"));
190                         (*i)->id.print (buf, sizeof(buf));
191                         inode->add_property (X_("id"), buf);
192                         inode->add_child_copy ((*i)->state);
193
194                         freeze_node->add_child_nocopy (*inode);
195                 }
196
197                 root.add_child_nocopy (*freeze_node);
198         }
199
200         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
201
202         root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
203         root.add_property ("note-mode", enum_2_string (_note_mode));
204         root.add_property ("midi-thru", (_midi_thru ? "yes" : "no"));
205         root.add_property ("input-active", (_input_active ? "yes" : "no"));
206
207         return root;
208 }
209
210 void
211 MidiTrack::set_state_part_two ()
212 {
213         XMLNode* fnode;
214         XMLProperty* prop;
215         LocaleGuard lg (X_("POSIX"));
216
217         /* This is called after all session state has been restored but before
218            have been made ports and connections are established.
219         */
220
221         if (pending_state == 0) {
222                 return;
223         }
224
225         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
226
227                 _freeze_record.state = Frozen;
228
229                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
230                         delete *i;
231                 }
232                 _freeze_record.processor_info.clear ();
233
234                 if ((prop = fnode->property (X_("playlist"))) != 0) {
235                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
236                         if (pl) {
237                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
238                         } else {
239                                 _freeze_record.playlist.reset();
240                                 _freeze_record.state = NoFreeze;
241                         return;
242                         }
243                 }
244
245                 if ((prop = fnode->property (X_("state"))) != 0) {
246                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
247                 }
248
249                 XMLNodeConstIterator citer;
250                 XMLNodeList clist = fnode->children();
251
252                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
253                         if ((*citer)->name() != X_("processor")) {
254                                 continue;
255                         }
256
257                         if ((prop = (*citer)->property (X_("id"))) == 0) {
258                                 continue;
259                         }
260
261                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
262                                                                                    boost::shared_ptr<Processor>());
263                         frii->id = prop->value ();
264                         _freeze_record.processor_info.push_back (frii);
265                 }
266         }
267
268         if (midi_diskstream ()) {
269                 midi_diskstream()->set_block_size (_session.get_block_size ());
270         }
271
272         return;
273 }
274
275 int
276 MidiTrack::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
277 {
278         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
279         if (!lm.locked()) {
280                 return 0;
281         }
282
283         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
284
285         automation_snapshot (start_frame);
286
287         if (n_outputs().n_total() == 0 && _processors.empty()) {
288                 return 0;
289         }
290
291         if (!_active) {
292                 silence (nframes);
293                 return 0;
294         }
295
296         framepos_t transport_frame = _session.transport_frame();
297
298         int dret;
299         framecnt_t playback_distance;
300
301         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
302                 /* need to do this so that the diskstream sets its
303                    playback distance to zero, thus causing diskstream::commit
304                    to do nothing.
305                    */
306                 dret = diskstream->process (transport_frame, 0, playback_distance);
307                 need_butler = diskstream->commit (playback_distance);
308                 return dret;
309         }
310
311         _silent = false;
312
313         if ((dret = diskstream->process (transport_frame, nframes, playback_distance)) != 0) {
314                 need_butler = diskstream->commit (playback_distance);
315                 silence (nframes);
316                 return dret;
317         }
318
319         /* special condition applies */
320
321         if (_meter_point == MeterInput) {
322                 _input->process_input (_meter, start_frame, end_frame, nframes);
323         }
324
325         if (monitoring_state() == MonitoringInput) {
326
327                 /* not actually recording, but we want to hear the input material anyway,
328                    at least potentially (depending on monitoring options)
329                 */
330
331                 passthru (start_frame, end_frame, nframes, 0);
332
333         } else {
334                 /*
335                    XXX is it true that the earlier test on n_outputs()
336                    means that we can avoid checking it again here? i think
337                    so, because changing the i/o configuration of an IO
338                    requires holding the AudioEngine lock, which we hold
339                    while in the process() tree.
340                    */
341
342
343                 /* copy the diskstream data to all output buffers */
344
345                 //const size_t limit = n_process_buffers().n_audio();
346                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
347                 MidiBuffer& mbuf (bufs.get_midi (0));
348
349                 /* we are a MIDI track, so we always start the chain with a single-channel diskstream */
350                 ChanCount c;
351                 c.set_audio (0);
352                 c.set_midi (1);
353                 bufs.set_count (c);
354
355                 diskstream->get_playback (mbuf, nframes);
356
357                 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
358
359                 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
360
361                 /* final argument: don't waste time with automation if we're recording or we've just stopped (yes it can happen) */
362
363                 process_output_buffers (
364                         bufs, start_frame, end_frame, nframes,
365                         declick, (!diskstream->record_enabled() && !_session.transport_stopped())
366                         );
367         }
368
369         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
370                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
371                 if (d) {
372                         d->flush_buffers (nframes, end_frame - start_frame - 1);
373                 }
374         }
375
376         need_butler = diskstream->commit (playback_distance);
377         
378         return 0;
379 }
380
381 int
382 MidiTrack::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool state_changing)
383 {
384         int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing);
385
386         if (ret == 0 && _step_editing) {
387                 push_midi_input_to_step_edit_ringbuffer (nframes);
388         }
389
390         return ret;
391 }
392
393 void
394 MidiTrack::realtime_locate ()
395 {
396         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
397         if (!lm.locked ()) {
398                 return;
399         }
400
401         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
402                 (*i)->realtime_locate ();
403         }
404 }
405
406 void
407 MidiTrack::realtime_handle_transport_stopped ()
408 {
409         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
410         if (!lm.locked ()) {
411                 return;
412         }
413
414         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
415                 (*i)->realtime_handle_transport_stopped ();
416         }
417 }
418
419 void
420 MidiTrack::push_midi_input_to_step_edit_ringbuffer (framecnt_t nframes)
421 {
422         PortSet& ports (_input->ports());
423
424         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
425
426                 Buffer& b (p->get_buffer (nframes));
427                 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
428                 assert (mb);
429
430                 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
431
432                         const Evoral::MIDIEvent<framepos_t> ev(*e, false);
433
434                         /* note on, since for step edit, note length is determined
435                            elsewhere
436                         */
437
438                         if (ev.is_note_on()) {
439                                 /* we don't care about the time for this purpose */
440                                 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
441                         }
442                 }
443         }
444 }
445
446 void
447 MidiTrack::write_out_of_band_data (BufferSet& bufs, framepos_t /*start*/, framepos_t /*end*/, framecnt_t nframes)
448 {
449         MidiBuffer& buf (bufs.get_midi (0));
450
451         // Append immediate events
452
453         if (_immediate_events.read_space()) {
454
455                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 has %2 of immediate events to deliver\n",
456                                                             name(), _immediate_events.read_space()));
457
458                 /* write as many of the immediate events as we can, but give "true" as
459                  * the last argument ("stop on overflow in destination") so that we'll
460                  * ship the rest out next time.
461                  *
462                  * the (nframes-1) argument puts all these events at the last
463                  * possible position of the output buffer, so that we do not
464                  * violate monotonicity when writing.
465                  */
466
467                 _immediate_events.read (buf, 0, 1, nframes-1, true);
468         }
469
470         // MIDI thru: send incoming data "through" output
471         if (_midi_thru && _session.transport_speed() != 0.0f && _input->n_ports().n_midi()) {
472                 buf.merge_in_place (_input->midi(0)->get_midi_buffer(nframes));
473         }
474 }
475
476 int
477 MidiTrack::export_stuff (BufferSet& /*bufs*/, framecnt_t /*nframes*/, framepos_t /*end_frame*/)
478 {
479         return -1;
480 }
481
482 boost::shared_ptr<Region>
483 MidiTrack::bounce (InterThreadInfo& /*itt*/)
484 {
485         std::cerr << "MIDI bounce currently unsupported" << std::endl;
486         return boost::shared_ptr<Region> ();
487 }
488
489
490 boost::shared_ptr<Region>
491 MidiTrack::bounce_range (framepos_t /*start*/, framepos_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
492 {
493         std::cerr << "MIDI bounce range currently unsupported" << std::endl;
494         return boost::shared_ptr<Region> ();
495 }
496
497 void
498 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
499 {
500         std::cerr << "MIDI freeze currently unsupported" << std::endl;
501 }
502
503 void
504 MidiTrack::unfreeze ()
505 {
506         _freeze_record.state = UnFrozen;
507         FreezeChange (); /* EMIT SIGNAL */
508 }
509
510 void
511 MidiTrack::set_note_mode (NoteMode m)
512 {
513         _note_mode = m;
514         midi_diskstream()->set_note_mode(m);
515 }
516
517 void
518 MidiTrack::midi_panic()
519 {
520         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers panic data\n", name()));
521         for (uint8_t channel = 0; channel <= 0xF; channel++) {
522                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
523                 write_immediate_event(3, ev);
524                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
525                 write_immediate_event(3, ev);
526                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
527                 write_immediate_event(3, ev);
528         }
529 }
530
531 /** \return true on success, false on failure (no buffer space left)
532  */
533 bool
534 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
535 {
536         if (!Evoral::midi_event_is_valid(buf, size)) {
537                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
538                 return false;
539         }
540         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
541         return (_immediate_events.write(0, type, size, buf) == size);
542 }
543
544 void
545 MidiTrack::MidiControl::set_value(double val)
546 {
547         bool valid = false;
548         if (isinf(val)) {
549                 cerr << "MIDIControl value is infinity" << endl;
550         } else if (isnan(val)) {
551                 cerr << "MIDIControl value is NaN" << endl;
552         } else if (val < _list->parameter().min()) {
553                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
554         } else if (val > _list->parameter().max()) {
555                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
556         } else {
557                 valid = true;
558         }
559
560         if (!valid) {
561                 return;
562         }
563
564         assert(val <= _list->parameter().max());
565         if ( ! automation_playback()) {
566                 size_t size = 3;
567                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
568                 switch(_list->parameter().type()) {
569                 case MidiCCAutomation:
570                         ev[0] += MIDI_CMD_CONTROL;
571                         ev[1] = _list->parameter().id();
572                         ev[2] = int(val);
573                         break;
574
575                 case MidiPgmChangeAutomation:
576                         size = 2;
577                         ev[0] += MIDI_CMD_PGM_CHANGE;
578                         ev[1] = int(val);
579                         break;
580
581                 case MidiChannelPressureAutomation:
582                         size = 2;
583                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
584                         ev[1] = int(val);
585                         break;
586
587                 case MidiPitchBenderAutomation:
588                         ev[0] += MIDI_CMD_BENDER;
589                         ev[1] = 0x7F & int(val);
590                         ev[2] = 0x7F & (int(val) >> 7);
591                         break;
592
593                 default:
594                         assert(false);
595                 }
596                 _route->write_immediate_event(size,  ev);
597         }
598
599         AutomationControl::set_value(val);
600 }
601
602 void
603 MidiTrack::set_step_editing (bool yn)
604 {
605         if (_session.record_status() != Session::Disabled) {
606                 return;
607         }
608
609         if (yn != _step_editing) {
610                 _step_editing = yn;
611                 StepEditStatusChange (yn);
612         }
613 }
614
615 void
616 MidiTrack::set_midi_thru (bool yn)
617 {
618         _midi_thru = yn;
619 }
620
621 boost::shared_ptr<SMFSource>
622 MidiTrack::write_source (uint32_t)
623 {
624         return midi_diskstream()->write_source ();
625 }
626
627 void
628 MidiTrack::set_channel_mode (ChannelMode mode, uint16_t mask)
629 {
630         midi_diskstream()->set_channel_mode (mode, mask);
631 }
632
633 ChannelMode
634 MidiTrack::get_channel_mode ()
635 {
636         return midi_diskstream()->get_channel_mode ();
637 }
638
639 uint16_t
640 MidiTrack::get_channel_mask ()
641 {
642         return midi_diskstream()->get_channel_mask ();
643 }
644
645 boost::shared_ptr<MidiPlaylist>
646 MidiTrack::midi_playlist ()
647 {
648         return midi_diskstream()->midi_playlist ();
649 }
650
651 void
652 MidiTrack::diskstream_data_recorded (boost::weak_ptr<MidiSource> src)
653 {
654         DataRecorded (src); /* EMIT SIGNAL */
655 }
656
657 bool
658 MidiTrack::should_monitor () const
659 {
660         return true;
661 }
662
663 bool
664 MidiTrack::send_silence () const
665 {
666         return false;
667 }
668
669 bool
670 MidiTrack::input_active () const
671 {
672         return _input_active;
673 }
674
675 void
676 MidiTrack::set_input_active (bool yn)
677 {
678         if (yn != _input_active) {
679                 _input_active = yn;
680                 map_input_active (yn);
681                 InputActiveChanged (); /* EMIT SIGNAL */
682         }
683 }
684
685 void
686 MidiTrack::map_input_active (bool yn)
687 {
688         if (!_input) {
689                 return;
690         }
691
692         PortSet& ports (_input->ports());
693
694         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
695                 boost::shared_ptr<MidiPort> mp = boost::dynamic_pointer_cast<MidiPort> (*p);
696                 if (yn != mp->input_active()) {
697                         mp->set_input_active (yn);
698                 }
699         }
700 }
701
702 void
703 MidiTrack::track_input_active (IOChange change, void* /* src */)
704 {
705         if (change.type & IOChange::ConfigurationChanged) {
706                 map_input_active (_input_active);
707         }
708 }
709
710 boost::shared_ptr<Diskstream>
711 MidiTrack::diskstream_factory (XMLNode const & node)
712 {
713         return boost::shared_ptr<Diskstream> (new MidiDiskstream (_session, node));
714 }
715
716 boost::shared_ptr<MidiBuffer>
717 MidiTrack::get_gui_feed_buffer () const
718 {
719         return midi_diskstream()->get_gui_feed_buffer ();
720 }