2 Copyright (C) 2006 Paul Davis
3 Author: David Robillard
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.
21 #include "pbd/enumwriter.h"
22 #include "pbd/convert.h"
23 #include "evoral/midi_util.h"
25 #include "ardour/buffer_set.h"
26 #include "ardour/debug.h"
27 #include "ardour/delivery.h"
28 #include "ardour/meter.h"
29 #include "ardour/midi_diskstream.h"
30 #include "ardour/midi_playlist.h"
31 #include "ardour/midi_port.h"
32 #include "ardour/midi_track.h"
33 #include "ardour/port.h"
34 #include "ardour/processor.h"
35 #include "ardour/session.h"
36 #include "ardour/session_playlists.h"
37 #include "ardour/utils.h"
42 class InterThreadInfo;
49 using namespace ARDOUR;
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 , _input_active (true)
59 , _playback_channel_mask(0x0000ffff)
60 , _capture_channel_mask(0x0000ffff)
64 MidiTrack::~MidiTrack ()
75 _input->changed.connect_same_thread (*this, boost::bind (&MidiTrack::track_input_active, this, _1, _2));
80 boost::shared_ptr<Diskstream>
81 MidiTrack::create_diskstream ()
83 MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
85 if (_flags & Auditioner) {
86 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
88 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
91 assert(_mode != Destructive);
93 return boost::shared_ptr<Diskstream> (new MidiDiskstream (_session, name(), dflags));
98 MidiTrack::set_record_enabled (bool yn, void *src)
104 Track::set_record_enabled (yn, src);
108 MidiTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
110 /* We have to do this here, as Track::set_diskstream will cause a buffer refill,
111 and the diskstream must be set up to fill its buffers using the correct _note_mode.
113 boost::shared_ptr<MidiDiskstream> mds = boost::dynamic_pointer_cast<MidiDiskstream> (ds);
114 mds->set_note_mode (_note_mode);
116 Track::set_diskstream (ds);
118 mds->reset_tracker ();
120 _diskstream->set_track (this);
121 _diskstream->set_destructive (_mode == Destructive);
122 _diskstream->set_record_enabled (false);
124 _diskstream_data_recorded_connection.disconnect ();
125 mds->DataRecorded.connect_same_thread (
126 _diskstream_data_recorded_connection,
127 boost::bind (&MidiTrack::diskstream_data_recorded, this, _1));
129 DiskstreamChanged (); /* EMIT SIGNAL */
132 boost::shared_ptr<MidiDiskstream>
133 MidiTrack::midi_diskstream() const
135 return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
139 MidiTrack::set_state (const XMLNode& node, int version)
141 const XMLProperty *prop;
143 /* This must happen before Track::set_state(), as there will be a buffer
144 fill during that call, and we must fill buffers using the correct
147 if ((prop = node.property (X_("note-mode"))) != 0) {
148 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
150 _note_mode = Sustained;
153 if (Track::set_state (node, version)) {
157 // No destructive MIDI tracks (yet?)
160 if ((prop = node.property ("input-active")) != 0) {
161 set_input_active (string_is_affirmative (prop->value()));
164 ChannelMode playback_channel_mode = AllChannels;
165 ChannelMode capture_channel_mode = AllChannels;
167 if ((prop = node.property ("playback-channel-mode")) != 0) {
168 playback_channel_mode = ChannelMode (string_2_enum(prop->value(), playback_channel_mode));
170 if ((prop = node.property ("capture-channel-mode")) != 0) {
171 capture_channel_mode = ChannelMode (string_2_enum(prop->value(), capture_channel_mode));
173 if ((prop = node.property ("channel-mode")) != 0) {
174 /* 3.0 behaviour where capture and playback modes were not separated */
175 playback_channel_mode = ChannelMode (string_2_enum(prop->value(), playback_channel_mode));
176 capture_channel_mode = playback_channel_mode;
179 unsigned int playback_channel_mask = 0xffff;
180 unsigned int capture_channel_mask = 0xffff;
182 if ((prop = node.property ("playback-channel-mask")) != 0) {
183 sscanf (prop->value().c_str(), "0x%x", &playback_channel_mask);
185 if ((prop = node.property ("capture-channel-mask")) != 0) {
186 sscanf (prop->value().c_str(), "0x%x", &capture_channel_mask);
188 if ((prop = node.property ("channel-mask")) != 0) {
189 sscanf (prop->value().c_str(), "0x%x", &playback_channel_mask);
190 capture_channel_mask = playback_channel_mask;
193 set_playback_channel_mode (playback_channel_mode, playback_channel_mask);
194 set_capture_channel_mode (capture_channel_mode, capture_channel_mask);
196 pending_state = const_cast<XMLNode*> (&node);
198 if (_session.state_of_the_state() & Session::Loading) {
199 _session.StateReady.connect_same_thread (
200 *this, boost::bind (&MidiTrack::set_state_part_two, this));
202 set_state_part_two ();
209 MidiTrack::state(bool full_state)
211 XMLNode& root (Track::state(full_state));
212 XMLNode* freeze_node;
215 if (_freeze_record.playlist) {
218 freeze_node = new XMLNode (X_("freeze-info"));
219 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
220 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
222 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
223 inode = new XMLNode (X_("processor"));
224 (*i)->id.print (buf, sizeof(buf));
225 inode->add_property (X_("id"), buf);
226 inode->add_child_copy ((*i)->state);
228 freeze_node->add_child_nocopy (*inode);
231 root.add_child_nocopy (*freeze_node);
234 root.add_property("playback_channel-mode", enum_2_string(get_playback_channel_mode()));
235 root.add_property("capture_channel-mode", enum_2_string(get_capture_channel_mode()));
236 snprintf (buf, sizeof(buf), "0x%x", get_playback_channel_mask());
237 root.add_property("playback-channel-mask", buf);
238 snprintf (buf, sizeof(buf), "0x%x", get_capture_channel_mask());
239 root.add_property("capture-channel-mask", buf);
241 root.add_property ("note-mode", enum_2_string (_note_mode));
242 root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
243 root.add_property ("input-active", (_input_active ? "yes" : "no"));
249 MidiTrack::set_state_part_two ()
253 LocaleGuard lg (X_("POSIX"));
255 /* This is called after all session state has been restored but before
256 have been made ports and connections are established.
259 if (pending_state == 0) {
263 if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
265 _freeze_record.state = Frozen;
267 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
270 _freeze_record.processor_info.clear ();
272 if ((prop = fnode->property (X_("playlist"))) != 0) {
273 boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
275 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
277 _freeze_record.playlist.reset();
278 _freeze_record.state = NoFreeze;
283 if ((prop = fnode->property (X_("state"))) != 0) {
284 _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
287 XMLNodeConstIterator citer;
288 XMLNodeList clist = fnode->children();
290 for (citer = clist.begin(); citer != clist.end(); ++citer) {
291 if ((*citer)->name() != X_("processor")) {
295 if ((prop = (*citer)->property (X_("id"))) == 0) {
299 FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
300 boost::shared_ptr<Processor>());
301 frii->id = prop->value ();
302 _freeze_record.processor_info.push_back (frii);
306 if (midi_diskstream ()) {
307 midi_diskstream()->set_block_size (_session.get_block_size ());
313 /** @param need_butler to be set to true if this track now needs the butler, otherwise it can be left alone
317 MidiTrack::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
319 Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
324 boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
326 if (n_outputs().n_total() == 0 && _processors.empty()) {
335 framepos_t transport_frame = _session.transport_frame();
338 framecnt_t playback_distance;
340 if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
341 /* need to do this so that the diskstream sets its
342 playback distance to zero, thus causing diskstream::commit
345 BufferSet bufs; /* empty set - is OK, since nothing will happen */
347 dret = diskstream->process (bufs, transport_frame, 0, playback_distance, false);
348 need_butler = diskstream->commit (playback_distance);
352 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
354 fill_buffers_with_input (bufs, _input, nframes);
356 if (_meter_point == MeterInput) {
357 _meter->run (bufs, start_frame, end_frame, nframes, true);
360 /* filter captured data before the diskstream sees it */
362 filter_channels (bufs, get_capture_channel_mode(), get_capture_channel_mask());
366 if ((dret = diskstream->process (bufs, transport_frame, nframes, playback_distance, (monitoring_state() == MonitoringDisk))) != 0) {
367 need_butler = diskstream->commit (playback_distance);
372 /* filter playback data before we do anything else */
374 filter_channels (bufs, get_playback_channel_mode(), get_playback_channel_mask ());
376 if (monitoring_state() == MonitoringInput) {
378 /* not actually recording, but we want to hear the input material anyway,
379 at least potentially (depending on monitoring options)
382 /* because the playback buffer is event based and not a
383 * continuous stream, we need to make sure that we empty
384 * it of events every cycle to avoid it filling up with events
385 * read from disk, while we are actually monitoring input
388 diskstream->flush_playback (start_frame, end_frame);
393 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
395 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
397 /* final argument: don't waste time with automation if we're not recording or rolling */
399 process_output_buffers (bufs, start_frame, end_frame, nframes,
400 declick, (!diskstream->record_enabled() && !_session.transport_stopped()));
402 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
403 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
405 d->flush_buffers (nframes);
409 need_butler = diskstream->commit (playback_distance);
415 MidiTrack::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool state_changing)
417 int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing);
419 if (ret == 0 && _step_editing) {
420 push_midi_input_to_step_edit_ringbuffer (nframes);
427 MidiTrack::realtime_locate ()
429 Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
435 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
436 (*i)->realtime_locate ();
439 midi_diskstream()->reset_tracker ();
443 MidiTrack::realtime_handle_transport_stopped ()
445 Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
451 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
452 (*i)->realtime_handle_transport_stopped ();
457 MidiTrack::push_midi_input_to_step_edit_ringbuffer (framecnt_t nframes)
459 PortSet& ports (_input->ports());
461 for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
463 Buffer& b (p->get_buffer (nframes));
464 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
467 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
469 const Evoral::MIDIEvent<framepos_t> ev(*e, false);
471 /* note on, since for step edit, note length is determined
475 if (ev.is_note_on()) {
476 /* we don't care about the time for this purpose */
477 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
484 MidiTrack::filter_channels (BufferSet& bufs, ChannelMode mode, uint32_t mask)
486 if (mode == AllChannels) {
490 MidiBuffer& buf (bufs.get_midi (0));
492 for (MidiBuffer::iterator e = buf.begin(); e != buf.end(); ) {
494 Evoral::MIDIEvent<framepos_t> ev(*e, false);
496 if (ev.is_channel_event()) {
499 if (0 == ((1<<ev.channel()) & mask)) {
506 ev.set_channel (PBD::ffs (mask) - 1);
510 /* handled by the opening if() */
521 MidiTrack::write_out_of_band_data (BufferSet& bufs, framepos_t /*start*/, framepos_t /*end*/, framecnt_t nframes)
523 MidiBuffer& buf (bufs.get_midi (0));
525 // Append immediate events
527 if (_immediate_events.read_space()) {
529 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 has %2 of immediate events to deliver\n",
530 name(), _immediate_events.read_space()));
532 /* write as many of the immediate events as we can, but give "true" as
533 * the last argument ("stop on overflow in destination") so that we'll
534 * ship the rest out next time.
536 * the (nframes-1) argument puts all these events at the last
537 * possible position of the output buffer, so that we do not
538 * violate monotonicity when writing.
541 _immediate_events.read (buf, 0, 1, nframes-1, true);
546 MidiTrack::export_stuff (BufferSet& /*bufs*/, framepos_t /*start_frame*/, framecnt_t /*nframes*/,
547 boost::shared_ptr<Processor> /*endpoint*/, bool /*include_endpoint*/, bool /*forexport*/)
552 boost::shared_ptr<Region>
553 MidiTrack::bounce (InterThreadInfo& /*itt*/)
555 std::cerr << "MIDI bounce currently unsupported" << std::endl;
556 return boost::shared_ptr<Region> ();
560 boost::shared_ptr<Region>
561 MidiTrack::bounce_range (framepos_t /*start*/, framepos_t /*end*/, InterThreadInfo& /*itt*/,
562 boost::shared_ptr<Processor> /*endpoint*/, bool /*include_endpoint*/)
564 std::cerr << "MIDI bounce range currently unsupported" << std::endl;
565 return boost::shared_ptr<Region> ();
569 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
571 std::cerr << "MIDI freeze currently unsupported" << std::endl;
575 MidiTrack::unfreeze ()
577 _freeze_record.state = UnFrozen;
578 FreezeChange (); /* EMIT SIGNAL */
582 MidiTrack::set_note_mode (NoteMode m)
585 midi_diskstream()->set_note_mode(m);
589 MidiTrack::describe_parameter (Evoral::Parameter param)
591 const std::string str(instrument_info().get_controller_name(param));
592 return str.empty() ? Automatable::describe_parameter(param) : str;
596 MidiTrack::midi_panic()
598 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers panic data\n", name()));
599 for (uint8_t channel = 0; channel <= 0xF; channel++) {
600 uint8_t ev[3] = { ((uint8_t) (MIDI_CMD_CONTROL | channel)), ((uint8_t) MIDI_CTL_SUSTAIN), 0 };
601 write_immediate_event(3, ev);
602 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
603 write_immediate_event(3, ev);
604 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
605 write_immediate_event(3, ev);
609 /** \return true on success, false on failure (no buffer space left)
612 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
614 if (!Evoral::midi_event_is_valid(buf, size)) {
615 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
618 const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
619 return (_immediate_events.write(0, type, size, buf) == size);
623 MidiTrack::MidiControl::set_value(double val)
626 if (std::isinf(val)) {
627 cerr << "MIDIControl value is infinity" << endl;
628 } else if (std::isnan(val)) {
629 cerr << "MIDIControl value is NaN" << endl;
630 } else if (val < _list->parameter().min()) {
631 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
632 } else if (val > _list->parameter().max()) {
633 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
642 assert(val <= _list->parameter().max());
643 if ( ! automation_playback()) {
645 uint8_t ev[3] = { _list->parameter().channel(), uint8_t (val), 0 };
646 switch(_list->parameter().type()) {
647 case MidiCCAutomation:
648 ev[0] += MIDI_CMD_CONTROL;
649 ev[1] = _list->parameter().id();
653 case MidiPgmChangeAutomation:
655 ev[0] += MIDI_CMD_PGM_CHANGE;
659 case MidiChannelPressureAutomation:
661 ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
665 case MidiPitchBenderAutomation:
666 ev[0] += MIDI_CMD_BENDER;
667 ev[1] = 0x7F & int(val);
668 ev[2] = 0x7F & (int(val) >> 7);
674 _route->write_immediate_event(size, ev);
677 AutomationControl::set_value(val);
681 MidiTrack::set_step_editing (bool yn)
683 if (_session.record_status() != Session::Disabled) {
687 if (yn != _step_editing) {
689 StepEditStatusChange (yn);
693 boost::shared_ptr<SMFSource>
694 MidiTrack::write_source (uint32_t)
696 return midi_diskstream()->write_source ();
700 MidiTrack::set_playback_channel_mode(ChannelMode mode, uint16_t mask)
702 ChannelMode old = get_playback_channel_mode ();
703 uint16_t old_mask = get_playback_channel_mask ();
705 if (old != mode || mask != old_mask) {
706 _set_playback_channel_mode (mode, mask);
707 PlaybackChannelModeChanged ();
708 _session.set_dirty ();
713 MidiTrack::set_capture_channel_mode(ChannelMode mode, uint16_t mask)
715 ChannelMode old = get_capture_channel_mode ();
716 uint16_t old_mask = get_capture_channel_mask ();
718 if (old != mode || mask != old_mask) {
719 _set_capture_channel_mode (mode, mask);
720 CaptureChannelModeChanged ();
721 _session.set_dirty ();
726 MidiTrack::set_playback_channel_mask (uint16_t mask)
728 uint16_t old = get_playback_channel_mask();
731 _set_playback_channel_mask (mask);
732 PlaybackChannelMaskChanged ();
733 _session.set_dirty ();
738 MidiTrack::set_capture_channel_mask (uint16_t mask)
740 uint16_t old = get_capture_channel_mask();
743 _set_capture_channel_mask (mask);
744 CaptureChannelMaskChanged ();
745 _session.set_dirty ();
749 boost::shared_ptr<MidiPlaylist>
750 MidiTrack::midi_playlist ()
752 return midi_diskstream()->midi_playlist ();
756 MidiTrack::diskstream_data_recorded (boost::weak_ptr<MidiSource> src)
758 DataRecorded (src); /* EMIT SIGNAL */
762 MidiTrack::input_active () const
764 return _input_active;
768 MidiTrack::set_input_active (bool yn)
770 if (yn != _input_active) {
772 map_input_active (yn);
773 InputActiveChanged (); /* EMIT SIGNAL */
778 MidiTrack::map_input_active (bool yn)
784 PortSet& ports (_input->ports());
786 for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
787 boost::shared_ptr<MidiPort> mp = boost::dynamic_pointer_cast<MidiPort> (*p);
788 if (yn != mp->input_active()) {
789 mp->set_input_active (yn);
795 MidiTrack::track_input_active (IOChange change, void* /* src */)
797 if (change.type & IOChange::ConfigurationChanged) {
798 map_input_active (_input_active);
802 boost::shared_ptr<Diskstream>
803 MidiTrack::diskstream_factory (XMLNode const & node)
805 return boost::shared_ptr<Diskstream> (new MidiDiskstream (_session, node));
808 boost::shared_ptr<MidiBuffer>
809 MidiTrack::get_gui_feed_buffer () const
811 return midi_diskstream()->get_gui_feed_buffer ();
815 MidiTrack::act_on_mute ()
817 /* this is called right after our mute status has changed.
818 if we are now muted, send suitable output to shutdown
821 XXX we should should also stop all relevant note trackers.
824 /* If we haven't got a diskstream yet, there's nothing to worry about,
825 and we can't call get_channel_mask() anyway.
827 if (!midi_diskstream()) {
832 /* only send messages for channels we are using */
834 uint16_t mask = get_playback_channel_mask();
836 for (uint8_t channel = 0; channel <= 0xF; channel++) {
838 if ((1<<channel) & mask) {
840 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers mute message to channel %2\n", name(), channel+1));
841 uint8_t ev[3] = { ((uint8_t) (MIDI_CMD_CONTROL | channel)), MIDI_CTL_SUSTAIN, 0 };
842 write_immediate_event (3, ev);
843 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
844 write_immediate_event (3, ev);
851 MidiTrack::set_monitoring (MonitorChoice mc)
853 if (mc != _monitoring) {
855 Track::set_monitoring (mc);
857 /* monitoring state changed, so flush out any on notes at the
861 PortSet& ports (_output->ports());
863 for (PortSet::iterator p = ports.begin(); p != ports.end(); ++p) {
864 boost::shared_ptr<MidiPort> mp = boost::dynamic_pointer_cast<MidiPort> (*p);
866 mp->require_resolve ();
870 boost::shared_ptr<MidiDiskstream> md (midi_diskstream());
873 md->reset_tracker ();
879 MidiTrack::monitoring_state () const
881 MonitorState ms = Track::monitoring_state();
882 if (ms == MonitoringSilence) {
883 return MonitoringInput;