fix up file renaming code a little bit
[ArdourMidi.git] / libs / ardour / smf_source.cc
blob405f12881a3a495a7153b72e9e804a0e35747a87
1 /*
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.
21 #include <vector>
23 #include <sys/time.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <errno.h>
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"
46 #include "i18n.h"
48 using namespace ARDOUR;
49 using namespace Glib;
50 using namespace PBD;
52 /** Constructor used for new internal-to-session files. File cannot exist. */
53 SMFSource::SMFSource (Session& s, const ustring& path, Source::Flag flags)
54 : Source(s, DataType::MIDI, path, flags)
55 , MidiSource(s, path)
56 , FileSource(s, DataType::MIDI, path, flags)
57 , Evoral::SMF()
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 if (init(_path, false)) {
64 throw failed_constructor ();
67 if (create(path)) {
68 throw failed_constructor ();
71 load_model(true, true); // FIXME
74 /** Constructor used for existing internal-to-session files. */
75 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
76 : Source(s, node)
77 , MidiSource(s, node)
78 , FileSource(s, node, must_exist)
79 , _last_ev_time_beats(0.0)
80 , _last_ev_time_frames(0)
81 , _smf_last_read_end (0)
82 , _smf_last_read_time (0)
84 if (set_state(node, Stateful::loading_state_version)) {
85 throw failed_constructor ();
88 if (init(_path, true)) {
89 throw failed_constructor ();
92 if (open(_path)) {
93 throw failed_constructor ();
96 load_model(true, true); // FIXME
99 SMFSource::~SMFSource ()
101 if (removable()) {
102 unlink (_path.c_str());
106 /** All stamps in audio frames */
107 nframes_t
108 SMFSource::read_unlocked (Evoral::EventSink<nframes_t>& destination, sframes_t source_start,
109 sframes_t start, nframes_t duration,
110 sframes_t stamp_offset, sframes_t negative_stamp_offset,
111 MidiStateTracker* tracker) const
113 int ret = 0;
114 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
116 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
118 _read_data_count = 0;
120 // Output parameters for read_event (which will allocate scratch in buffer as needed)
121 uint32_t ev_delta_t = 0;
122 uint32_t ev_type = 0;
123 uint32_t ev_size = 0;
124 uint8_t* ev_buffer = 0;
126 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
128 BeatsFramesConverter converter(_session.tempo_map(), source_start);
130 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
131 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
133 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
134 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
135 Evoral::SMF::seek_to_start();
136 while (time < start_ticks) {
137 gint ignored;
139 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
140 if (ret == -1) { // EOF
141 _smf_last_read_end = start + duration;
142 return duration;
144 time += ev_delta_t; // accumulate delta time
146 } else {
147 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
148 time = _smf_last_read_time;
151 _smf_last_read_end = start + duration;
153 while (true) {
154 gint ignored; /* XXX don't ignore note id's ??*/
156 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
157 if (ret == -1) { // EOF
158 break;
161 time += ev_delta_t; // accumulate delta time
162 _smf_last_read_time = time;
164 if (ret == 0) { // meta-event (skipped, just accumulate time)
165 continue;
168 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
170 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
171 ev_delta_t, time, ev_buffer[0], ev_type));
173 assert(time >= start_ticks);
174 const sframes_t ev_frame_time = converter.to(time / (double)ppqn()) + stamp_offset;
176 #if 0
177 cerr << " frames = " << ev_frame_time
178 << " w/offset = " << ev_frame_time - negative_stamp_offset
179 << endl;
180 #endif
182 if (ev_frame_time < start + duration) {
183 destination.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
185 if (tracker) {
186 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
187 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
188 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
189 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
192 } else {
193 break;
196 _read_data_count += ev_size;
198 if (ev_size > scratch_size) {
199 scratch_size = ev_size;
201 ev_size = scratch_size; // ensure read_event only allocates if necessary
204 return duration;
207 /** All stamps in audio frames */
208 nframes_t
209 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& source, sframes_t position, nframes_t duration)
211 _write_data_count = 0;
213 nframes_t time;
214 Evoral::EventType type;
215 uint32_t size;
217 size_t buf_capacity = 4;
218 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
220 if (_model && ! _model->writing()) {
221 _model->start_write();
224 Evoral::MIDIEvent<nframes_t> ev;
226 while (true) {
227 bool ret = source.peek_time(&time);
228 if (!ret || time > _last_write_end + duration) {
229 break;
232 ret = source.read_prefix(&time, &type, &size);
233 if (!ret) {
234 cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
235 break;
238 if (size > buf_capacity) {
239 buf_capacity = size;
240 buf = (uint8_t*)realloc(buf, size);
243 ret = source.read_contents(size, buf);
244 if (!ret) {
245 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
246 break;
249 assert(time >= position);
250 time -= position;
252 ev.set(buf, size, time);
253 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
254 ev.set_id (Evoral::next_event_id());
256 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
257 /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
258 << std::hex << int(ev.buffer()[0]) << endl;*/
259 continue;
262 append_event_unlocked_frames(ev, position);
265 Evoral::SMF::flush();
266 free(buf);
268 ViewDataRangeReady(position + _last_write_end, duration); /* EMIT SIGNAL */
270 return duration;
274 /** Append an event with a timestamp in beats (double) */
275 void
276 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
278 assert(_writing);
279 if (ev.size() == 0) {
280 return;
283 /* printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
284 name().c_str(), ev.id(), ev.time(), ev.size());
285 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
287 assert(ev.time() >= 0);
288 if (ev.time() < _last_ev_time_beats) {
289 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
290 return;
293 Evoral::event_id_t event_id;
295 if (ev.id() < 0) {
296 event_id = Evoral::next_event_id();
297 } else {
298 event_id = ev.id();
301 if (_model) {
302 _model->append (ev, event_id);
305 _length_beats = max(_length_beats, ev.time());
307 const double delta_time_beats = ev.time() - _last_ev_time_beats;
308 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
310 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
311 _last_ev_time_beats = ev.time();
313 _write_data_count += ev.size();
317 /** Append an event with a timestamp in frames (nframes_t) */
318 void
319 SMFSource::append_event_unlocked_frames (const Evoral::Event<nframes_t>& ev, sframes_t position)
321 assert(_writing);
322 if (ev.size() == 0) {
323 return;
326 /* printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
327 name().c_str(), ev.id(), ev.time(), ev.size());
328 for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
330 if (ev.time() < _last_ev_time_frames) {
331 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
332 return;
335 BeatsFramesConverter converter(_session.tempo_map(), position);
336 const double ev_time_beats = converter.from(ev.time());
337 Evoral::event_id_t event_id;
339 if (ev.id() < 0) {
340 event_id = Evoral::next_event_id();
341 } else {
342 event_id = ev.id();
345 if (_model) {
346 const Evoral::Event<double> beat_ev (ev.event_type(),
347 ev_time_beats,
348 ev.size(),
349 (uint8_t*)ev.buffer());
350 _model->append (beat_ev, event_id);
353 _length_beats = max(_length_beats, ev_time_beats);
355 const sframes_t delta_time_frames = ev.time() - _last_ev_time_frames;
356 const double delta_time_beats = converter.from(delta_time_frames);
357 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
359 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
360 _last_ev_time_frames = ev.time();
362 _write_data_count += ev.size();
366 XMLNode&
367 SMFSource::get_state ()
369 return MidiSource::get_state();
373 SMFSource::set_state (const XMLNode& node, int version)
375 if (Source::set_state (node, version)) {
376 return -1;
379 if (MidiSource::set_state (node, version)) {
380 return -1;
383 if (FileSource::set_state (node, version)) {
384 return -1;
387 return 0;
390 void
391 SMFSource::mark_streaming_midi_write_started (NoteMode mode, sframes_t start_frame)
393 Glib::Mutex::Lock lm (_lock);
394 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
395 Evoral::SMF::begin_write ();
396 _last_ev_time_beats = 0.0;
397 _last_ev_time_frames = 0;
400 void
401 SMFSource::mark_streaming_write_completed ()
403 Glib::Mutex::Lock lm (_lock);
404 MidiSource::mark_streaming_write_completed();
406 if (!writable()) {
407 return;
410 if (_model) {
411 _model->set_edited(false);
414 Evoral::SMF::end_write ();
416 /* data in the file now, not removable */
418 mark_nonremovable ();
421 bool
422 SMFSource::safe_midi_file_extension (const Glib::ustring& file)
424 return (file.rfind(".mid") != Glib::ustring::npos);
427 void
428 SMFSource::load_model (bool lock, bool force_reload)
430 if (_writing) {
431 return;
434 boost::shared_ptr<Glib::Mutex::Lock> lm;
435 if (lock)
436 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
438 if (_model && !force_reload) {
439 return;
442 if (! _model) {
443 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
444 //cerr << _name << " loaded new model " << _model.get() << endl;
445 } else {
446 /*cerr << _name << " reloading model " << _model.get()
447 << " (" << _model->n_notes() << " notes)" << endl;*/
448 _model->clear();
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;
460 uint32_t size = 0;
461 uint8_t* buf = NULL;
462 int ret;
463 gint event_id;
464 bool have_event_id = false;
466 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
468 time += delta_t;
470 if (ret == 0) {
472 /* meta-event : did we get an event ID ?
475 if (event_id >= 0) {
476 have_event_id = true;
479 continue;
482 if (ret > 0) {
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();
492 #ifndef NDEBUG
493 std::string ss;
495 for (uint32_t xx = 0; xx < size; ++xx) {
496 char b[8];
497 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
498 ss += b;
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()));
503 #endif
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();
527 free(buf);
530 void
531 SMFSource::destroy_model ()
533 //cerr << _name << " destroying model " << _model.get() << endl;
534 _model.reset();
537 void
538 SMFSource::flush_midi ()
540 if (!writable()) {
541 return;
544 Evoral::SMF::end_write();
545 /* data in the file means its no longer removable */
546 mark_nonremovable ();
549 void
550 SMFSource::set_path (const string& p)
552 FileSource::set_path (p);
553 SMF::set_path (_path);