2 Copyright (C) 2006 Paul Davis
3 By Dave Robillard, 2006
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.
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.
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.
19 #include <pbd/error.h>
20 #include <sigc++/retype.h>
21 #include <sigc++/retype_return.h>
22 #include <sigc++/bind.h>
24 #include <pbd/enumwriter.h>
25 #include <midi++/events.h>
27 #include <ardour/midi_track.h>
28 #include <ardour/midi_diskstream.h>
29 #include <ardour/session.h>
30 #include <ardour/io_processor.h>
31 #include <ardour/midi_region.h>
32 #include <ardour/midi_source.h>
33 #include <ardour/route_group_specialized.h>
34 #include <ardour/processor.h>
35 #include <ardour/midi_playlist.h>
36 #include <ardour/panner.h>
37 #include <ardour/utils.h>
38 #include <ardour/buffer_set.h>
39 #include <ardour/meter.h>
45 using namespace ARDOUR;
48 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
49 : Track (sess, name, flag, mode, DataType::MIDI)
50 , _immediate_events(1024) // FIXME: size?
51 , _note_mode(Sustained)
53 MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
55 if (_flags & Hidden) {
56 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
58 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
61 assert(mode != Destructive);
63 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name, dflags));
64 _session.add_diskstream (ds);
66 set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
69 _freeze_record.state = NoFreeze;
70 _saved_meter_point = _meter_point;
73 set_input_minimum(ChanCount(DataType::MIDI, 1));
74 set_input_maximum(ChanCount(DataType::MIDI, 1));
75 set_output_minimum(ChanCount(DataType::MIDI, 1));
76 set_output_maximum(ChanCount(DataType::MIDI, 1));
78 PortCountChanged(ChanCount(DataType::MIDI, 2)); /* EMIT SIGNAL */
81 MidiTrack::MidiTrack (Session& sess, const XMLNode& node)
83 , _immediate_events(1024) // FIXME: size?
84 , _note_mode(Sustained)
86 _set_state(node, false);
88 set_input_minimum(ChanCount(DataType::MIDI, 1));
89 set_input_maximum(ChanCount(DataType::MIDI, 1));
90 set_output_minimum(ChanCount(DataType::MIDI, 1));
91 set_output_maximum(ChanCount(DataType::MIDI, 1));
93 PortCountChanged(ChanCount(DataType::MIDI, 2)); /* EMIT SIGNAL */
96 MidiTrack::~MidiTrack ()
102 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
105 _diskstream->set_io (*this);
106 _diskstream->set_destructive (_mode == Destructive);
108 _diskstream->set_record_enabled (false);
109 //_diskstream->monitor_input (false);
111 ic_connection.disconnect();
112 ic_connection = input_changed.connect (mem_fun (*_diskstream, &MidiDiskstream::handle_input_change));
114 DiskstreamChanged (); /* EMIT SIGNAL */
120 MidiTrack::use_diskstream (string name)
122 boost::shared_ptr<MidiDiskstream> dstream;
124 if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream>(_session.diskstream_by_name (name))) == 0) {
125 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), name) << endmsg;
129 return set_diskstream (dstream);
133 MidiTrack::use_diskstream (const PBD::ID& id)
135 boost::shared_ptr<MidiDiskstream> dstream;
137 if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
138 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
142 return set_diskstream (dstream);
145 boost::shared_ptr<MidiDiskstream>
146 MidiTrack::midi_diskstream() const
148 return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
152 MidiTrack::set_state (const XMLNode& node)
154 return _set_state (node, true);
158 MidiTrack::_set_state (const XMLNode& node, bool call_base)
160 const XMLProperty *prop;
161 XMLNodeConstIterator iter;
163 if (Route::_set_state (node, call_base)) {
167 // No destructive MIDI tracks (yet?)
170 if ((prop = node.property (X_("note-mode"))) != 0) {
171 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
173 _note_mode = Sustained;
176 if ((prop = node.property ("diskstream-id")) == 0) {
178 /* some old sessions use the diskstream name rather than the ID */
180 if ((prop = node.property ("diskstream")) == 0) {
181 fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
186 if (use_diskstream (prop->value())) {
192 PBD::ID id (prop->value());
194 if (use_diskstream (id)) {
201 XMLNodeConstIterator niter;
204 nlist = node.children();
205 for (niter = nlist.begin(); niter != nlist.end(); ++niter){
208 if (child->name() == X_("recenable")) {
209 _rec_enable_control->set_state (*child);
210 _session.add_controllable (_rec_enable_control);
214 pending_state = const_cast<XMLNode*> (&node);
216 _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
222 MidiTrack::state(bool full_state)
224 XMLNode& root (Route::state(full_state));
225 XMLNode* freeze_node;
228 if (_freeze_record.playlist) {
231 freeze_node = new XMLNode (X_("freeze-info"));
232 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
233 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
235 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
236 inode = new XMLNode (X_("processor"));
237 (*i)->id.print (buf, sizeof(buf));
238 inode->add_property (X_("id"), buf);
239 inode->add_child_copy ((*i)->state);
241 freeze_node->add_child_nocopy (*inode);
244 root.add_child_nocopy (*freeze_node);
247 /* Alignment: act as a proxy for the diskstream */
249 XMLNode* align_node = new XMLNode (X_("alignment"));
250 AlignStyle as = _diskstream->alignment_style ();
251 align_node->add_property (X_("style"), enum_2_string (as));
252 root.add_child_nocopy (*align_node);
254 root.add_property (X_("note-mode"), enum_2_string (_note_mode));
256 /* we don't return diskstream state because we don't
257 own the diskstream exclusively. control of the diskstream
258 state is ceded to the Session, even if we create the
262 _diskstream->id().print (buf, sizeof(buf));
263 root.add_property ("diskstream-id", buf);
265 root.add_child_nocopy (_rec_enable_control->get_state());
271 MidiTrack::set_state_part_two ()
275 LocaleGuard lg (X_("POSIX"));
277 /* This is called after all session state has been restored but before
278 have been made ports and connections are established.
281 if (pending_state == 0) {
285 if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
288 _freeze_record.have_mementos = false;
289 _freeze_record.state = Frozen;
291 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
294 _freeze_record.processor_info.clear ();
296 if ((prop = fnode->property (X_("playlist"))) != 0) {
297 boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
299 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
301 _freeze_record.playlist.reset();
302 _freeze_record.state = NoFreeze;
307 if ((prop = fnode->property (X_("state"))) != 0) {
308 _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
311 XMLNodeConstIterator citer;
312 XMLNodeList clist = fnode->children();
314 for (citer = clist.begin(); citer != clist.end(); ++citer) {
315 if ((*citer)->name() != X_("processor")) {
319 if ((prop = (*citer)->property (X_("id"))) == 0) {
323 FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
324 boost::shared_ptr<Processor>());
325 frii->id = prop->value ();
326 _freeze_record.processor_info.push_back (frii);
330 /* Alignment: act as a proxy for the diskstream */
332 if ((fnode = find_named_node (*pending_state, X_("alignment"))) != 0) {
334 if ((prop = fnode->property (X_("style"))) != 0) {
336 /* fix for older sessions from before EnumWriter */
340 if (prop->value() == "capture") {
341 pstr = "CaptureTime";
342 } else if (prop->value() == "existing") {
343 pstr = "ExistingMaterial";
345 pstr = prop->value();
348 AlignStyle as = AlignStyle (string_2_enum (pstr, as));
349 _diskstream->set_persistent_align_style (as);
356 MidiTrack::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset,
357 bool session_state_changing, bool can_record, bool rec_monitors_input)
359 if (n_outputs().n_midi() == 0) {
364 silence (nframes, offset);
367 if (session_state_changing) {
369 /* XXX is this safe to do against transport state changes? */
371 passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
375 midi_diskstream()->check_record_status (start_frame, nframes, can_record);
379 if (_have_internal_generator) {
380 /* since the instrument has no input streams,
381 there is no reason to send any signal
387 if (Config->get_auto_input()) {
388 if (Config->get_monitoring_model() == SoftwareMonitoring) {
389 send_silence = false;
394 if (_diskstream->record_enabled()) {
395 if (Config->get_monitoring_model() == SoftwareMonitoring) {
396 send_silence = false;
406 apply_gain_automation = false;
410 /* if we're sending silence, but we want the meters to show levels for the signal,
414 if (_have_internal_generator) {
415 passthru_silence (start_frame, end_frame, nframes, offset, 0, true);
417 if (_meter_point == MeterInput) {
418 just_meter_input (start_frame, end_frame, nframes, offset);
420 passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
425 /* we're sending signal, but we may still want to meter the input.
428 passthru (start_frame, end_frame, nframes, offset, 0, (_meter_point == MeterInput));
435 MidiTrack::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
436 bool can_record, bool rec_monitors_input)
439 boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
442 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
444 // automation snapshot can also be called from the non-rt context
445 // and it uses the redirect list, so we take the lock out here
446 automation_snapshot (start_frame);
450 if (n_outputs().n_total() == 0 && _processors.empty()) {
455 silence (nframes, offset);
459 nframes_t transport_frame = _session.transport_frame();
461 if ((nframes = check_initial_delay (nframes, offset, transport_frame)) == 0) {
462 /* need to do this so that the diskstream sets its
463 playback distance to zero, thus causing diskstream::commit
466 return diskstream->process (transport_frame, 0, 0, can_record, rec_monitors_input);
471 if ((dret = diskstream->process (transport_frame, nframes, offset, can_record, rec_monitors_input)) != 0) {
473 silence (nframes, offset);
478 /* special condition applies */
480 if (_meter_point == MeterInput) {
481 just_meter_input (start_frame, end_frame, nframes, offset);
484 if (diskstream->record_enabled() && !can_record && !Config->get_auto_input()) {
486 /* not actually recording, but we want to hear the input material anyway,
487 at least potentially (depending on monitoring options)
490 passthru (start_frame, end_frame, nframes, offset, 0, true);
494 XXX is it true that the earlier test on n_outputs()
495 means that we can avoid checking it again here? i think
496 so, because changing the i/o configuration of an IO
497 requires holding the AudioEngine lock, which we hold
498 while in the process() tree.
502 /* copy the diskstream data to all output buffers */
504 //const size_t limit = n_process_buffers().n_audio();
505 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
507 diskstream->get_playback(bufs.get_midi(0), start_frame, end_frame);
509 process_output_buffers (bufs, start_frame, end_frame, nframes, offset,
510 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick, (_meter_point != MeterInput));
518 MidiTrack::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset,
519 bool can_record, bool rec_monitors_input)
521 if (n_outputs().n_midi() == 0 && _processors.empty()) {
526 silence (nframes, offset);
531 apply_gain_automation = false;
533 silence (nframes, offset);
535 return midi_diskstream()->process (_session.transport_frame() + offset, nframes, offset, can_record, rec_monitors_input);
539 MidiTrack::process_output_buffers (BufferSet& bufs,
540 nframes_t start_frame, nframes_t end_frame,
541 nframes_t nframes, nframes_t offset, bool with_processors, int declick,
544 /* There's no such thing as a MIDI bus for the time being.
545 * We'll do all the MIDI route work here for now, but the long-term goal is to have
546 * Route::process_output_buffers handle everything */
548 if (meter && (_meter_point == MeterInput || _meter_point == MeterPreFader)) {
549 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
552 // Run all processors
553 if (with_processors) {
554 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
556 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
557 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
562 if (meter && (_meter_point == MeterPostFader)) {
563 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
568 IO::silence(nframes, offset);
571 // Write 'automation' controllers (e.g. CC events from a UI slider)
572 write_controller_messages(bufs.get_midi(0), start_frame, end_frame, nframes, offset);
574 deliver_output(bufs, start_frame, end_frame, nframes, offset);
579 MidiTrack::write_controller_messages(MidiBuffer& output_buf, nframes_t start_frame, nframes_t end_frame,
580 nframes_t nframes, nframes_t offset)
583 BufferSet& mix_buffers = _session.get_mix_buffers(ChanCount(DataType::MIDI, 2));
585 /* FIXME: this could be more realtimey */
587 // Write immediate events (UI controls)
588 MidiBuffer& cc_buf = mix_buffers.get_midi(0);
589 cc_buf.silence(nframes, offset);
591 uint8_t buf[3]; // CC = 3 bytes
592 buf[0] = MIDI_CMD_CONTROL;
593 MIDI::Event ev(0, 3, buf, false);
595 // Write track controller automation
596 // This now lives in MidiModel. Any need for track automation like this?
597 // Relative Velocity?
598 if (_session.transport_rolling()) {
599 for (Controls::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
600 const boost::shared_ptr<AutomationList> list = (*i).second->list();
602 if ( (!list->automation_playback())
603 || (list->parameter().type() != MidiCCAutomation))
606 double start = start_frame;
608 while ((*i).second->list()->rt_safe_earliest_event(start, end_frame, x, y)) {
609 assert(x >= start_frame);
610 assert(x <= end_frame);
612 const nframes_t stamp = (nframes_t)floor(x - start_frame);
613 assert(stamp < nframes);
619 ev.buffer()[1] = (uint8_t)list->parameter().id();
620 ev.buffer()[2] = (uint8_t)y;
622 cc_buf.push_back(ev);
624 start = x + 1; // FIXME? maybe?
629 /* FIXME: too much copying! */
631 // Merge cc buf into output
632 if (cc_buf.size() > 0) {
634 // Both CC and route, must merge
635 if (output_buf.size() > 0) {
637 MidiBuffer& mix_buf = mix_buffers.get_midi(1);
638 mix_buf.merge(output_buf, cc_buf);
639 output_buf.copy(mix_buf);
642 output_buf.copy(cc_buf);
647 // Append immediate events (UI controls)
648 _immediate_events.read(output_buf, 0, 0, offset + nframes-1); // all stamps = 0
652 MidiTrack::export_stuff (BufferSet& bufs, nframes_t nframes, nframes_t end_frame)
658 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
660 Route::set_latency_delay (longest_session_latency);
661 _diskstream->set_roll_delay (_roll_delay);
664 boost::shared_ptr<Region>
665 MidiTrack::bounce (InterThreadInfo& itt)
668 // vector<MidiSource*> srcs;
669 // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
670 return boost::shared_ptr<Region> ();
674 boost::shared_ptr<Region>
675 MidiTrack::bounce_range (nframes_t start, nframes_t end, InterThreadInfo& itt)
678 //vector<MidiSource*> srcs;
679 //return _session.write_one_track (*this, start, end, false, srcs, itt);
680 return boost::shared_ptr<Region> ();
684 MidiTrack::freeze (InterThreadInfo& itt)
689 MidiTrack::unfreeze ()
691 _freeze_record.state = UnFrozen;
692 FreezeChange (); /* EMIT SIGNAL */
696 MidiTrack::set_note_mode (NoteMode m)
698 cout << _name << " SET NOTE MODE " << m << endl;
700 midi_diskstream()->set_note_mode(m);
704 MidiTrack::midi_panic()
706 for (uint8_t channel = 0; channel <= 0xF; channel++) {
707 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
708 write_immediate_event(3, ev);
709 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
710 write_immediate_event(3, ev);
711 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
712 write_immediate_event(3, ev);
716 /** \return true on success, false on failure (no buffer space left)
719 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
721 /*printf("Write immediate event: ");
722 for (size_t i=0; i < size; ++i) {
723 printf("%X ", buf[i]);
726 return (_immediate_events.write(0, size, buf) == size);
730 MidiTrack::MidiControl::set_value(float val)
732 assert(val >= _list->parameter().min());
733 assert(val <= _list->parameter().max());
736 if ( ! _list->automation_playback()) {
737 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
738 switch(_list->parameter().type()) {
739 case MidiCCAutomation:
740 ev[0] += MIDI_CMD_CONTROL;
741 ev[1] = _list->parameter().id();
745 case MidiPgmChangeAutomation:
747 ev[0] += MIDI_CMD_PGM_CHANGE;
751 case MidiChannelAftertouchAutomation:
753 ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
757 case MidiPitchBenderAutomation:
758 ev[0] += MIDI_CMD_BENDER;
759 ev[1] = 0x7F & int(val);
760 ev[2] = 0x7F & (int(val) >> 7);
766 _route->write_immediate_event(size, ev);
769 AutomationControl::set_value(val);