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>
34 #include <glibmm/fileutils.h>
36 #include "evoral/Control.hpp"
37 #include "evoral/evoral/SMF.hpp"
39 #include "ardour/event_type_map.h"
40 #include "ardour/midi_model.h"
41 #include "ardour/midi_ring_buffer.h"
42 #include "ardour/midi_state_tracker.h"
43 #include "ardour/session.h"
44 #include "ardour/smf_source.h"
45 #include "ardour/debug.h"
49 using namespace ARDOUR;
52 using namespace Evoral;
54 /** Constructor used for new internal-to-session files. File cannot exist. */
55 SMFSource::SMFSource (Session& s, const string& path, Source::Flag flags)
56 : Source(s, DataType::MIDI, path, flags)
57 , MidiSource(s, path, flags)
58 , FileSource(s, DataType::MIDI, path, string(), flags)
60 , _last_ev_time_beats(0.0)
61 , _last_ev_time_frames(0)
62 , _smf_last_read_end (0)
63 , _smf_last_read_time (0)
65 /* note that origin remains empty */
67 if (init (_path, false)) {
68 throw failed_constructor ();
71 assert (!Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
74 /* file is not opened until write */
76 if (flags & Writable) {
81 throw failed_constructor ();
87 /** Constructor used for external-to-session files. File must exist. */
88 SMFSource::SMFSource (Session& s, const string& path)
89 : Source(s, DataType::MIDI, path, Source::Flag (0))
90 , MidiSource(s, path, Source::Flag (0))
91 , FileSource(s, DataType::MIDI, path, string(), Source::Flag (0))
93 , _last_ev_time_beats(0.0)
94 , _last_ev_time_frames(0)
95 , _smf_last_read_end (0)
96 , _smf_last_read_time (0)
98 /* note that origin remains empty */
100 if (init (_path, false)) {
101 throw failed_constructor ();
104 assert (Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
107 /* file is not opened until write */
109 if (_flags & Writable) {
114 throw failed_constructor ();
120 /** Constructor used for existing internal-to-session files. */
121 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
123 , MidiSource(s, node)
124 , FileSource(s, node, must_exist)
125 , _last_ev_time_beats(0.0)
126 , _last_ev_time_frames(0)
127 , _smf_last_read_end (0)
128 , _smf_last_read_time (0)
130 if (set_state(node, Stateful::loading_state_version)) {
131 throw failed_constructor ();
134 if (init (_path, true)) {
135 throw failed_constructor ();
138 assert (Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
142 throw failed_constructor ();
148 SMFSource::~SMFSource ()
151 unlink (_path.c_str());
156 SMFSource::open_for_write ()
158 if (create (_path)) {
165 /** All stamps in audio frames */
167 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination,
168 framepos_t const source_start,
171 MidiStateTracker* tracker) const
174 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
176 if (writable() && !_open) {
177 /* nothing to read since nothing has ben written */
181 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
183 // Output parameters for read_event (which will allocate scratch in buffer as needed)
184 uint32_t ev_delta_t = 0;
185 uint32_t ev_type = 0;
186 uint32_t ev_size = 0;
187 uint8_t* ev_buffer = 0;
189 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
191 BeatsFramesConverter converter(_session.tempo_map(), source_start);
193 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
194 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
196 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
197 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
198 Evoral::SMF::seek_to_start();
199 while (time < start_ticks) {
202 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
203 if (ret == -1) { // EOF
204 _smf_last_read_end = start + duration;
207 time += ev_delta_t; // accumulate delta time
210 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
211 time = _smf_last_read_time;
214 _smf_last_read_end = start + duration;
217 gint ignored; /* XXX don't ignore note id's ??*/
219 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
220 if (ret == -1) { // EOF
224 time += ev_delta_t; // accumulate delta time
225 _smf_last_read_time = time;
227 if (ret == 0) { // meta-event (skipped, just accumulate time)
231 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
233 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
234 ev_delta_t, time, ev_buffer[0], ev_type));
236 assert(time >= start_ticks);
238 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
239 is in session frames.
241 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
243 if (ev_frame_time < start + duration) {
244 destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
247 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
248 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
249 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
250 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
257 if (ev_size > scratch_size) {
258 scratch_size = ev_size;
260 ev_size = scratch_size; // ensure read_event only allocates if necessary
267 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source,
272 mark_streaming_write_started ();
276 Evoral::EventType type;
279 size_t buf_capacity = 4;
280 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
282 if (_model && !_model->writing()) {
283 _model->start_write();
286 Evoral::MIDIEvent<framepos_t> ev;
288 /* Get the event time, in frames since session start but ignoring looping. */
290 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
291 /* Ring is empty, no more events. */
295 if ((cnt != max_framecnt) &&
296 (time > position + _capture_length + cnt)) {
297 /* The diskstream doesn't want us to write everything, and this
298 event is past the end of this block, so we're done for now. */
302 /* Read the time, type, and size of the event. */
303 if (!(ret = source.read_prefix (&time, &type, &size))) {
304 error << _("Unable to read event prefix, corrupt MIDI ring") << endmsg;
308 /* Enlarge body buffer if necessary now that we know the size. */
309 if (size > buf_capacity) {
311 buf = (uint8_t*)realloc(buf, size);
314 /* Read the event body into buffer. */
315 ret = source.read_contents(size, buf);
317 error << _("Event has time and size but no body, corrupt MIDI ring") << endmsg;
321 /* Convert event time from absolute to source relative. */
322 if (time < position) {
323 error << _("Event time is before MIDI source position") << endmsg;
328 ev.set(buf, size, time);
329 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
330 ev.set_id(Evoral::next_event_id());
332 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
336 append_event_unlocked_frames(ev, position);
339 Evoral::SMF::flush ();
345 /** Append an event with a timestamp in beats (double) */
347 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
349 if (!_writing || ev.size() == 0) {
353 /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
354 name().c_str(), ev.id(), ev.time(), ev.size());
355 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
357 if (ev.time() < _last_ev_time_beats) {
358 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
363 Evoral::event_id_t event_id;
366 event_id = Evoral::next_event_id();
372 _model->append (ev, event_id);
375 _length_beats = max(_length_beats, ev.time());
377 const double delta_time_beats = ev.time() - _last_ev_time_beats;
378 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
380 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
381 _last_ev_time_beats = ev.time();
384 /** Append an event with a timestamp in frames (framepos_t) */
386 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
388 if (!_writing || ev.size() == 0) {
392 // printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
393 // name().c_str(), ev.id(), ev.time(), ev.size());
394 // for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");
396 if (ev.time() < _last_ev_time_frames) {
397 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
402 BeatsFramesConverter converter(_session.tempo_map(), position);
403 const double ev_time_beats = converter.from(ev.time());
404 Evoral::event_id_t event_id;
407 event_id = Evoral::next_event_id();
413 const Evoral::Event<double> beat_ev (ev.event_type(),
416 const_cast<uint8_t*>(ev.buffer()));
417 _model->append (beat_ev, event_id);
420 _length_beats = max(_length_beats, ev_time_beats);
422 const Evoral::MusicalTime last_time_beats = converter.from (_last_ev_time_frames);
423 const Evoral::MusicalTime delta_time_beats = ev_time_beats - last_time_beats;
424 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
426 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
427 _last_ev_time_frames = ev.time();
431 SMFSource::get_state ()
433 XMLNode& node = MidiSource::get_state();
434 node.add_property (X_("origin"), _origin);
439 SMFSource::set_state (const XMLNode& node, int version)
441 if (Source::set_state (node, version)) {
445 if (MidiSource::set_state (node, version)) {
449 if (FileSource::set_state (node, version)) {
457 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
459 /* CALLER MUST HOLD LOCK */
461 if (!_open && open_for_write()) {
462 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
463 /* XXX should probably throw or return something */
467 MidiSource::mark_streaming_midi_write_started (mode);
468 Evoral::SMF::begin_write ();
469 _last_ev_time_beats = 0.0;
470 _last_ev_time_frames = 0;
474 SMFSource::mark_streaming_write_completed ()
476 mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
480 SMFSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption stuck_notes_option, Evoral::MusicalTime when)
482 Glib::Threads::Mutex::Lock lm (_lock);
483 MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
486 warning << string_compose ("attempt to write to unwritable SMF file %1", _path) << endmsg;
491 _model->set_edited(false);
494 Evoral::SMF::end_write ();
496 /* data in the file now, not removable */
498 mark_nonremovable ();
502 SMFSource::valid_midi_file (const string& file)
504 if (safe_midi_file_extension (file) ) {
505 return (SMF::test (file) );
511 SMFSource::safe_midi_file_extension (const string& file)
513 static regex_t compiled_pattern;
514 static bool compile = true;
515 const int nmatches = 2;
516 regmatch_t matches[nmatches];
518 if (Glib::file_test (file, Glib::FILE_TEST_EXISTS)) {
519 if (!Glib::file_test (file, Glib::FILE_TEST_IS_REGULAR)) {
520 /* exists but is not a regular file */
525 if (compile && regcomp (&compiled_pattern, "\\.[mM][iI][dD][iI]?$", REG_EXTENDED)) {
531 if (regexec (&compiled_pattern, file.c_str(), nmatches, matches, 0)) {
538 static bool compare_eventlist (
539 const std::pair< Evoral::Event<double>*, gint >& a,
540 const std::pair< Evoral::Event<double>*, gint >& b) {
541 return ( a.first->time() < b.first->time() );
545 SMFSource::load_model (bool lock, bool force_reload)
551 boost::shared_ptr<Glib::Threads::Mutex::Lock> lm;
553 lm = boost::shared_ptr<Glib::Threads::Mutex::Lock>(new Glib::Threads::Mutex::Lock(_lock));
555 if (_model && !force_reload) {
560 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
565 if (writable() && !_open) {
569 _model->start_write();
570 Evoral::SMF::seek_to_start();
572 uint64_t time = 0; /* in SMF ticks */
573 Evoral::Event<double> ev;
575 uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
577 uint32_t delta_t = 0;
584 // TODO simplify event allocation
585 std::list< std::pair< Evoral::Event<double>*, gint > > eventlist;
587 for (unsigned i = 1; i <= num_tracks(); ++i) {
588 if (seek_to_track(i)) continue;
591 have_event_id = false;
593 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
598 /* meta-event : did we get an event ID ? */
600 have_event_id = true;
606 /* not a meta-event */
608 if (!have_event_id) {
609 event_id = Evoral::next_event_id();
611 uint32_t event_type = EventTypeMap::instance().midi_event_type(buf[0]);
612 double event_time = time / (double) ppqn();
616 for (uint32_t xx = 0; xx < size; ++xx) {
618 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
622 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
623 delta_t, time, size, ss , event_type, name()));
626 eventlist.push_back(make_pair (
627 new Evoral::Event<double> (
628 event_type, event_time,
632 // Set size to max capacity to minimize allocs in read_event
633 scratch_size = std::max(size, scratch_size);
636 _length_beats = max(_length_beats, event_time);
639 /* event ID's must immediately precede the event they are for */
640 have_event_id = false;
644 eventlist.sort(compare_eventlist);
646 std::list< std::pair< Evoral::Event<double>*, gint > >::iterator it;
647 for (it=eventlist.begin(); it!=eventlist.end(); ++it) {
648 _model->append (*it->first, it->second);
652 _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
653 _model->set_edited (false);
655 _model_iter = _model->begin();
661 SMFSource::destroy_model ()
663 //cerr << _name << " destroying model " << _model.get() << endl;
668 SMFSource::flush_midi ()
670 if (!writable() || (writable() && !_open)) {
674 Evoral::SMF::end_write ();
675 /* data in the file means its no longer removable */
676 mark_nonremovable ();
680 SMFSource::set_path (const string& p)
682 FileSource::set_path (p);
683 SMF::set_path (_path);
686 /** Ensure that this source has some file on disk, even if it's just a SMF header */
688 SMFSource::ensure_disk_file ()
691 /* We have a model, so write it to disk; see MidiSource::session_saved
692 for an explanation of what we are doing here.
694 boost::shared_ptr<MidiModel> mm = _model;
696 mm->sync_to_source ();
699 /* No model; if it's not already open, it's an empty source, so create
700 and open it for writing.
706 /* Flush, which will definitely put something on disk */
712 SMFSource::prevent_deletion ()
714 /* Unlike the audio case, the MIDI file remains mutable (because we can
718 _flags = Flag (_flags & ~(Removable|RemovableIfEmpty|RemoveAtDestroy));