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.
30 #include <glibmm/fileutils.h>
31 #include <glibmm/miscutils.h>
33 #include "pbd/xml++.h"
34 #include "pbd/pthread_utils.h"
35 #include "pbd/basename.h"
37 #include "evoral/Control.hpp"
38 #include "evoral/EventSink.hpp"
40 #include "ardour/debug.h"
41 #include "ardour/file_source.h"
42 #include "ardour/midi_channel_filter.h"
43 #include "ardour/midi_cursor.h"
44 #include "ardour/midi_model.h"
45 #include "ardour/midi_source.h"
46 #include "ardour/midi_state_tracker.h"
47 #include "ardour/session.h"
48 #include "ardour/session_directory.h"
49 #include "ardour/source_factory.h"
50 #include "ardour/tempo.h"
54 namespace ARDOUR { template <typename T> class MidiRingBuffer; }
57 using namespace ARDOUR;
60 MidiSource::MidiSource (Session& s, string name, Source::Flag flags)
61 : Source(s, DataType::MIDI, name, flags)
65 , _capture_loop_length(0)
69 MidiSource::MidiSource (Session& s, const XMLNode& node)
74 , _capture_loop_length(0)
76 if (set_state (node, Stateful::loading_state_version)) {
77 throw failed_constructor();
81 MidiSource::~MidiSource ()
86 MidiSource::get_state ()
88 XMLNode& node (Source::get_state());
90 if (_captured_for.length()) {
91 node.add_property ("captured-for", _captured_for);
94 for (InterpolationStyleMap::const_iterator i = _interpolation_style.begin(); i != _interpolation_style.end(); ++i) {
95 XMLNode* child = node.add_child (X_("InterpolationStyle"));
96 child->add_property (X_("parameter"), EventTypeMap::instance().to_symbol (i->first));
97 child->add_property (X_("style"), enum_2_string (i->second));
100 for (AutomationStateMap::const_iterator i = _automation_state.begin(); i != _automation_state.end(); ++i) {
101 XMLNode* child = node.add_child (X_("AutomationState"));
102 child->add_property (X_("parameter"), EventTypeMap::instance().to_symbol (i->first));
103 child->add_property (X_("state"), enum_2_string (i->second));
110 MidiSource::set_state (const XMLNode& node, int /*version*/)
112 XMLProperty const * prop;
113 if ((prop = node.property ("captured-for")) != 0) {
114 _captured_for = prop->value();
117 XMLNodeList children = node.children ();
118 for (XMLNodeConstIterator i = children.begin(); i != children.end(); ++i) {
119 if ((*i)->name() == X_("InterpolationStyle")) {
120 if ((prop = (*i)->property (X_("parameter"))) == 0) {
121 error << _("Missing parameter property on InterpolationStyle") << endmsg;
124 Evoral::Parameter p = EventTypeMap::instance().from_symbol (prop->value());
126 if ((prop = (*i)->property (X_("style"))) == 0) {
127 error << _("Missing style property on InterpolationStyle") << endmsg;
130 Evoral::ControlList::InterpolationStyle s = static_cast<Evoral::ControlList::InterpolationStyle>(
131 string_2_enum (prop->value(), s));
132 set_interpolation_of (p, s);
134 } else if ((*i)->name() == X_("AutomationState")) {
135 if ((prop = (*i)->property (X_("parameter"))) == 0) {
136 error << _("Missing parameter property on AutomationState") << endmsg;
139 Evoral::Parameter p = EventTypeMap::instance().from_symbol (prop->value());
141 if ((prop = (*i)->property (X_("state"))) == 0) {
142 error << _("Missing state property on AutomationState") << endmsg;
145 AutoState s = static_cast<AutoState> (string_2_enum (prop->value(), s));
146 set_automation_state_of (p, s);
154 MidiSource::empty () const
156 return !_length_beats;
160 MidiSource::length (framepos_t pos) const
162 if (!_length_beats) {
166 BeatsFramesConverter converter(_session.tempo_map(), pos);
167 return converter.to(_length_beats);
171 MidiSource::update_length (framecnt_t)
173 // You're not the boss of me!
177 MidiSource::invalidate (const Lock& lock)
179 Invalidated(_session.transport_rolling());
183 MidiSource::midi_read (const Lock& lm,
184 Evoral::EventSink<framepos_t>& dst,
185 framepos_t source_start,
188 Evoral::Range<framepos_t>* loop_range,
190 MidiStateTracker* tracker,
191 MidiChannelFilter* filter,
192 const std::set<Evoral::Parameter>& filtered,
194 const double start_beats) const
196 BeatsFramesConverter converter(_session.tempo_map(), source_start);
198 const double start_qn = (pulse * 4.0) - start_beats;
200 DEBUG_TRACE (DEBUG::MidiSourceIO,
201 string_compose ("MidiSource::midi_read() %5 sstart %1 start %2 cnt %3 tracker %4\n",
202 source_start, start, cnt, tracker, name()));
205 return read_unlocked (lm, dst, source_start, start, cnt, loop_range, tracker, filter);
208 // Find appropriate model iterator
209 Evoral::Sequence<Evoral::Beats>::const_iterator& i = cursor.iter;
210 const bool linear_read = cursor.last_read_end != 0 && start == cursor.last_read_end;
211 if (!linear_read || !i.valid()) {
212 /* Cached iterator is invalid, search for the first event past start.
213 Note that multiple tracks can use a MidiSource simultaneously, so
214 all playback state must be in parameters (the cursor) and must not
215 be cached in the source of model itself.
216 See http://tracker.ardour.org/view.php?id=6541
218 cursor.connect(Invalidated);
219 cursor.iter = _model->begin(converter.from(start), false, filtered, &cursor.active_notes);
220 cursor.active_notes.clear();
223 cursor.last_read_end = start + cnt;
225 // Copy events in [start, start + cnt) into dst
226 for (; i != _model->end(); ++i) {
228 // Offset by source start to convert event time to session time
230 framepos_t time_frames = _session.tempo_map().frame_at_quarter_note (i->time().to_double() + start_qn);
232 if (time_frames < start + source_start) {
233 /* event too early */
237 } else if (time_frames >= start + cnt + source_start) {
239 DEBUG_TRACE (DEBUG::MidiSourceIO,
240 string_compose ("%1: reached end with event @ %2 vs. %3\n",
241 _name, time_frames, start+cnt));
248 if (filter && filter->filter(i->buffer(), i->size())) {
249 DEBUG_TRACE (DEBUG::MidiSourceIO,
250 string_compose ("%1: filter event @ %2 type %3 size %4\n",
251 _name, time_frames, i->event_type(), i->size()));
256 time_frames = loop_range->squish (time_frames);
259 dst.write (time_frames, i->event_type(), i->size(), i->buffer());
262 if (DEBUG_ENABLED(DEBUG::MidiSourceIO)) {
264 DEBUG_STR_APPEND(a, string_compose ("%1 added event @ %2 sz %3 within %4 .. %5 ",
265 _name, time_frames, i->size(),
266 start + source_start, start + cnt + source_start));
267 for (size_t n=0; n < i->size(); ++n) {
268 DEBUG_STR_APPEND(a,hex);
269 DEBUG_STR_APPEND(a,"0x");
270 DEBUG_STR_APPEND(a,(int)i->buffer()[n]);
271 DEBUG_STR_APPEND(a,' ');
273 DEBUG_STR_APPEND(a,'\n');
274 DEBUG_TRACE (DEBUG::MidiSourceIO, DEBUG_STR(a).str());
288 MidiSource::midi_write (const Lock& lm,
289 MidiRingBuffer<framepos_t>& source,
290 framepos_t source_start,
293 const framecnt_t ret = write_unlocked (lm, source, source_start, cnt);
295 if (cnt == max_framecnt) {
298 _capture_length += cnt;
305 MidiSource::mark_streaming_midi_write_started (const Lock& lock, NoteMode mode)
308 _model->set_note_mode (mode);
309 _model->start_write ();
316 MidiSource::mark_write_starting_now (framecnt_t position,
317 framecnt_t capture_length,
318 framecnt_t loop_length)
320 /* I'm not sure if this is the best way to approach this, but
321 _capture_length needs to be set up with the transport frame
322 when a record actually starts, as it is used by
323 SMFSource::write_unlocked to decide whether incoming notes
324 are within the correct time range.
325 mark_streaming_midi_write_started (perhaps a more logical
326 place to do this) is not called at exactly the time when
327 record starts, and I don't think it necessarily can be
328 because it is not RT-safe.
331 set_timeline_position(position);
332 _capture_length = capture_length;
333 _capture_loop_length = loop_length;
335 TempoMap& map (_session.tempo_map());
336 BeatsFramesConverter converter(map, position);
337 _length_beats = converter.from(capture_length);
341 MidiSource::mark_streaming_write_started (const Lock& lock)
343 NoteMode note_mode = _model ? _model->note_mode() : Sustained;
344 mark_streaming_midi_write_started (lock, note_mode);
348 MidiSource::mark_midi_streaming_write_completed (const Lock& lock,
349 Evoral::Sequence<Evoral::Beats>::StuckNoteOption option,
353 _model->end_write (option, end);
355 /* Make captured controls discrete to play back user input exactly. */
356 for (MidiModel::Controls::iterator i = _model->controls().begin(); i != _model->controls().end(); ++i) {
357 if (i->second->list()) {
358 i->second->list()->set_interpolation(Evoral::ControlList::Discrete);
359 _interpolation_style.insert(std::make_pair(i->second->parameter(), Evoral::ControlList::Discrete));
369 MidiSource::mark_streaming_write_completed (const Lock& lock)
371 mark_midi_streaming_write_completed (lock, Evoral::Sequence<Evoral::Beats>::DeleteStuckNotes);
375 MidiSource::export_write_to (const Lock& lock, boost::shared_ptr<MidiSource> newsrc, Evoral::Beats begin, Evoral::Beats end)
377 Lock newsrc_lock (newsrc->mutex ());
380 error << string_compose (_("programming error: %1"), X_("no model for MidiSource during export"));
384 _model->write_section_to (newsrc, newsrc_lock, begin, end, true);
386 newsrc->flush_midi(newsrc_lock);
392 MidiSource::write_to (const Lock& lock, boost::shared_ptr<MidiSource> newsrc, Evoral::Beats begin, Evoral::Beats end)
394 Lock newsrc_lock (newsrc->mutex ());
396 newsrc->set_timeline_position (_timeline_position);
397 newsrc->copy_interpolation_from (this);
398 newsrc->copy_automation_state_from (this);
401 if (begin == Evoral::MinBeats && end == Evoral::MaxBeats) {
402 _model->write_to (newsrc, newsrc_lock);
404 _model->write_section_to (newsrc, newsrc_lock, begin, end);
407 error << string_compose (_("programming error: %1"), X_("no model for MidiSource during ::clone()"));
411 newsrc->flush_midi(newsrc_lock);
413 /* force a reload of the model if the range is partial */
415 if (begin != Evoral::MinBeats || end != Evoral::MaxBeats) {
416 newsrc->load_model (newsrc_lock, true);
418 newsrc->set_model (newsrc_lock, _model);
421 /* this file is not removable (but since it is MIDI, it is mutable) */
423 boost::dynamic_pointer_cast<FileSource> (newsrc)->prevent_deletion ();
429 MidiSource::session_saved()
433 /* this writes a copy of the data to disk.
434 XXX do we need to do this every time?
437 if (_model && _model->edited()) {
438 /* The model is edited, write its contents into the current source
439 file (overwiting previous contents). */
441 /* Temporarily drop our reference to the model so that as the model
442 pushes its current state to us, we don't try to update it. */
443 boost::shared_ptr<MidiModel> mm = _model;
446 /* Flush model contents to disk. */
447 mm->sync_to_source (lm);
449 /* Reacquire model. */
458 MidiSource::set_note_mode(const Lock& lock, NoteMode mode)
461 _model->set_note_mode(mode);
466 MidiSource::drop_model (const Lock& lock)
470 ModelChanged (); /* EMIT SIGNAL */
474 MidiSource::set_model (const Lock& lock, boost::shared_ptr<MidiModel> m)
478 ModelChanged (); /* EMIT SIGNAL */
481 Evoral::ControlList::InterpolationStyle
482 MidiSource::interpolation_of (Evoral::Parameter p) const
484 InterpolationStyleMap::const_iterator i = _interpolation_style.find (p);
485 if (i == _interpolation_style.end()) {
486 return EventTypeMap::instance().interpolation_of (p);
493 MidiSource::automation_state_of (Evoral::Parameter p) const
495 AutomationStateMap::const_iterator i = _automation_state.find (p);
496 if (i == _automation_state.end()) {
497 /* default to `play', otherwise if MIDI is recorded /
498 imported with controllers etc. they are by default
499 not played back, which is a little surprising.
507 /** Set interpolation style to be used for a given parameter. This change will be
508 * propagated to anyone who needs to know.
511 MidiSource::set_interpolation_of (Evoral::Parameter p, Evoral::ControlList::InterpolationStyle s)
513 if (interpolation_of (p) == s) {
517 if (EventTypeMap::instance().interpolation_of (p) == s) {
518 /* interpolation type is being set to the default, so we don't need a note in our map */
519 _interpolation_style.erase (p);
521 _interpolation_style[p] = s;
524 InterpolationChanged (p, s); /* EMIT SIGNAL */
528 MidiSource::set_automation_state_of (Evoral::Parameter p, AutoState s)
530 if (automation_state_of (p) == s) {
535 /* automation state is being set to the default, so we don't need a note in our map */
536 _automation_state.erase (p);
538 _automation_state[p] = s;
541 AutomationStateChanged (p, s); /* EMIT SIGNAL */
545 MidiSource::copy_interpolation_from (boost::shared_ptr<MidiSource> s)
547 copy_interpolation_from (s.get ());
551 MidiSource::copy_automation_state_from (boost::shared_ptr<MidiSource> s)
553 copy_automation_state_from (s.get ());
557 MidiSource::copy_interpolation_from (MidiSource* s)
559 _interpolation_style = s->_interpolation_style;
561 /* XXX: should probably emit signals here */
565 MidiSource::copy_automation_state_from (MidiSource* s)
567 _automation_state = s->_automation_state;
569 /* XXX: should probably emit signals here */