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/io_processor.h"
31 #include "ardour/meter.h"
32 #include "ardour/midi_diskstream.h"
33 #include "ardour/midi_playlist.h"
34 #include "ardour/midi_region.h"
35 #include "ardour/midi_source.h"
36 #include "ardour/midi_track.h"
37 #include "ardour/panner.h"
38 #include "ardour/processor.h"
39 #include "ardour/route_group_specialized.h"
40 #include "ardour/session.h"
41 #include "ardour/utils.h"
46 using namespace ARDOUR;
49 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
50 : Track (sess, name, flag, mode, DataType::MIDI)
51 , _immediate_events(1024) // FIXME: size?
52 , _note_mode(Sustained)
54 use_new_diskstream ();
57 _freeze_record.state = NoFreeze;
58 _saved_meter_point = _meter_point;
62 MidiTrack::MidiTrack (Session& sess, const XMLNode& node)
63 : Track (sess, node, DataType::MIDI )
64 , _immediate_events(1024) // FIXME: size?
65 , _note_mode(Sustained)
67 _set_state(node, false);
70 MidiTrack::~MidiTrack ()
75 MidiTrack::use_new_diskstream ()
77 MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
79 if (_flags & Hidden) {
80 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
82 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
85 assert(_mode != Destructive);
87 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
88 _session.add_diskstream (ds);
90 set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
94 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
97 _diskstream->set_io (*this);
98 _diskstream->set_destructive (_mode == Destructive);
100 _diskstream->set_record_enabled (false);
101 //_diskstream->monitor_input (false);
103 ic_connection.disconnect();
104 ic_connection = input_changed.connect (mem_fun (*_diskstream, &MidiDiskstream::handle_input_change));
106 DiskstreamChanged (); /* EMIT SIGNAL */
112 MidiTrack::use_diskstream (string name)
114 boost::shared_ptr<MidiDiskstream> dstream;
116 if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream>(_session.diskstream_by_name (name))) == 0) {
117 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), name) << endmsg;
121 return set_diskstream (dstream);
125 MidiTrack::use_diskstream (const PBD::ID& id)
127 boost::shared_ptr<MidiDiskstream> dstream;
129 if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
130 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
134 return set_diskstream (dstream);
137 boost::shared_ptr<MidiDiskstream>
138 MidiTrack::midi_diskstream() const
140 return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
144 MidiTrack::set_state (const XMLNode& node)
146 return _set_state (node, true);
150 MidiTrack::_set_state (const XMLNode& node, bool call_base)
152 const XMLProperty *prop;
153 XMLNodeConstIterator iter;
155 if (Route::_set_state (node, call_base)) {
159 // No destructive MIDI tracks (yet?)
162 if ((prop = node.property (X_("note-mode"))) != 0) {
163 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
165 _note_mode = Sustained;
168 if ((prop = node.property ("diskstream-id")) == 0) {
170 /* some old sessions use the diskstream name rather than the ID */
172 if ((prop = node.property ("diskstream")) == 0) {
173 fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
178 if (use_diskstream (prop->value())) {
184 PBD::ID id (prop->value());
187 /* this wierd hack is used when creating tracks from a template. there isn't
188 a particularly good time to interpose between setting the first part of
189 the track state (notably Route::set_state() and the track mode), and the
190 second part (diskstream stuff). So, we have a special ID for the diskstream
191 that means "you should create a new diskstream here, not look for
196 use_new_diskstream ();
197 } else if (use_diskstream (id)) {
203 XMLNodeConstIterator niter;
206 nlist = node.children();
207 for (niter = nlist.begin(); niter != nlist.end(); ++niter){
210 if (child->name() == X_("recenable")) {
211 _rec_enable_control->set_state (*child);
212 _session.add_controllable (_rec_enable_control);
216 pending_state = const_cast<XMLNode*> (&node);
218 if (_session.state_of_the_state() & Session::Loading) {
219 _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
221 set_state_part_two ();
228 MidiTrack::state(bool full_state)
230 XMLNode& root (Route::state(full_state));
231 XMLNode* freeze_node;
234 if (_freeze_record.playlist) {
237 freeze_node = new XMLNode (X_("freeze-info"));
238 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
239 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
241 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
242 inode = new XMLNode (X_("processor"));
243 (*i)->id.print (buf, sizeof(buf));
244 inode->add_property (X_("id"), buf);
245 inode->add_child_copy ((*i)->state);
247 freeze_node->add_child_nocopy (*inode);
250 root.add_child_nocopy (*freeze_node);
253 /* Alignment: act as a proxy for the diskstream */
255 XMLNode* align_node = new XMLNode (X_("Alignment"));
256 AlignStyle as = _diskstream->alignment_style ();
257 align_node->add_property (X_("style"), enum_2_string (as));
258 root.add_child_nocopy (*align_node);
260 root.add_property (X_("note-mode"), enum_2_string (_note_mode));
262 /* we don't return diskstream state because we don't
263 own the diskstream exclusively. control of the diskstream
264 state is ceded to the Session, even if we create the
268 _diskstream->id().print (buf, sizeof(buf));
269 root.add_property ("diskstream-id", buf);
271 root.add_child_nocopy (_rec_enable_control->get_state());
277 MidiTrack::set_state_part_two ()
281 LocaleGuard lg (X_("POSIX"));
283 /* This is called after all session state has been restored but before
284 have been made ports and connections are established.
287 if (pending_state == 0) {
291 if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
293 _freeze_record.state = Frozen;
295 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
298 _freeze_record.processor_info.clear ();
300 if ((prop = fnode->property (X_("playlist"))) != 0) {
301 boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
303 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
305 _freeze_record.playlist.reset();
306 _freeze_record.state = NoFreeze;
311 if ((prop = fnode->property (X_("state"))) != 0) {
312 _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
315 XMLNodeConstIterator citer;
316 XMLNodeList clist = fnode->children();
318 for (citer = clist.begin(); citer != clist.end(); ++citer) {
319 if ((*citer)->name() != X_("processor")) {
323 if ((prop = (*citer)->property (X_("id"))) == 0) {
327 FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
328 boost::shared_ptr<Processor>());
329 frii->id = prop->value ();
330 _freeze_record.processor_info.push_back (frii);
334 /* Alignment: act as a proxy for the diskstream */
336 if ((fnode = find_named_node (*pending_state, X_("Alignment"))) != 0) {
338 if ((prop = fnode->property (X_("style"))) != 0) {
340 /* fix for older sessions from before EnumWriter */
344 if (prop->value() == "capture") {
345 pstr = "CaptureTime";
346 } else if (prop->value() == "existing") {
347 pstr = "ExistingMaterial";
349 pstr = prop->value();
352 AlignStyle as = AlignStyle (string_2_enum (pstr, as));
353 _diskstream->set_persistent_align_style (as);
360 MidiTrack::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
361 bool can_record, bool rec_monitors_input)
364 boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
366 prepare_inputs (nframes);
369 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
371 // automation snapshot can also be called from the non-rt context
372 // and it uses the redirect list, so we take the lock out here
373 automation_snapshot (start_frame);
377 if (n_outputs().n_total() == 0 && _processors.empty()) {
386 nframes_t transport_frame = _session.transport_frame();
389 if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
390 /* need to do this so that the diskstream sets its
391 playback distance to zero, thus causing diskstream::commit
394 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input);
399 if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input)) != 0) {
405 /* special condition applies */
407 if (_meter_point == MeterInput) {
408 just_meter_input (start_frame, end_frame, nframes);
411 if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
413 /* not actually recording, but we want to hear the input material anyway,
414 at least potentially (depending on monitoring options)
417 passthru (start_frame, end_frame, nframes, 0);
421 XXX is it true that the earlier test on n_outputs()
422 means that we can avoid checking it again here? i think
423 so, because changing the i/o configuration of an IO
424 requires holding the AudioEngine lock, which we hold
425 while in the process() tree.
429 /* copy the diskstream data to all output buffers */
431 //const size_t limit = n_process_buffers().n_audio();
432 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
434 diskstream->get_playback(bufs.get_midi(0), start_frame, end_frame);
436 process_output_buffers (bufs, start_frame, end_frame, nframes,
437 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
441 flush_outputs (nframes);
447 MidiTrack::write_controller_messages(MidiBuffer& output_buf, sframes_t start, sframes_t end, nframes_t nframes)
449 // Append immediate events (UI controls)
451 // XXX TAKE _port_offset in Port into account???
453 _immediate_events.read (output_buf, 0, 0, nframes - 1); // all stamps = 0
457 MidiTrack::export_stuff (BufferSet& bufs, nframes_t nframes, sframes_t end_frame)
463 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
465 Route::set_latency_delay (longest_session_latency);
466 _diskstream->set_roll_delay (_roll_delay);
469 boost::shared_ptr<Region>
470 MidiTrack::bounce (InterThreadInfo& itt)
473 // vector<MidiSource*> srcs;
474 // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
475 return boost::shared_ptr<Region> ();
479 boost::shared_ptr<Region>
480 MidiTrack::bounce_range (nframes_t start, nframes_t end, InterThreadInfo& itt, bool enable_processing)
483 //vector<MidiSource*> srcs;
484 //return _session.write_one_track (*this, start, end, false, srcs, itt);
485 return boost::shared_ptr<Region> ();
489 MidiTrack::freeze (InterThreadInfo& itt)
494 MidiTrack::unfreeze ()
496 _freeze_record.state = UnFrozen;
497 FreezeChange (); /* EMIT SIGNAL */
501 MidiTrack::set_note_mode (NoteMode m)
504 midi_diskstream()->set_note_mode(m);
508 MidiTrack::midi_panic()
510 for (uint8_t channel = 0; channel <= 0xF; channel++) {
511 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
512 write_immediate_event(3, ev);
513 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
514 write_immediate_event(3, ev);
515 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
516 write_immediate_event(3, ev);
520 /** \return true on success, false on failure (no buffer space left)
523 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
525 if (!Evoral::midi_event_is_valid(buf, size)) {
526 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
529 const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
530 return (_immediate_events.write(0, type, size, buf) == size);
534 MidiTrack::MidiControl::set_value(float val)
538 cerr << "MIDIControl value is infinity" << endl;
539 } else if (isnan(val)) {
540 cerr << "MIDIControl value is NaN" << endl;
541 } else if (val < _list->parameter().min()) {
542 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
543 } else if (val > _list->parameter().max()) {
544 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
553 assert(val <= _list->parameter().max());
556 if ( ! automation_playback()) {
557 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
558 switch(_list->parameter().type()) {
559 case MidiCCAutomation:
560 ev[0] += MIDI_CMD_CONTROL;
561 ev[1] = _list->parameter().id();
565 case MidiPgmChangeAutomation:
567 ev[0] += MIDI_CMD_PGM_CHANGE;
571 case MidiChannelPressureAutomation:
573 ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
577 case MidiPitchBenderAutomation:
578 ev[0] += MIDI_CMD_BENDER;
579 ev[1] = 0x7F & int(val);
580 ev[2] = 0x7F & (int(val) >> 7);
586 _route->write_immediate_event(size, ev);
589 AutomationControl::set_value(val);