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, string(), 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 /* note that origin remains empty */
65 if (init(_path, false)) {
66 throw failed_constructor ();
70 throw failed_constructor ();
73 load_model(true, true); // FIXME
76 /** Constructor used for existing internal-to-session files. */
77 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
80 , FileSource(s, node, must_exist)
81 , _last_ev_time_beats(0.0)
82 , _last_ev_time_frames(0)
83 , _smf_last_read_end (0)
84 , _smf_last_read_time (0)
86 if (set_state(node, Stateful::loading_state_version)) {
87 throw failed_constructor ();
90 if (init(_path, true)) {
91 throw failed_constructor ();
95 throw failed_constructor ();
98 load_model(true, true); // FIXME
101 SMFSource::~SMFSource ()
104 unlink (_path.c_str());
108 /** All stamps in audio frames */
110 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination, framepos_t const source_start,
111 framepos_t start, framecnt_t duration,
112 MidiStateTracker* tracker) const
115 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
117 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
119 _read_data_count = 0;
121 // Output parameters for read_event (which will allocate scratch in buffer as needed)
122 uint32_t ev_delta_t = 0;
123 uint32_t ev_type = 0;
124 uint32_t ev_size = 0;
125 uint8_t* ev_buffer = 0;
127 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
129 BeatsFramesConverter converter(_session.tempo_map(), source_start);
131 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
132 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
134 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
135 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
136 Evoral::SMF::seek_to_start();
137 while (time < start_ticks) {
140 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
141 if (ret == -1) { // EOF
142 _smf_last_read_end = start + duration;
145 time += ev_delta_t; // accumulate delta time
148 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
149 time = _smf_last_read_time;
152 _smf_last_read_end = start + duration;
155 gint ignored; /* XXX don't ignore note id's ??*/
157 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
158 if (ret == -1) { // EOF
162 time += ev_delta_t; // accumulate delta time
163 _smf_last_read_time = time;
165 if (ret == 0) { // meta-event (skipped, just accumulate time)
169 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
171 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
172 ev_delta_t, time, ev_buffer[0], ev_type));
174 assert(time >= start_ticks);
176 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
177 is in session frames.
179 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
181 if (ev_frame_time < start + duration) {
182 destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
185 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
186 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
187 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
188 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
195 _read_data_count += ev_size;
197 if (ev_size > scratch_size) {
198 scratch_size = ev_size;
200 ev_size = scratch_size; // ensure read_event only allocates if necessary
206 /** Write data to this source from a MidiRingBuffer.
207 * @param source Buffer to read from.
208 * @param position This source's start position in session frames.
211 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source, framepos_t position, framecnt_t duration)
213 _write_data_count = 0;
216 Evoral::EventType type;
219 size_t buf_capacity = 4;
220 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
222 if (_model && ! _model->writing()) {
223 _model->start_write();
226 Evoral::MIDIEvent<framepos_t> ev;
229 bool ret = source.peek_time(&time);
230 if (!ret || time > _last_write_end + duration) {
234 ret = source.read_prefix(&time, &type, &size);
236 cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
240 if (size > buf_capacity) {
242 buf = (uint8_t*)realloc(buf, size);
245 ret = source.read_contents(size, buf);
247 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
251 /* convert from session time to time relative to the source start */
252 assert(time >= position);
255 ev.set(buf, size, time);
256 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
257 ev.set_id (Evoral::next_event_id());
259 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
260 /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
261 << std::hex << int(ev.buffer()[0]) << endl;*/
265 append_event_unlocked_frames(ev, position);
268 Evoral::SMF::flush();
275 /** Append an event with a timestamp in beats (double) */
277 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
280 if (ev.size() == 0) {
284 /* printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
285 name().c_str(), ev.id(), ev.time(), ev.size());
286 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
288 assert(ev.time() >= 0);
289 if (ev.time() < _last_ev_time_beats) {
290 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
294 Evoral::event_id_t event_id;
297 event_id = Evoral::next_event_id();
303 _model->append (ev, event_id);
306 _length_beats = max(_length_beats, ev.time());
308 const double delta_time_beats = ev.time() - _last_ev_time_beats;
309 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
311 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
312 _last_ev_time_beats = ev.time();
314 _write_data_count += ev.size();
318 /** Append an event with a timestamp in frames (framepos_t) */
320 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
323 if (ev.size() == 0) {
327 /* printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
328 name().c_str(), ev.id(), ev.time(), ev.size());
329 for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
331 if (ev.time() < _last_ev_time_frames) {
332 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
336 BeatsFramesConverter converter(_session.tempo_map(), position);
337 const double ev_time_beats = converter.from(ev.time());
338 Evoral::event_id_t event_id;
341 event_id = Evoral::next_event_id();
347 const Evoral::Event<double> beat_ev (ev.event_type(),
350 (uint8_t*)ev.buffer());
351 _model->append (beat_ev, event_id);
354 _length_beats = max(_length_beats, ev_time_beats);
356 const framepos_t delta_time_frames = ev.time() - _last_ev_time_frames;
357 const double delta_time_beats = converter.from(delta_time_frames);
358 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
360 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
361 _last_ev_time_frames = ev.time();
363 _write_data_count += ev.size();
368 SMFSource::get_state ()
370 XMLNode& node = MidiSource::get_state();
371 node.add_property (X_("origin"), _origin);
376 SMFSource::set_state (const XMLNode& node, int version)
378 if (Source::set_state (node, version)) {
382 if (MidiSource::set_state (node, version)) {
386 if (FileSource::set_state (node, version)) {
394 SMFSource::mark_streaming_midi_write_started (NoteMode mode, framepos_t start_frame)
396 Glib::Mutex::Lock lm (_lock);
397 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
398 Evoral::SMF::begin_write ();
399 _last_ev_time_beats = 0.0;
400 _last_ev_time_frames = 0;
404 SMFSource::mark_streaming_write_completed ()
406 Glib::Mutex::Lock lm (_lock);
407 MidiSource::mark_streaming_write_completed();
414 _model->set_edited(false);
417 Evoral::SMF::end_write ();
419 /* data in the file now, not removable */
421 mark_nonremovable ();
425 SMFSource::safe_midi_file_extension (const string& file)
427 return (file.rfind(".mid") != string::npos);
431 SMFSource::load_model (bool lock, bool force_reload)
437 boost::shared_ptr<Glib::Mutex::Lock> lm;
439 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
441 if (_model && !force_reload) {
446 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
451 _model->start_write();
452 Evoral::SMF::seek_to_start();
454 uint64_t time = 0; /* in SMF ticks */
455 Evoral::Event<double> ev;
457 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
459 uint32_t delta_t = 0;
464 bool have_event_id = false;
466 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
472 /* meta-event : did we get an event ID ?
476 have_event_id = true;
484 /* not a meta-event */
486 ev.set (buf, size, time / (double)ppqn());
487 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
489 if (!have_event_id) {
490 event_id = Evoral::next_event_id();
495 for (uint32_t xx = 0; xx < size; ++xx) {
497 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
501 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
502 delta_t, time, size, ss , ev.event_type(), name()));
505 _model->append (ev, event_id);
507 if (ev.size() > scratch_size) {
508 scratch_size = ev.size();
511 ev.size() = scratch_size; // ensure read_event only allocates if necessary
513 _length_beats = max(_length_beats, ev.time());
516 /* event ID's must immediately precede the event they are for
519 have_event_id = false;
522 _model->end_write(false);
523 _model->set_edited(false);
525 _model_iter = _model->begin();
531 SMFSource::destroy_model ()
533 //cerr << _name << " destroying model " << _model.get() << endl;
538 SMFSource::flush_midi ()
544 Evoral::SMF::end_write();
545 /* data in the file means its no longer removable */
546 mark_nonremovable ();
550 SMFSource::set_path (const string& p)
552 FileSource::set_path (p);
553 SMF::set_path (_path);