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 */
70 if (flags & Writable) {
75 throw failed_constructor ();
80 /** Constructor used for existing internal-to-session files. */
81 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
84 , FileSource(s, node, must_exist)
85 , _last_ev_time_beats(0.0)
86 , _last_ev_time_frames(0)
87 , _smf_last_read_end (0)
88 , _smf_last_read_time (0)
90 if (set_state(node, Stateful::loading_state_version)) {
91 throw failed_constructor ();
94 if (init(_path, true)) {
95 throw failed_constructor ();
99 throw failed_constructor ();
105 SMFSource::~SMFSource ()
108 unlink (_path.c_str());
113 SMFSource::open_for_write ()
115 if (create (_path)) {
122 /** All stamps in audio frames */
124 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination,
125 framepos_t const source_start,
128 MidiStateTracker* tracker) const
131 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
133 if (writable() && !_open) {
134 /* nothing to read since nothing has ben written */
138 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
140 // Output parameters for read_event (which will allocate scratch in buffer as needed)
141 uint32_t ev_delta_t = 0;
142 uint32_t ev_type = 0;
143 uint32_t ev_size = 0;
144 uint8_t* ev_buffer = 0;
146 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
148 BeatsFramesConverter converter(_session.tempo_map(), source_start);
150 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
151 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
153 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
154 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
155 Evoral::SMF::seek_to_start();
156 while (time < start_ticks) {
159 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
160 if (ret == -1) { // EOF
161 _smf_last_read_end = start + duration;
164 time += ev_delta_t; // accumulate delta time
167 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
168 time = _smf_last_read_time;
171 _smf_last_read_end = start + duration;
174 gint ignored; /* XXX don't ignore note id's ??*/
176 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
177 if (ret == -1) { // EOF
181 time += ev_delta_t; // accumulate delta time
182 _smf_last_read_time = time;
184 if (ret == 0) { // meta-event (skipped, just accumulate time)
188 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
190 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
191 ev_delta_t, time, ev_buffer[0], ev_type));
193 assert(time >= start_ticks);
195 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
196 is in session frames.
198 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
200 if (ev_frame_time < start + duration) {
201 destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
204 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
205 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
206 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
207 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
214 if (ev_size > scratch_size) {
215 scratch_size = ev_size;
217 ev_size = scratch_size; // ensure read_event only allocates if necessary
224 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source,
229 mark_streaming_write_started ();
233 Evoral::EventType type;
236 size_t buf_capacity = 4;
237 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
239 if (_model && !_model->writing()) {
240 _model->start_write();
243 Evoral::MIDIEvent<framepos_t> ev;
245 /* Get the event time, in frames since session start but ignoring looping. */
247 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
248 /* Ring is empty, no more events. */
252 if ((cnt != max_framecnt) &&
253 (time > position + _capture_length + cnt)) {
254 /* The diskstream doesn't want us to write everything, and this
255 event is past the end of this block, so we're done for now. */
259 /* Read the time, type, and size of the event. */
260 if (!(ret = source.read_prefix (&time, &type, &size))) {
261 error << _("Unable to read event prefix, corrupt MIDI ring") << endmsg;
265 /* Enlarge body buffer if necessary now that we know the size. */
266 if (size > buf_capacity) {
268 buf = (uint8_t*)realloc(buf, size);
271 /* Read the event body into buffer. */
272 ret = source.read_contents(size, buf);
274 error << _("Event has time and size but no body, corrupt MIDI ring") << endmsg;
278 /* Convert event time from absolute to source relative. */
279 if (time < position) {
280 error << _("Event time is before MIDI source position") << endmsg;
285 ev.set(buf, size, time);
286 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
287 ev.set_id(Evoral::next_event_id());
289 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
293 append_event_unlocked_frames(ev, position);
296 Evoral::SMF::flush ();
302 /** Append an event with a timestamp in beats (double) */
304 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
306 if (!_writing || ev.size() == 0) {
310 /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
311 name().c_str(), ev.id(), ev.time(), ev.size());
312 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
314 if (ev.time() < _last_ev_time_beats) {
315 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
320 Evoral::event_id_t event_id;
323 event_id = Evoral::next_event_id();
329 _model->append (ev, event_id);
332 _length_beats = max(_length_beats, ev.time());
334 const double delta_time_beats = ev.time() - _last_ev_time_beats;
335 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
337 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
338 _last_ev_time_beats = ev.time();
341 /** Append an event with a timestamp in frames (framepos_t) */
343 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
345 if (!_writing || ev.size() == 0) {
349 // printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
350 // name().c_str(), ev.id(), ev.time(), ev.size());
351 // for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");
353 if (ev.time() < _last_ev_time_frames) {
354 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
359 BeatsFramesConverter converter(_session.tempo_map(), position);
360 const double ev_time_beats = converter.from(ev.time());
361 Evoral::event_id_t event_id;
364 event_id = Evoral::next_event_id();
370 const Evoral::Event<double> beat_ev (ev.event_type(),
373 const_cast<uint8_t*>(ev.buffer()));
374 _model->append (beat_ev, event_id);
377 _length_beats = max(_length_beats, ev_time_beats);
379 const Evoral::MusicalTime last_time_beats = converter.from (_last_ev_time_frames);
380 const Evoral::MusicalTime delta_time_beats = ev_time_beats - last_time_beats;
381 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
383 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
384 _last_ev_time_frames = ev.time();
388 SMFSource::get_state ()
390 XMLNode& node = MidiSource::get_state();
391 node.add_property (X_("origin"), _origin);
396 SMFSource::set_state (const XMLNode& node, int version)
398 if (Source::set_state (node, version)) {
402 if (MidiSource::set_state (node, version)) {
406 if (FileSource::set_state (node, version)) {
414 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
416 /* CALLER MUST HOLD LOCK */
418 if (!_open && open_for_write()) {
419 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
420 /* XXX should probably throw or return something */
424 MidiSource::mark_streaming_midi_write_started (mode);
425 Evoral::SMF::begin_write ();
426 _last_ev_time_beats = 0.0;
427 _last_ev_time_frames = 0;
431 SMFSource::mark_streaming_write_completed ()
433 mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
437 SMFSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption stuck_notes_option, Evoral::MusicalTime when)
439 Glib::Threads::Mutex::Lock lm (_lock);
440 MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
443 warning << string_compose ("attempt to write to unwritable SMF file %1", _path) << endmsg;
448 _model->set_edited(false);
451 Evoral::SMF::end_write ();
453 /* data in the file now, not removable */
455 mark_nonremovable ();
459 SMFSource::safe_midi_file_extension (const string& file)
461 static regex_t compiled_pattern;
462 static bool compile = true;
463 const int nmatches = 2;
464 regmatch_t matches[nmatches];
466 if (compile && regcomp (&compiled_pattern, "[mM][iI][dD][iI]?$", REG_EXTENDED)) {
472 if (regexec (&compiled_pattern, file.c_str(), nmatches, matches, 0)) {
479 static bool compare_eventlist (
480 const std::pair< Evoral::Event<double>*, gint >& a,
481 const std::pair< Evoral::Event<double>*, gint >& b) {
482 return ( a.first->time() < b.first->time() );
486 SMFSource::load_model (bool lock, bool force_reload)
492 boost::shared_ptr<Glib::Threads::Mutex::Lock> lm;
494 lm = boost::shared_ptr<Glib::Threads::Mutex::Lock>(new Glib::Threads::Mutex::Lock(_lock));
496 if (_model && !force_reload) {
501 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
506 if (writable() && !_open) {
510 _model->start_write();
511 Evoral::SMF::seek_to_start();
513 uint64_t time = 0; /* in SMF ticks */
514 Evoral::Event<double> ev;
516 uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
518 uint32_t delta_t = 0;
525 // TODO simplify event allocation
526 std::list< std::pair< Evoral::Event<double>*, gint > > eventlist;
528 for (unsigned i = 1; i <= num_tracks(); ++i) {
529 if (seek_to_track(i)) continue;
532 have_event_id = false;
534 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
539 /* meta-event : did we get an event ID ? */
541 have_event_id = true;
547 /* not a meta-event */
549 if (!have_event_id) {
550 event_id = Evoral::next_event_id();
552 uint32_t event_type = EventTypeMap::instance().midi_event_type(buf[0]);
553 double event_time = time / (double) ppqn();
557 for (uint32_t xx = 0; xx < size; ++xx) {
559 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
563 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
564 delta_t, time, size, ss , event_type, name()));
567 eventlist.push_back(make_pair (
568 new Evoral::Event<double> (
569 event_type, event_time,
573 // Set size to max capacity to minimize allocs in read_event
574 scratch_size = std::max(size, scratch_size);
577 _length_beats = max(_length_beats, event_time);
580 /* event ID's must immediately precede the event they are for */
581 have_event_id = false;
585 eventlist.sort(compare_eventlist);
587 std::list< std::pair< Evoral::Event<double>*, gint > >::iterator it;
588 for (it=eventlist.begin(); it!=eventlist.end(); ++it) {
589 _model->append (*it->first, it->second);
593 _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
594 _model->set_edited (false);
596 _model_iter = _model->begin();
602 SMFSource::destroy_model ()
604 //cerr << _name << " destroying model " << _model.get() << endl;
609 SMFSource::flush_midi ()
611 if (!writable() || (writable() && !_open)) {
615 Evoral::SMF::end_write ();
616 /* data in the file means its no longer removable */
617 mark_nonremovable ();
621 SMFSource::set_path (const string& p)
623 FileSource::set_path (p);
624 SMF::set_path (_path);
627 /** Ensure that this source has some file on disk, even if it's just a SMF header */
629 SMFSource::ensure_disk_file ()
632 /* We have a model, so write it to disk; see MidiSource::session_saved
633 for an explanation of what we are doing here.
635 boost::shared_ptr<MidiModel> mm = _model;
637 mm->sync_to_source ();
640 /* No model; if it's not already open, it's an empty source, so create
641 and open it for writing.
647 /* Flush, which will definitely put something on disk */