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 <glib/gstdio.h>
34 #include <glibmm/miscutils.h>
35 #include <glibmm/fileutils.h>
37 #include "evoral/Control.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;
53 /** Constructor used for new internal-to-session files. File cannot exist. */
54 SMFSource::SMFSource (Session& s, const string& path, Source::Flag flags)
55 : Source(s, DataType::MIDI, path, flags)
56 , MidiSource(s, path, flags)
57 , FileSource(s, DataType::MIDI, path, string(), flags)
59 , _last_ev_time_beats(0.0)
60 , _last_ev_time_frames(0)
61 , _smf_last_read_end (0)
62 , _smf_last_read_time (0)
64 /* note that origin remains empty */
66 if (init (_path, false)) {
67 throw failed_constructor ();
70 assert (!Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
73 /* file is not opened until write */
75 if (flags & Writable) {
80 throw failed_constructor ();
86 /** Constructor used for existing internal-to-session files. */
87 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
90 , FileSource(s, node, must_exist)
91 , _last_ev_time_beats(0.0)
92 , _last_ev_time_frames(0)
93 , _smf_last_read_end (0)
94 , _smf_last_read_time (0)
96 if (set_state(node, Stateful::loading_state_version)) {
97 throw failed_constructor ();
100 if (init (_path, true)) {
101 throw failed_constructor ();
104 assert (Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
108 throw failed_constructor ();
114 SMFSource::~SMFSource ()
117 ::g_unlink (_path.c_str());
122 SMFSource::open_for_write ()
124 if (create (_path)) {
131 /** All stamps in audio frames */
133 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination,
134 framepos_t const source_start,
137 MidiStateTracker* tracker) const
140 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
142 if (writable() && !_open) {
143 /* nothing to read since nothing has ben written */
147 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
149 // Output parameters for read_event (which will allocate scratch in buffer as needed)
150 uint32_t ev_delta_t = 0;
151 uint32_t ev_type = 0;
152 uint32_t ev_size = 0;
153 uint8_t* ev_buffer = 0;
155 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
157 BeatsFramesConverter converter(_session.tempo_map(), source_start);
159 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
160 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
162 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
163 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
164 Evoral::SMF::seek_to_start();
165 while (time < start_ticks) {
168 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
169 if (ret == -1) { // EOF
170 _smf_last_read_end = start + duration;
173 time += ev_delta_t; // accumulate delta time
176 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
177 time = _smf_last_read_time;
180 _smf_last_read_end = start + duration;
183 gint ignored; /* XXX don't ignore note id's ??*/
185 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
186 if (ret == -1) { // EOF
190 time += ev_delta_t; // accumulate delta time
191 _smf_last_read_time = time;
193 if (ret == 0) { // meta-event (skipped, just accumulate time)
197 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
199 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
200 ev_delta_t, time, ev_buffer[0], ev_type));
202 assert(time >= start_ticks);
204 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
205 is in session frames.
207 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
209 if (ev_frame_time < start + duration) {
210 destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
213 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
214 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
215 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
216 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
223 if (ev_size > scratch_size) {
224 scratch_size = ev_size;
226 ev_size = scratch_size; // ensure read_event only allocates if necessary
233 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source,
238 mark_streaming_write_started ();
242 Evoral::EventType type;
245 size_t buf_capacity = 4;
246 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
248 if (_model && !_model->writing()) {
249 _model->start_write();
252 Evoral::MIDIEvent<framepos_t> ev;
254 /* Get the event time, in frames since session start but ignoring looping. */
256 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
257 /* Ring is empty, no more events. */
261 if ((cnt != max_framecnt) &&
262 (time > position + _capture_length + cnt)) {
263 /* The diskstream doesn't want us to write everything, and this
264 event is past the end of this block, so we're done for now. */
268 /* Read the time, type, and size of the event. */
269 if (!(ret = source.read_prefix (&time, &type, &size))) {
270 error << _("Unable to read event prefix, corrupt MIDI ring") << endmsg;
274 /* Enlarge body buffer if necessary now that we know the size. */
275 if (size > buf_capacity) {
277 buf = (uint8_t*)realloc(buf, size);
280 /* Read the event body into buffer. */
281 ret = source.read_contents(size, buf);
283 error << _("Event has time and size but no body, corrupt MIDI ring") << endmsg;
287 /* Convert event time from absolute to source relative. */
288 if (time < position) {
289 error << _("Event time is before MIDI source position") << endmsg;
294 ev.set(buf, size, time);
295 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
296 ev.set_id(Evoral::next_event_id());
298 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
302 append_event_unlocked_frames(ev, position);
305 Evoral::SMF::flush ();
311 /** Append an event with a timestamp in beats (double) */
313 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
315 if (!_writing || ev.size() == 0) {
319 /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
320 name().c_str(), ev.id(), ev.time(), ev.size());
321 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
323 if (ev.time() < _last_ev_time_beats) {
324 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
329 Evoral::event_id_t event_id;
332 event_id = Evoral::next_event_id();
338 _model->append (ev, event_id);
341 _length_beats = max(_length_beats, ev.time());
343 const double delta_time_beats = ev.time() - _last_ev_time_beats;
344 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
346 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
347 _last_ev_time_beats = ev.time();
350 /** Append an event with a timestamp in frames (framepos_t) */
352 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
354 if (!_writing || ev.size() == 0) {
358 // printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
359 // name().c_str(), ev.id(), ev.time(), ev.size());
360 // for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");
362 if (ev.time() < _last_ev_time_frames) {
363 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
368 BeatsFramesConverter converter(_session.tempo_map(), position);
369 const double ev_time_beats = converter.from(ev.time());
370 Evoral::event_id_t event_id;
373 event_id = Evoral::next_event_id();
379 const Evoral::Event<double> beat_ev (ev.event_type(),
382 const_cast<uint8_t*>(ev.buffer()));
383 _model->append (beat_ev, event_id);
386 _length_beats = max(_length_beats, ev_time_beats);
388 const Evoral::MusicalTime last_time_beats = converter.from (_last_ev_time_frames);
389 const Evoral::MusicalTime delta_time_beats = ev_time_beats - last_time_beats;
390 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
392 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
393 _last_ev_time_frames = ev.time();
397 SMFSource::get_state ()
399 XMLNode& node = MidiSource::get_state();
400 node.add_property (X_("origin"), _origin);
405 SMFSource::set_state (const XMLNode& node, int version)
407 if (Source::set_state (node, version)) {
411 if (MidiSource::set_state (node, version)) {
415 if (FileSource::set_state (node, version)) {
423 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
425 /* CALLER MUST HOLD LOCK */
427 if (!_open && open_for_write()) {
428 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
429 /* XXX should probably throw or return something */
433 MidiSource::mark_streaming_midi_write_started (mode);
434 Evoral::SMF::begin_write ();
435 _last_ev_time_beats = 0.0;
436 _last_ev_time_frames = 0;
440 SMFSource::mark_streaming_write_completed ()
442 mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
446 SMFSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption stuck_notes_option, Evoral::MusicalTime when)
448 Glib::Threads::Mutex::Lock lm (_lock);
449 MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
452 warning << string_compose ("attempt to write to unwritable SMF file %1", _path) << endmsg;
457 _model->set_edited(false);
460 Evoral::SMF::end_write ();
462 /* data in the file now, not removable */
464 mark_nonremovable ();
468 SMFSource::safe_midi_file_extension (const string& file)
470 static regex_t compiled_pattern;
471 static bool compile = true;
472 const int nmatches = 2;
473 regmatch_t matches[nmatches];
475 if (Glib::file_test (file, Glib::FILE_TEST_EXISTS)) {
476 if (!Glib::file_test (file, Glib::FILE_TEST_IS_REGULAR)) {
477 /* exists but is not a regular file */
482 if (compile && regcomp (&compiled_pattern, "\\.[mM][iI][dD][iI]?$", REG_EXTENDED)) {
488 if (regexec (&compiled_pattern, file.c_str(), nmatches, matches, 0)) {
495 static bool compare_eventlist (
496 const std::pair< Evoral::Event<double>*, gint >& a,
497 const std::pair< Evoral::Event<double>*, gint >& b) {
498 return ( a.first->time() < b.first->time() );
502 SMFSource::load_model (bool lock, bool force_reload)
508 boost::shared_ptr<Glib::Threads::Mutex::Lock> lm;
510 lm = boost::shared_ptr<Glib::Threads::Mutex::Lock>(new Glib::Threads::Mutex::Lock(_lock));
512 if (_model && !force_reload) {
517 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
522 if (writable() && !_open) {
526 _model->start_write();
527 Evoral::SMF::seek_to_start();
529 uint64_t time = 0; /* in SMF ticks */
530 Evoral::Event<double> ev;
532 uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
534 uint32_t delta_t = 0;
541 // TODO simplify event allocation
542 std::list< std::pair< Evoral::Event<double>*, gint > > eventlist;
544 for (unsigned i = 1; i <= num_tracks(); ++i) {
545 if (seek_to_track(i)) continue;
548 have_event_id = false;
550 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
555 /* meta-event : did we get an event ID ? */
557 have_event_id = true;
563 /* not a meta-event */
565 if (!have_event_id) {
566 event_id = Evoral::next_event_id();
568 uint32_t event_type = EventTypeMap::instance().midi_event_type(buf[0]);
569 double event_time = time / (double) ppqn();
573 for (uint32_t xx = 0; xx < size; ++xx) {
575 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
579 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
580 delta_t, time, size, ss , event_type, name()));
583 eventlist.push_back(make_pair (
584 new Evoral::Event<double> (
585 event_type, event_time,
589 // Set size to max capacity to minimize allocs in read_event
590 scratch_size = std::max(size, scratch_size);
593 _length_beats = max(_length_beats, event_time);
596 /* event ID's must immediately precede the event they are for */
597 have_event_id = false;
601 eventlist.sort(compare_eventlist);
603 std::list< std::pair< Evoral::Event<double>*, gint > >::iterator it;
604 for (it=eventlist.begin(); it!=eventlist.end(); ++it) {
605 _model->append (*it->first, it->second);
609 _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
610 _model->set_edited (false);
612 _model_iter = _model->begin();
618 SMFSource::destroy_model ()
620 //cerr << _name << " destroying model " << _model.get() << endl;
625 SMFSource::flush_midi ()
627 if (!writable() || (writable() && !_open)) {
631 Evoral::SMF::end_write ();
632 /* data in the file means its no longer removable */
633 mark_nonremovable ();
637 SMFSource::set_path (const string& p)
639 FileSource::set_path (p);
640 SMF::set_path (_path);
643 /** Ensure that this source has some file on disk, even if it's just a SMF header */
645 SMFSource::ensure_disk_file ()
648 /* We have a model, so write it to disk; see MidiSource::session_saved
649 for an explanation of what we are doing here.
651 boost::shared_ptr<MidiModel> mm = _model;
653 mm->sync_to_source ();
656 /* No model; if it's not already open, it's an empty source, so create
657 and open it for writing.
663 /* Flush, which will definitely put something on disk */
669 SMFSource::prevent_deletion ()
671 /* Unlike the audio case, the MIDI file remains mutable (because we can
675 _flags = Flag (_flags & ~(Removable|RemovableIfEmpty|RemoveAtDestroy));
679 SMFSource::rename (const string& newname)
681 Glib::Threads::Mutex::Lock lm (_lock);
682 string oldpath = _path;
683 string newpath = _session.new_source_path_from_name (DataType::MIDI, newname);
685 if (newpath.empty()) {
686 error << string_compose (_("programming error: %1"), "cannot generate a changed file path") << endmsg;
690 // Test whether newpath exists, if yes notify the user but continue.
691 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
692 error << string_compose (_("Programming error! %1 tried to rename a file over another file! It's safe to continue working, but please report this to the developers."), PROGRAM_NAME) << endmsg;
696 if (Glib::file_test (oldpath.c_str(), Glib::FILE_TEST_EXISTS)) {
697 /* rename only needed if file exists on disk */
698 if (::rename (oldpath.c_str(), newpath.c_str()) != 0) {
699 error << string_compose (_("cannot rename file %1 to %2 (%3)"), oldpath, newpath, strerror(errno)) << endmsg;
704 _name = Glib::path_get_basename (newpath);