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"
21 #include "pbd/enumwriter.h"
22 #include "midi++/events.h"
23 #include "evoral/midi_util.h"
25 #include "ardour/amp.h"
26 #include "ardour/buffer_set.h"
27 #include "ardour/delivery.h"
28 #include "ardour/io_processor.h"
29 #include "ardour/meter.h"
30 #include "ardour/midi_diskstream.h"
31 #include "ardour/midi_playlist.h"
32 #include "ardour/midi_port.h"
33 #include "ardour/midi_region.h"
34 #include "ardour/midi_source.h"
35 #include "ardour/midi_track.h"
36 #include "ardour/panner.h"
37 #include "ardour/port.h"
38 #include "ardour/processor.h"
39 #include "ardour/route_group_specialized.h"
40 #include "ardour/session.h"
41 #include "ardour/session_playlists.h"
42 #include "ardour/utils.h"
47 using namespace ARDOUR;
50 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
51 : Track (sess, name, flag, mode, DataType::MIDI)
52 , _immediate_events(1024) // FIXME: size?
53 , _step_edit_ring_buffer(64) // FIXME: size?
54 , _note_mode(Sustained)
55 , _step_editing (false)
56 , _default_channel (0)
59 use_new_diskstream ();
62 _freeze_record.state = NoFreeze;
63 _saved_meter_point = _meter_point;
67 MidiTrack::MidiTrack (Session& sess, const XMLNode& node, int /*version*/)
68 : Track (sess, node, DataType::MIDI)
69 , _immediate_events(1024) // FIXME: size?
70 , _step_edit_ring_buffer(64) // FIXME: size?
71 , _note_mode(Sustained)
72 , _step_editing (false)
73 , _default_channel (0)
76 _set_state (node, Stateful::loading_state_version, false);
79 MidiTrack::~MidiTrack ()
84 MidiTrack::use_new_diskstream ()
86 MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
88 if (_flags & Hidden) {
89 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
91 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
94 assert(_mode != Destructive);
96 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
97 _session.add_diskstream (ds);
99 set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
103 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
106 _diskstream->set_route (*this);
107 _diskstream->set_destructive (_mode == Destructive);
109 _diskstream->set_record_enabled (false);
110 //_diskstream->monitor_input (false);
112 DiskstreamChanged (); /* EMIT SIGNAL */
118 MidiTrack::use_diskstream (string name)
120 boost::shared_ptr<MidiDiskstream> dstream;
122 if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream>(_session.diskstream_by_name (name))) == 0) {
123 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), name) << endmsg;
127 return set_diskstream (dstream);
131 MidiTrack::use_diskstream (const PBD::ID& id)
133 boost::shared_ptr<MidiDiskstream> dstream;
135 if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
136 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
140 return set_diskstream (dstream);
143 boost::shared_ptr<MidiDiskstream>
144 MidiTrack::midi_diskstream() const
146 return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
150 MidiTrack::set_state (const XMLNode& node, int version)
152 return _set_state (node, version, true);
156 MidiTrack::_set_state (const XMLNode& node, int version, bool call_base)
158 const XMLProperty *prop;
159 XMLNodeConstIterator iter;
161 if (Route::_set_state (node, version, call_base)) {
165 // No destructive MIDI tracks (yet?)
168 if ((prop = node.property (X_("note-mode"))) != 0) {
169 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
171 _note_mode = Sustained;
174 if ((prop = node.property ("midi-thru")) != 0) {
175 set_midi_thru (prop->value() == "yes");
178 if ((prop = node.property ("default-channel")) != 0) {
179 set_default_channel ((uint8_t) atoi (prop->value()));
182 if ((prop = node.property ("diskstream-id")) == 0) {
184 /* some old sessions use the diskstream name rather than the ID */
186 if ((prop = node.property ("diskstream")) == 0) {
187 fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
192 if (use_diskstream (prop->value())) {
198 PBD::ID id (prop->value());
201 /* this wierd hack is used when creating tracks from a template. there isn't
202 a particularly good time to interpose between setting the first part of
203 the track state (notably Route::set_state() and the track mode), and the
204 second part (diskstream stuff). So, we have a special ID for the diskstream
205 that means "you should create a new diskstream here, not look for
210 use_new_diskstream ();
211 } else if (use_diskstream (id)) {
217 XMLNodeConstIterator niter;
220 nlist = node.children();
221 for (niter = nlist.begin(); niter != nlist.end(); ++niter){
224 if (child->name() == X_("recenable")) {
225 _rec_enable_control->set_state (*child, version);
226 _session.add_controllable (_rec_enable_control);
230 pending_state = const_cast<XMLNode*> (&node);
232 if (_session.state_of_the_state() & Session::Loading) {
233 _session.StateReady.connect_same_thread (*this, boost::bind (&MidiTrack::set_state_part_two, this));
235 set_state_part_two ();
242 MidiTrack::state(bool full_state)
244 XMLNode& root (Route::state(full_state));
245 XMLNode* freeze_node;
248 if (_freeze_record.playlist) {
251 freeze_node = new XMLNode (X_("freeze-info"));
252 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
253 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
255 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
256 inode = new XMLNode (X_("processor"));
257 (*i)->id.print (buf, sizeof(buf));
258 inode->add_property (X_("id"), buf);
259 inode->add_child_copy ((*i)->state);
261 freeze_node->add_child_nocopy (*inode);
264 root.add_child_nocopy (*freeze_node);
267 /* Alignment: act as a proxy for the diskstream */
269 XMLNode* align_node = new XMLNode (X_("Alignment"));
270 AlignStyle as = _diskstream->alignment_style ();
271 align_node->add_property (X_("style"), enum_2_string (as));
272 root.add_child_nocopy (*align_node);
274 root.add_property (X_("note-mode"), enum_2_string (_note_mode));
276 /* we don't return diskstream state because we don't
277 own the diskstream exclusively. control of the diskstream
278 state is ceded to the Session, even if we create the
282 _diskstream->id().print (buf, sizeof(buf));
283 root.add_property ("diskstream-id", buf);
285 root.add_child_nocopy (_rec_enable_control->get_state());
287 root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
288 root.add_property ("note-mode", enum_2_string (_note_mode));
289 root.add_property ("midi-thru", (_midi_thru ? "yes" : "no"));
290 snprintf (buf, sizeof (buf), "%d", (int) _default_channel);
291 root.add_property ("default-channel", buf);
297 MidiTrack::set_state_part_two ()
301 LocaleGuard lg (X_("POSIX"));
303 /* This is called after all session state has been restored but before
304 have been made ports and connections are established.
307 if (pending_state == 0) {
311 if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
313 _freeze_record.state = Frozen;
315 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
318 _freeze_record.processor_info.clear ();
320 if ((prop = fnode->property (X_("playlist"))) != 0) {
321 boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
323 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
325 _freeze_record.playlist.reset();
326 _freeze_record.state = NoFreeze;
331 if ((prop = fnode->property (X_("state"))) != 0) {
332 _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
335 XMLNodeConstIterator citer;
336 XMLNodeList clist = fnode->children();
338 for (citer = clist.begin(); citer != clist.end(); ++citer) {
339 if ((*citer)->name() != X_("processor")) {
343 if ((prop = (*citer)->property (X_("id"))) == 0) {
347 FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
348 boost::shared_ptr<Processor>());
349 frii->id = prop->value ();
350 _freeze_record.processor_info.push_back (frii);
354 /* Alignment: act as a proxy for the diskstream */
356 if ((fnode = find_named_node (*pending_state, X_("Alignment"))) != 0) {
358 if ((prop = fnode->property (X_("style"))) != 0) {
360 /* fix for older sessions from before EnumWriter */
364 if (prop->value() == "capture") {
365 pstr = "CaptureTime";
366 } else if (prop->value() == "existing") {
367 pstr = "ExistingMaterial";
369 pstr = prop->value();
372 AlignStyle as = AlignStyle (string_2_enum (pstr, as));
373 _diskstream->set_persistent_align_style (as);
380 MidiTrack::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
381 bool can_record, bool rec_monitors_input)
384 boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
387 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
389 // automation snapshot can also be called from the non-rt context
390 // and it uses the redirect list, so we take the lock out here
391 automation_snapshot (start_frame);
395 if (n_outputs().n_total() == 0 && _processors.empty()) {
404 nframes_t transport_frame = _session.transport_frame();
407 if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
408 /* need to do this so that the diskstream sets its
409 playback distance to zero, thus causing diskstream::commit
412 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input);
417 if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input)) != 0) {
422 /* special condition applies */
424 if (_meter_point == MeterInput) {
425 _input->process_input (_meter, start_frame, end_frame, nframes);
428 if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
430 /* not actually recording, but we want to hear the input material anyway,
431 at least potentially (depending on monitoring options)
434 passthru (start_frame, end_frame, nframes, 0);
438 XXX is it true that the earlier test on n_outputs()
439 means that we can avoid checking it again here? i think
440 so, because changing the i/o configuration of an IO
441 requires holding the AudioEngine lock, which we hold
442 while in the process() tree.
446 /* copy the diskstream data to all output buffers */
448 //const size_t limit = n_process_buffers().n_audio();
449 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
450 MidiBuffer& mbuf (bufs.get_midi (0));
452 diskstream->get_playback (mbuf, start_frame, end_frame);
454 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
456 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
458 process_output_buffers (bufs, start_frame, end_frame, nframes,
459 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
463 _main_outs->flush (nframes, end_frame - start_frame - 1);
469 MidiTrack::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
470 bool state_changing, bool can_record, bool rec_monitors_input)
472 int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
474 if (ret == 0 && diskstream()->record_enabled() && _step_editing) {
475 push_midi_input_to_step_edit_ringbuffer (nframes);
482 MidiTrack::handle_transport_stopped (bool abort, bool did_locate, bool flush_processors)
485 _main_outs->transport_stopped ();
486 Route::handle_transport_stopped (abort, did_locate, flush_processors);
491 MidiTrack::push_midi_input_to_step_edit_ringbuffer (nframes_t nframes)
493 PortSet& ports (_input->ports());
495 for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
497 Buffer& b (p->get_buffer (nframes));
498 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
501 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
503 const Evoral::MIDIEvent<nframes_t> ev(*e, false);
505 /* we don't care about the time for this purpose */
507 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
513 MidiTrack::write_out_of_band_data (BufferSet& bufs, sframes_t /*start*/, sframes_t /*end*/, nframes_t nframes)
515 // Append immediate events
516 MidiBuffer& buf (bufs.get_midi (0));
517 _immediate_events.read (buf, 0, 0, nframes - 1); // all stamps = 0
519 // MIDI thru: send incoming data "through" output
520 if (_midi_thru && _session.transport_speed() != 0.0f && _input->n_ports().n_midi()) {
521 buf.merge_in_place (_input->midi(0)->get_midi_buffer(nframes));
526 MidiTrack::export_stuff (BufferSet& /*bufs*/, nframes_t /*nframes*/, sframes_t /*end_frame*/)
532 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
534 Route::set_latency_delay (longest_session_latency);
535 _diskstream->set_roll_delay (_roll_delay);
538 boost::shared_ptr<Region>
539 MidiTrack::bounce (InterThreadInfo& /*itt*/)
542 // vector<MidiSource*> srcs;
543 // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
544 return boost::shared_ptr<Region> ();
548 boost::shared_ptr<Region>
549 MidiTrack::bounce_range (nframes_t /*start*/, nframes_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
552 //vector<MidiSource*> srcs;
553 //return _session.write_one_track (*this, start, end, false, srcs, itt);
554 return boost::shared_ptr<Region> ();
558 MidiTrack::freeze (InterThreadInfo& /*itt*/)
563 MidiTrack::unfreeze ()
565 _freeze_record.state = UnFrozen;
566 FreezeChange (); /* EMIT SIGNAL */
570 MidiTrack::set_note_mode (NoteMode m)
573 midi_diskstream()->set_note_mode(m);
577 MidiTrack::midi_panic()
579 for (uint8_t channel = 0; channel <= 0xF; channel++) {
580 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
581 write_immediate_event(3, ev);
582 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
583 write_immediate_event(3, ev);
584 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
585 write_immediate_event(3, ev);
589 /** \return true on success, false on failure (no buffer space left)
592 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
594 if (!Evoral::midi_event_is_valid(buf, size)) {
595 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
598 const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
599 return (_immediate_events.write(0, type, size, buf) == size);
603 MidiTrack::MidiControl::set_value(float val)
607 cerr << "MIDIControl value is infinity" << endl;
608 } else if (isnan(val)) {
609 cerr << "MIDIControl value is NaN" << endl;
610 } else if (val < _list->parameter().min()) {
611 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
612 } else if (val > _list->parameter().max()) {
613 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
622 assert(val <= _list->parameter().max());
625 if ( ! automation_playback()) {
626 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
627 switch(_list->parameter().type()) {
628 case MidiCCAutomation:
629 ev[0] += MIDI_CMD_CONTROL;
630 ev[1] = _list->parameter().id();
634 case MidiPgmChangeAutomation:
636 ev[0] += MIDI_CMD_PGM_CHANGE;
640 case MidiChannelPressureAutomation:
642 ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
646 case MidiPitchBenderAutomation:
647 ev[0] += MIDI_CMD_BENDER;
648 ev[1] = 0x7F & int(val);
649 ev[2] = 0x7F & (int(val) >> 7);
655 _route->write_immediate_event(size, ev);
658 AutomationControl::set_value(val);
662 MidiTrack::set_step_editing (bool yn)
668 MidiTrack::set_default_channel (uint8_t chn)
670 _default_channel = std::min ((unsigned int) chn, 15U);
674 MidiTrack::set_midi_thru (bool yn)