2 Copyright (C) 2006 Paul Davis
3 Written 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.
28 #include "pbd/mountpoint.h"
29 #include "pbd/pathscanner.h"
30 #include "pbd/stl_delete.h"
31 #include "pbd/strsplit.h"
33 #include <glibmm/miscutils.h>
35 #include "evoral/Control.hpp"
37 #include "ardour/audioengine.h"
38 #include "ardour/event_type_map.h"
39 #include "ardour/midi_model.h"
40 #include "ardour/midi_ring_buffer.h"
41 #include "ardour/midi_state_tracker.h"
42 #include "ardour/session.h"
43 #include "ardour/smf_source.h"
44 #include "ardour/debug.h"
48 using namespace ARDOUR;
52 /** Constructor used for new internal-to-session files. File cannot exist. */
53 SMFSource::SMFSource (Session& s, const string& path, Source::Flag flags)
54 : Source(s, DataType::MIDI, path, flags)
56 , FileSource(s, DataType::MIDI, path, flags)
58 , _last_ev_time_beats(0.0)
59 , _last_ev_time_frames(0)
60 , _smf_last_read_end (0)
61 , _smf_last_read_time (0)
63 if (init(_path, false)) {
64 throw failed_constructor ();
68 throw failed_constructor ();
71 load_model(true, true); // FIXME
74 /** Constructor used for existing internal-to-session files. */
75 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
78 , FileSource(s, node, must_exist)
79 , _last_ev_time_beats(0.0)
80 , _last_ev_time_frames(0)
81 , _smf_last_read_end (0)
82 , _smf_last_read_time (0)
84 if (set_state(node, Stateful::loading_state_version)) {
85 throw failed_constructor ();
88 if (init(_path, true)) {
89 throw failed_constructor ();
93 throw failed_constructor ();
96 load_model(true, true); // FIXME
99 SMFSource::~SMFSource ()
102 unlink (_path.c_str());
106 /** All stamps in audio frames */
108 SMFSource::read_unlocked (Evoral::EventSink<nframes_t>& destination, framepos_t const source_start,
109 framepos_t start, nframes_t duration,
110 MidiStateTracker* tracker) const
113 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
115 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
117 _read_data_count = 0;
119 // Output parameters for read_event (which will allocate scratch in buffer as needed)
120 uint32_t ev_delta_t = 0;
121 uint32_t ev_type = 0;
122 uint32_t ev_size = 0;
123 uint8_t* ev_buffer = 0;
125 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
127 BeatsFramesConverter converter(_session.tempo_map(), source_start);
129 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
130 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
132 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
133 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
134 Evoral::SMF::seek_to_start();
135 while (time < start_ticks) {
138 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
139 if (ret == -1) { // EOF
140 _smf_last_read_end = start + duration;
143 time += ev_delta_t; // accumulate delta time
146 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
147 time = _smf_last_read_time;
150 _smf_last_read_end = start + duration;
153 gint ignored; /* XXX don't ignore note id's ??*/
155 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
156 if (ret == -1) { // EOF
160 time += ev_delta_t; // accumulate delta time
161 _smf_last_read_time = time;
163 if (ret == 0) { // meta-event (skipped, just accumulate time)
167 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
169 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
170 ev_delta_t, time, ev_buffer[0], ev_type));
172 assert(time >= start_ticks);
174 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
175 is in session frames.
177 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
179 if (ev_frame_time < start + duration) {
180 destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
183 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
184 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
185 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
186 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
193 _read_data_count += ev_size;
195 if (ev_size > scratch_size) {
196 scratch_size = ev_size;
198 ev_size = scratch_size; // ensure read_event only allocates if necessary
204 /** All stamps in audio frames */
206 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& source, framepos_t position, nframes_t duration)
208 _write_data_count = 0;
211 Evoral::EventType type;
214 size_t buf_capacity = 4;
215 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
217 if (_model && ! _model->writing()) {
218 _model->start_write();
221 Evoral::MIDIEvent<nframes_t> ev;
224 bool ret = source.peek_time(&time);
225 if (!ret || time > _last_write_end + duration) {
229 ret = source.read_prefix(&time, &type, &size);
231 cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
235 if (size > buf_capacity) {
237 buf = (uint8_t*)realloc(buf, size);
240 ret = source.read_contents(size, buf);
242 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
246 assert(time >= position);
249 ev.set(buf, size, time);
250 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
251 ev.set_id (Evoral::next_event_id());
253 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
254 /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
255 << std::hex << int(ev.buffer()[0]) << endl;*/
259 append_event_unlocked_frames(ev, position);
262 Evoral::SMF::flush();
265 ViewDataRangeReady(position + _last_write_end, duration); /* EMIT SIGNAL */
271 /** Append an event with a timestamp in beats (double) */
273 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
276 if (ev.size() == 0) {
280 /* printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
281 name().c_str(), ev.id(), ev.time(), ev.size());
282 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
284 assert(ev.time() >= 0);
285 if (ev.time() < _last_ev_time_beats) {
286 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
290 Evoral::event_id_t event_id;
293 event_id = Evoral::next_event_id();
299 _model->append (ev, event_id);
302 _length_beats = max(_length_beats, ev.time());
304 const double delta_time_beats = ev.time() - _last_ev_time_beats;
305 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
307 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
308 _last_ev_time_beats = ev.time();
310 _write_data_count += ev.size();
314 /** Append an event with a timestamp in frames (nframes_t) */
316 SMFSource::append_event_unlocked_frames (const Evoral::Event<nframes_t>& ev, framepos_t position)
319 if (ev.size() == 0) {
323 /* printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
324 name().c_str(), ev.id(), ev.time(), ev.size());
325 for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
327 if (ev.time() < _last_ev_time_frames) {
328 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
332 BeatsFramesConverter converter(_session.tempo_map(), position);
333 const double ev_time_beats = converter.from(ev.time());
334 Evoral::event_id_t event_id;
337 event_id = Evoral::next_event_id();
343 const Evoral::Event<double> beat_ev (ev.event_type(),
346 (uint8_t*)ev.buffer());
347 _model->append (beat_ev, event_id);
350 _length_beats = max(_length_beats, ev_time_beats);
352 const framepos_t delta_time_frames = ev.time() - _last_ev_time_frames;
353 const double delta_time_beats = converter.from(delta_time_frames);
354 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
356 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
357 _last_ev_time_frames = ev.time();
359 _write_data_count += ev.size();
364 SMFSource::get_state ()
366 return MidiSource::get_state();
370 SMFSource::set_state (const XMLNode& node, int version)
372 if (Source::set_state (node, version)) {
376 if (MidiSource::set_state (node, version)) {
380 if (FileSource::set_state (node, version)) {
388 SMFSource::mark_streaming_midi_write_started (NoteMode mode, framepos_t start_frame)
390 Glib::Mutex::Lock lm (_lock);
391 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
392 Evoral::SMF::begin_write ();
393 _last_ev_time_beats = 0.0;
394 _last_ev_time_frames = 0;
398 SMFSource::mark_streaming_write_completed ()
400 Glib::Mutex::Lock lm (_lock);
401 MidiSource::mark_streaming_write_completed();
408 _model->set_edited(false);
411 Evoral::SMF::end_write ();
413 /* data in the file now, not removable */
415 mark_nonremovable ();
419 SMFSource::safe_midi_file_extension (const string& file)
421 return (file.rfind(".mid") != string::npos);
425 SMFSource::load_model (bool lock, bool force_reload)
431 boost::shared_ptr<Glib::Mutex::Lock> lm;
433 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
435 if (_model && !force_reload) {
440 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
445 _model->start_write();
446 Evoral::SMF::seek_to_start();
448 uint64_t time = 0; /* in SMF ticks */
449 Evoral::Event<double> ev;
451 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
453 uint32_t delta_t = 0;
458 bool have_event_id = false;
460 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
466 /* meta-event : did we get an event ID ?
470 have_event_id = true;
478 /* not a meta-event */
480 ev.set (buf, size, time / (double)ppqn());
481 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
483 if (!have_event_id) {
484 event_id = Evoral::next_event_id();
489 for (uint32_t xx = 0; xx < size; ++xx) {
491 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
495 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
496 delta_t, time, size, ss , ev.event_type(), name()));
499 _model->append (ev, event_id);
501 if (ev.size() > scratch_size) {
502 scratch_size = ev.size();
505 ev.size() = scratch_size; // ensure read_event only allocates if necessary
507 _length_beats = max(_length_beats, ev.time());
510 /* event ID's must immediately precede the event they are for
513 have_event_id = false;
516 _model->end_write(false);
517 _model->set_edited(false);
519 _model_iter = _model->begin();
525 SMFSource::destroy_model ()
527 //cerr << _name << " destroying model " << _model.get() << endl;
532 SMFSource::flush_midi ()
538 Evoral::SMF::end_write();
539 /* data in the file means its no longer removable */
540 mark_nonremovable ();
544 SMFSource::set_path (const string& p)
546 FileSource::set_path (p);
547 SMF::set_path (_path);