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.
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/event_type_map.h"
38 #include "ardour/midi_model.h"
39 #include "ardour/midi_ring_buffer.h"
40 #include "ardour/midi_state_tracker.h"
41 #include "ardour/session.h"
42 #include "ardour/smf_source.h"
43 #include "ardour/debug.h"
47 using namespace ARDOUR;
51 /** Constructor used for new internal-to-session files. File cannot exist. */
52 SMFSource::SMFSource (Session& s, const string& path, Source::Flag flags)
53 : Source(s, DataType::MIDI, path, flags)
54 , MidiSource(s, path, flags)
55 , FileSource(s, DataType::MIDI, path, string(), flags)
57 , _last_ev_time_beats(0.0)
58 , _last_ev_time_frames(0)
59 , _smf_last_read_end (0)
60 , _smf_last_read_time (0)
62 /* note that origin remains empty */
64 if (init(_path, false)) {
65 throw failed_constructor ();
68 /* file is not opened until write */
71 /** Constructor used for existing internal-to-session files. */
72 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
75 , FileSource(s, node, must_exist)
76 , _last_ev_time_beats(0.0)
77 , _last_ev_time_frames(0)
78 , _smf_last_read_end (0)
79 , _smf_last_read_time (0)
81 if (set_state(node, Stateful::loading_state_version)) {
82 throw failed_constructor ();
85 if (init(_path, true)) {
86 throw failed_constructor ();
90 throw failed_constructor ();
96 SMFSource::~SMFSource ()
99 unlink (_path.c_str());
104 SMFSource::open_for_write ()
106 if (create (_path)) {
113 /** All stamps in audio frames */
115 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination,
116 framepos_t const source_start,
119 MidiStateTracker* tracker) const
122 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
124 if (writable() && !_open) {
125 /* nothing to read since nothing has ben written */
129 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
131 // Output parameters for read_event (which will allocate scratch in buffer as needed)
132 uint32_t ev_delta_t = 0;
133 uint32_t ev_type = 0;
134 uint32_t ev_size = 0;
135 uint8_t* ev_buffer = 0;
137 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
139 BeatsFramesConverter converter(_session.tempo_map(), source_start);
141 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
142 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
144 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
145 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
146 Evoral::SMF::seek_to_start();
147 while (time < start_ticks) {
150 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
151 if (ret == -1) { // EOF
152 _smf_last_read_end = start + duration;
155 time += ev_delta_t; // accumulate delta time
158 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
159 time = _smf_last_read_time;
162 _smf_last_read_end = start + duration;
165 gint ignored; /* XXX don't ignore note id's ??*/
167 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
168 if (ret == -1) { // EOF
172 time += ev_delta_t; // accumulate delta time
173 _smf_last_read_time = time;
175 if (ret == 0) { // meta-event (skipped, just accumulate time)
179 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
181 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
182 ev_delta_t, time, ev_buffer[0], ev_type));
184 assert(time >= start_ticks);
186 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
187 is in session frames.
189 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
191 if (ev_frame_time < start + duration) {
192 destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
195 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
196 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
197 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
198 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
205 if (ev_size > scratch_size) {
206 scratch_size = ev_size;
208 ev_size = scratch_size; // ensure read_event only allocates if necessary
215 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source,
220 mark_streaming_write_started ();
224 Evoral::EventType type;
227 size_t buf_capacity = 4;
228 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
230 if (_model && !_model->writing()) {
231 _model->start_write();
234 Evoral::MIDIEvent<framepos_t> ev;
236 /* Get the event time, in frames since session start but ignoring looping. */
238 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
239 /* Ring is empty, no more events. */
243 if ((cnt != max_framecnt) &&
244 (time > position + _capture_length + cnt)) {
245 /* The diskstream doesn't want us to write everything, and this
246 event is past the end of this block, so we're done for now. */
250 /* Read the time, type, and size of the event. */
251 if (!(ret = source.read_prefix (&time, &type, &size))) {
252 error << _("Unable to read event prefix, corrupt MIDI ring") << endmsg;
256 /* Enlarge body buffer if necessary now that we know the size. */
257 if (size > buf_capacity) {
259 buf = (uint8_t*)realloc(buf, size);
262 /* Read the event body into buffer. */
263 ret = source.read_contents(size, buf);
265 error << _("Event has time and size but no body, corrupt MIDI ring") << endmsg;
269 /* Convert event time from absolute to source relative. */
270 if (time < position) {
271 error << _("Event time is before MIDI source position") << endmsg;
276 ev.set(buf, size, time);
277 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
278 ev.set_id(Evoral::next_event_id());
280 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
284 append_event_unlocked_frames(ev, position);
287 Evoral::SMF::flush ();
293 /** Append an event with a timestamp in beats (double) */
295 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
297 if (!_writing || ev.size() == 0) {
301 /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
302 name().c_str(), ev.id(), ev.time(), ev.size());
303 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
305 if (ev.time() < _last_ev_time_beats) {
306 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
311 Evoral::event_id_t event_id;
314 event_id = Evoral::next_event_id();
320 _model->append (ev, event_id);
323 _length_beats = max(_length_beats, ev.time());
325 const double delta_time_beats = ev.time() - _last_ev_time_beats;
326 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
328 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
329 _last_ev_time_beats = ev.time();
332 /** Append an event with a timestamp in frames (framepos_t) */
334 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
336 if (!_writing || ev.size() == 0) {
340 // printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
341 // name().c_str(), ev.id(), ev.time(), ev.size());
342 // for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");
344 if (ev.time() < _last_ev_time_frames) {
345 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
350 BeatsFramesConverter converter(_session.tempo_map(), position);
351 const double ev_time_beats = converter.from(ev.time());
352 Evoral::event_id_t event_id;
355 event_id = Evoral::next_event_id();
361 const Evoral::Event<double> beat_ev (ev.event_type(),
364 const_cast<uint8_t*>(ev.buffer()));
365 _model->append (beat_ev, event_id);
368 _length_beats = max(_length_beats, ev_time_beats);
370 const Evoral::MusicalTime last_time_beats = converter.from (_last_ev_time_frames);
371 const Evoral::MusicalTime delta_time_beats = ev_time_beats - last_time_beats;
372 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
374 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
375 _last_ev_time_frames = ev.time();
379 SMFSource::get_state ()
381 XMLNode& node = MidiSource::get_state();
382 node.add_property (X_("origin"), _origin);
387 SMFSource::set_state (const XMLNode& node, int version)
389 if (Source::set_state (node, version)) {
393 if (MidiSource::set_state (node, version)) {
397 if (FileSource::set_state (node, version)) {
405 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
407 /* CALLER MUST HOLD LOCK */
409 if (!_open && open_for_write()) {
410 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
411 /* XXX should probably throw or return something */
415 MidiSource::mark_streaming_midi_write_started (mode);
416 Evoral::SMF::begin_write ();
417 _last_ev_time_beats = 0.0;
418 _last_ev_time_frames = 0;
422 SMFSource::mark_streaming_write_completed ()
424 mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
428 SMFSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption stuck_notes_option, Evoral::MusicalTime when)
430 Glib::Threads::Mutex::Lock lm (_lock);
431 MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
434 warning << string_compose ("attempt to write to unwritable SMF file %1", _path) << endmsg;
439 _model->set_edited(false);
442 Evoral::SMF::end_write ();
444 /* data in the file now, not removable */
446 mark_nonremovable ();
450 SMFSource::safe_midi_file_extension (const string& file)
452 static regex_t compiled_pattern;
453 static bool compile = true;
454 const int nmatches = 2;
455 regmatch_t matches[nmatches];
457 if (compile && regcomp (&compiled_pattern, "[mM][iI][dD][iI]?$", REG_EXTENDED)) {
463 if (regexec (&compiled_pattern, file.c_str(), nmatches, matches, 0)) {
471 SMFSource::load_model (bool lock, bool force_reload)
477 boost::shared_ptr<Glib::Threads::Mutex::Lock> lm;
479 lm = boost::shared_ptr<Glib::Threads::Mutex::Lock>(new Glib::Threads::Mutex::Lock(_lock));
481 if (_model && !force_reload) {
486 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
491 if (writable() && !_open) {
495 _model->start_write();
496 Evoral::SMF::seek_to_start();
498 uint64_t time = 0; /* in SMF ticks */
499 Evoral::Event<double> ev;
501 uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
503 uint32_t delta_t = 0;
508 bool have_event_id = false;
510 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
516 /* meta-event : did we get an event ID ?
520 have_event_id = true;
528 /* not a meta-event */
530 ev.set (buf, size, time / (double)ppqn());
531 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
533 if (!have_event_id) {
534 event_id = Evoral::next_event_id();
539 for (uint32_t xx = 0; xx < size; ++xx) {
541 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
545 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
546 delta_t, time, size, ss , ev.event_type(), name()));
549 _model->append (ev, event_id);
551 // Set size to max capacity to minimize allocs in read_event
552 scratch_size = std::max(size, scratch_size);
555 _length_beats = max(_length_beats, ev.time());
558 /* event ID's must immediately precede the event they are for
561 have_event_id = false;
564 _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
565 _model->set_edited (false);
567 _model_iter = _model->begin();
573 SMFSource::destroy_model ()
575 //cerr << _name << " destroying model " << _model.get() << endl;
580 SMFSource::flush_midi ()
582 if (!writable() || (writable() && !_open)) {
586 Evoral::SMF::end_write ();
587 /* data in the file means its no longer removable */
588 mark_nonremovable ();
592 SMFSource::set_path (const string& p)
594 FileSource::set_path (p);
595 SMF::set_path (_path);
598 /** Ensure that this source has some file on disk, even if it's just a SMF header */
600 SMFSource::ensure_disk_file ()
603 /* We have a model, so write it to disk; see MidiSource::session_saved
604 for an explanation of what we are doing here.
606 boost::shared_ptr<MidiModel> mm = _model;
608 mm->sync_to_source ();
611 /* No model; if it's not already open, it's an empty source, so create
612 and open it for writing.
618 /* Flush, which will definitely put something on disk */