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"
26 #include "evoral/midi_util.h"
28 #include "ardour/amp.h"
29 #include "ardour/buffer_set.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_region.h"
36 #include "ardour/midi_source.h"
37 #include "ardour/midi_track.h"
38 #include "ardour/panner.h"
39 #include "ardour/port.h"
40 #include "ardour/processor.h"
41 #include "ardour/route_group_specialized.h"
42 #include "ardour/session.h"
43 #include "ardour/utils.h"
48 using namespace ARDOUR;
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)
58 use_new_diskstream ();
61 _freeze_record.state = NoFreeze;
62 _saved_meter_point = _meter_point;
66 MidiTrack::MidiTrack (Session& sess, const XMLNode& node)
67 : Track (sess, node, DataType::MIDI )
68 , _immediate_events(1024) // FIXME: size?
69 , _step_edit_ring_buffer(64) // FIXME: size?
70 , _note_mode(Sustained)
71 , _step_editing (false)
73 _set_state(node, false);
76 MidiTrack::~MidiTrack ()
81 MidiTrack::use_new_diskstream ()
83 MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
85 if (_flags & Hidden) {
86 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
88 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
91 assert(_mode != Destructive);
93 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
94 _session.add_diskstream (ds);
96 set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
100 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
103 _diskstream->set_route (*this);
104 _diskstream->set_destructive (_mode == Destructive);
106 _diskstream->set_record_enabled (false);
107 //_diskstream->monitor_input (false);
109 ic_connection.disconnect();
110 ic_connection = _input->changed.connect (mem_fun (*_diskstream, &MidiDiskstream::handle_input_change));
112 DiskstreamChanged (); /* EMIT SIGNAL */
118 MidiTrack::use_diskstream (string name)
120 boost::shared_ptr<MidiDiskstream> dstream;
122 cerr << "\n\n\nMIDI use diskstream\n";
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 cerr << "\n\n\nMIDI found DS\n";
130 return set_diskstream (dstream);
134 MidiTrack::use_diskstream (const PBD::ID& id)
136 boost::shared_ptr<MidiDiskstream> dstream;
138 if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
139 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
143 return set_diskstream (dstream);
146 boost::shared_ptr<MidiDiskstream>
147 MidiTrack::midi_diskstream() const
149 return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
153 MidiTrack::set_state (const XMLNode& node)
155 return _set_state (node, true);
159 MidiTrack::_set_state (const XMLNode& node, bool call_base)
161 const XMLProperty *prop;
162 XMLNodeConstIterator iter;
164 if (Route::_set_state (node, call_base)) {
168 // No destructive MIDI tracks (yet?)
171 if ((prop = node.property (X_("note-mode"))) != 0) {
172 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
174 _note_mode = Sustained;
177 if ((prop = node.property ("diskstream-id")) == 0) {
179 /* some old sessions use the diskstream name rather than the ID */
181 if ((prop = node.property ("diskstream")) == 0) {
182 fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
187 if (use_diskstream (prop->value())) {
193 PBD::ID id (prop->value());
196 /* this wierd hack is used when creating tracks from a template. there isn't
197 a particularly good time to interpose between setting the first part of
198 the track state (notably Route::set_state() and the track mode), and the
199 second part (diskstream stuff). So, we have a special ID for the diskstream
200 that means "you should create a new diskstream here, not look for
204 cerr << "\n\n\n\n MIDI track " << name() << " found DS id " << id << endl;
207 use_new_diskstream ();
208 } else if (use_diskstream (id)) {
214 XMLNodeConstIterator niter;
217 nlist = node.children();
218 for (niter = nlist.begin(); niter != nlist.end(); ++niter){
221 if (child->name() == X_("recenable")) {
222 _rec_enable_control->set_state (*child);
223 _session.add_controllable (_rec_enable_control);
227 pending_state = const_cast<XMLNode*> (&node);
229 if (_session.state_of_the_state() & Session::Loading) {
230 _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
232 set_state_part_two ();
239 MidiTrack::state(bool full_state)
241 XMLNode& root (Route::state(full_state));
242 XMLNode* freeze_node;
245 if (_freeze_record.playlist) {
248 freeze_node = new XMLNode (X_("freeze-info"));
249 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
250 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
252 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
253 inode = new XMLNode (X_("processor"));
254 (*i)->id.print (buf, sizeof(buf));
255 inode->add_property (X_("id"), buf);
256 inode->add_child_copy ((*i)->state);
258 freeze_node->add_child_nocopy (*inode);
261 root.add_child_nocopy (*freeze_node);
264 /* Alignment: act as a proxy for the diskstream */
266 XMLNode* align_node = new XMLNode (X_("Alignment"));
267 AlignStyle as = _diskstream->alignment_style ();
268 align_node->add_property (X_("style"), enum_2_string (as));
269 root.add_child_nocopy (*align_node);
271 root.add_property (X_("note-mode"), enum_2_string (_note_mode));
273 /* we don't return diskstream state because we don't
274 own the diskstream exclusively. control of the diskstream
275 state is ceded to the Session, even if we create the
279 _diskstream->id().print (buf, sizeof(buf));
280 root.add_property ("diskstream-id", buf);
282 root.add_child_nocopy (_rec_enable_control->get_state());
284 root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
285 root.add_property ("note-mode", enum_2_string (_note_mode));
291 MidiTrack::set_state_part_two ()
295 LocaleGuard lg (X_("POSIX"));
297 /* This is called after all session state has been restored but before
298 have been made ports and connections are established.
301 if (pending_state == 0) {
305 if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
307 _freeze_record.state = Frozen;
309 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
312 _freeze_record.processor_info.clear ();
314 if ((prop = fnode->property (X_("playlist"))) != 0) {
315 boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
317 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
319 _freeze_record.playlist.reset();
320 _freeze_record.state = NoFreeze;
325 if ((prop = fnode->property (X_("state"))) != 0) {
326 _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
329 XMLNodeConstIterator citer;
330 XMLNodeList clist = fnode->children();
332 for (citer = clist.begin(); citer != clist.end(); ++citer) {
333 if ((*citer)->name() != X_("processor")) {
337 if ((prop = (*citer)->property (X_("id"))) == 0) {
341 FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
342 boost::shared_ptr<Processor>());
343 frii->id = prop->value ();
344 _freeze_record.processor_info.push_back (frii);
348 /* Alignment: act as a proxy for the diskstream */
350 if ((fnode = find_named_node (*pending_state, X_("Alignment"))) != 0) {
352 if ((prop = fnode->property (X_("style"))) != 0) {
354 /* fix for older sessions from before EnumWriter */
358 if (prop->value() == "capture") {
359 pstr = "CaptureTime";
360 } else if (prop->value() == "existing") {
361 pstr = "ExistingMaterial";
363 pstr = prop->value();
366 AlignStyle as = AlignStyle (string_2_enum (pstr, as));
367 _diskstream->set_persistent_align_style (as);
374 MidiTrack::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
375 bool can_record, bool rec_monitors_input)
378 boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
381 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
383 // automation snapshot can also be called from the non-rt context
384 // and it uses the redirect list, so we take the lock out here
385 automation_snapshot (start_frame);
389 if (n_outputs().n_total() == 0 && _processors.empty()) {
398 nframes_t transport_frame = _session.transport_frame();
401 if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
402 /* need to do this so that the diskstream sets its
403 playback distance to zero, thus causing diskstream::commit
406 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input);
411 if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input)) != 0) {
416 /* special condition applies */
418 if (_meter_point == MeterInput) {
419 _input->process_input (_meter, start_frame, end_frame, nframes);
422 if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
424 /* not actually recording, but we want to hear the input material anyway,
425 at least potentially (depending on monitoring options)
428 passthru (start_frame, end_frame, nframes, 0);
432 XXX is it true that the earlier test on n_outputs()
433 means that we can avoid checking it again here? i think
434 so, because changing the i/o configuration of an IO
435 requires holding the AudioEngine lock, which we hold
436 while in the process() tree.
440 /* copy the diskstream data to all output buffers */
442 //const size_t limit = n_process_buffers().n_audio();
443 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
444 MidiBuffer& mbuf (bufs.get_midi (0));
446 diskstream->get_playback (mbuf, start_frame, end_frame);
448 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
450 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
452 // Feed the data through the MidiStateTracker
455 _midi_state_tracker.track (mbuf.begin(), mbuf.end(), did_loop);
458 /* add necessary note offs */
459 cerr << "DID LOOP, RESOLVE NOTES\n";
460 _midi_state_tracker.resolve_notes (mbuf, end_frame-start_frame - 1);
463 process_output_buffers (bufs, start_frame, end_frame, nframes,
464 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
468 _main_outs->flush (nframes);
474 MidiTrack::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
475 bool state_changing, bool can_record, bool rec_monitors_input)
477 int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
479 if (ret == 0 && diskstream()->record_enabled() && _step_editing) {
480 push_midi_input_to_step_edit_ringbuffer (nframes);
487 MidiTrack::handle_transport_stopped (bool abort, bool did_locate, bool flush_processors)
489 /* turn off any notes that are on */
491 MidiBuffer buf (1024); // XXX is this a reasonable size ?
493 _midi_state_tracker.resolve_notes (buf, 0); // time is zero because notes are immediate
495 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
496 write_immediate_event ((*i).size(), (*i).buffer());
499 Route::handle_transport_stopped (abort, did_locate, flush_processors);
504 MidiTrack::push_midi_input_to_step_edit_ringbuffer (nframes_t nframes)
506 PortSet& ports (_input->ports());
508 for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
510 Buffer& b (p->get_buffer (nframes));
511 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
514 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
516 const Evoral::MIDIEvent<nframes_t> ev(*e, false);
518 /* we don't care about the time for this purpose */
520 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
526 MidiTrack::write_out_of_band_data (BufferSet& bufs, sframes_t /*start*/, sframes_t /*end*/, nframes_t nframes)
528 // Append immediate events
530 MidiBuffer& buf (bufs.get_midi (0));
531 _immediate_events.read (buf, 0, 0, nframes - 1); // all stamps = 0
535 MidiTrack::export_stuff (BufferSet& /*bufs*/, nframes_t /*nframes*/, sframes_t /*end_frame*/)
541 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
543 Route::set_latency_delay (longest_session_latency);
544 _diskstream->set_roll_delay (_roll_delay);
547 boost::shared_ptr<Region>
548 MidiTrack::bounce (InterThreadInfo& /*itt*/)
551 // vector<MidiSource*> srcs;
552 // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
553 return boost::shared_ptr<Region> ();
557 boost::shared_ptr<Region>
558 MidiTrack::bounce_range (nframes_t /*start*/, nframes_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
561 //vector<MidiSource*> srcs;
562 //return _session.write_one_track (*this, start, end, false, srcs, itt);
563 return boost::shared_ptr<Region> ();
567 MidiTrack::freeze (InterThreadInfo& /*itt*/)
572 MidiTrack::unfreeze ()
574 _freeze_record.state = UnFrozen;
575 FreezeChange (); /* EMIT SIGNAL */
579 MidiTrack::set_note_mode (NoteMode m)
582 midi_diskstream()->set_note_mode(m);
586 MidiTrack::midi_panic()
588 for (uint8_t channel = 0; channel <= 0xF; channel++) {
589 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
590 write_immediate_event(3, ev);
591 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
592 write_immediate_event(3, ev);
593 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
594 write_immediate_event(3, ev);
598 /** \return true on success, false on failure (no buffer space left)
601 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
603 if (!Evoral::midi_event_is_valid(buf, size)) {
604 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
607 const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
608 return (_immediate_events.write(0, type, size, buf) == size);
612 MidiTrack::MidiControl::set_value(float val)
616 cerr << "MIDIControl value is infinity" << endl;
617 } else if (isnan(val)) {
618 cerr << "MIDIControl value is NaN" << endl;
619 } else if (val < _list->parameter().min()) {
620 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
621 } else if (val > _list->parameter().max()) {
622 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
631 assert(val <= _list->parameter().max());
634 if ( ! automation_playback()) {
635 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
636 switch(_list->parameter().type()) {
637 case MidiCCAutomation:
638 ev[0] += MIDI_CMD_CONTROL;
639 ev[1] = _list->parameter().id();
643 case MidiPgmChangeAutomation:
645 ev[0] += MIDI_CMD_PGM_CHANGE;
649 case MidiChannelPressureAutomation:
651 ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
655 case MidiPitchBenderAutomation:
656 ev[0] += MIDI_CMD_BENDER;
657 ev[1] = 0x7F & int(val);
658 ev[2] = 0x7F & (int(val) >> 7);
664 _route->write_immediate_event(size, ev);
667 AutomationControl::set_value(val);
671 MidiTrack::set_step_editing (bool yn)