Move panner bypass state up to the PannerShell so that it is preserved even when...
[ardour2.git] / libs / ardour / smf_source.cc
blob9078a17608aaad0c2a7eebb002a2dd66cdf37e0a
1 /*
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.
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 string& path, Source::Flag flags)
54 : Source(s, DataType::MIDI, path, flags)
55 , MidiSource(s, path, flags)
56 , FileSource(s, DataType::MIDI, path, string(), 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 /* note that origin remains empty */
65 if (init(_path, false)) {
66 throw failed_constructor ();
69 /* file is not opened until write */
72 /** Constructor used for existing internal-to-session files. */
73 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
74 : Source(s, node)
75 , MidiSource(s, node)
76 , FileSource(s, node, must_exist)
77 , _last_ev_time_beats(0.0)
78 , _last_ev_time_frames(0)
79 , _smf_last_read_end (0)
80 , _smf_last_read_time (0)
82 if (set_state(node, Stateful::loading_state_version)) {
83 throw failed_constructor ();
86 if (init(_path, true)) {
87 throw failed_constructor ();
90 if (open(_path)) {
91 throw failed_constructor ();
94 _open = true;
97 SMFSource::~SMFSource ()
99 if (removable()) {
100 unlink (_path.c_str());
105 SMFSource::open_for_write ()
107 if (create (_path)) {
108 return -1;
110 _open = true;
111 return 0;
114 /** All stamps in audio frames */
115 framecnt_t
116 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination, framepos_t const source_start,
117 framepos_t start, framecnt_t duration,
118 MidiStateTracker* tracker) const
120 int ret = 0;
121 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
123 if (writable() && !_open) {
124 /* nothing to read since nothing has ben written */
125 return duration;
128 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
130 _read_data_count = 0;
132 // Output parameters for read_event (which will allocate scratch in buffer as needed)
133 uint32_t ev_delta_t = 0;
134 uint32_t ev_type = 0;
135 uint32_t ev_size = 0;
136 uint8_t* ev_buffer = 0;
138 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
140 BeatsFramesConverter converter(_session.tempo_map(), source_start);
142 const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
143 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
145 if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
146 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
147 Evoral::SMF::seek_to_start();
148 while (time < start_ticks) {
149 gint ignored;
151 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
152 if (ret == -1) { // EOF
153 _smf_last_read_end = start + duration;
154 return duration;
156 time += ev_delta_t; // accumulate delta time
158 } else {
159 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
160 time = _smf_last_read_time;
163 _smf_last_read_end = start + duration;
165 while (true) {
166 gint ignored; /* XXX don't ignore note id's ??*/
168 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
169 if (ret == -1) { // EOF
170 break;
173 time += ev_delta_t; // accumulate delta time
174 _smf_last_read_time = time;
176 if (ret == 0) { // meta-event (skipped, just accumulate time)
177 continue;
180 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
182 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
183 ev_delta_t, time, ev_buffer[0], ev_type));
185 assert(time >= start_ticks);
187 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
188 is in session frames.
190 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
192 if (ev_frame_time < start + duration) {
193 destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
195 if (tracker) {
196 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
197 tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
198 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
199 tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
202 } else {
203 break;
206 _read_data_count += ev_size;
208 if (ev_size > scratch_size) {
209 scratch_size = ev_size;
211 ev_size = scratch_size; // ensure read_event only allocates if necessary
214 return duration;
217 /** Write data to this source from a MidiRingBuffer.
218 * @param source Buffer to read from.
219 * @param position This source's start position in session frames.
221 framecnt_t
222 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source, framepos_t position, framecnt_t duration)
224 if (!_writing) {
225 mark_streaming_write_started ();
228 _write_data_count = 0;
230 framepos_t time;
231 Evoral::EventType type;
232 uint32_t size;
234 size_t buf_capacity = 4;
235 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
237 if (_model && ! _model->writing()) {
238 _model->start_write();
241 Evoral::MIDIEvent<framepos_t> ev;
243 cerr << "SMFSource::write unlocked, begins writing from src buffer\n";
245 while (true) {
246 bool ret = source.peek ((uint8_t*)&time, sizeof (time));
247 if (!ret || time > _last_write_end + duration) {
248 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("SMFSource::write_unlocked: dropping event @ %1 because ret %4 or it is later than %2 + %3\n",
249 time, _last_write_end, duration, ret));
250 break;
253 ret = source.read_prefix(&time, &type, &size);
254 if (!ret) {
255 cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
256 break;
259 if (size > buf_capacity) {
260 buf_capacity = size;
261 buf = (uint8_t*)realloc(buf, size);
264 ret = source.read_contents(size, buf);
265 if (!ret) {
266 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
267 break;
270 /* convert from session time to time relative to the source start */
271 assert(time >= position);
272 time -= position;
274 ev.set(buf, size, time);
275 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
276 ev.set_id (Evoral::next_event_id());
278 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
279 /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
280 << std::hex << int(ev.buffer()[0]) << endl;*/
281 continue;
284 cerr << "SMFSource:: calling append_event_unlocked_frames()\n";
285 append_event_unlocked_frames(ev, position);
288 Evoral::SMF::flush();
289 free (buf);
291 return duration;
295 /** Append an event with a timestamp in beats (double) */
296 void
297 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
299 assert(_writing);
300 if (ev.size() == 0) {
301 return;
304 /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
305 name().c_str(), ev.id(), ev.time(), ev.size());
306 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
308 assert(ev.time() >= 0);
309 if (ev.time() < _last_ev_time_beats) {
310 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
311 return;
314 Evoral::event_id_t event_id;
316 if (ev.id() < 0) {
317 event_id = Evoral::next_event_id();
318 } else {
319 event_id = ev.id();
322 if (_model) {
323 _model->append (ev, event_id);
326 _length_beats = max(_length_beats, ev.time());
328 const double delta_time_beats = ev.time() - _last_ev_time_beats;
329 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
331 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
332 _last_ev_time_beats = ev.time();
334 _write_data_count += ev.size();
338 /** Append an event with a timestamp in frames (framepos_t) */
339 void
340 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
342 assert(_writing);
343 if (ev.size() == 0) {
344 cerr << "SMFSource: asked to append zero-size event\n";
345 return;
348 /* printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
349 name().c_str(), ev.id(), ev.time(), ev.size());
350 for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
352 if (ev.time() < _last_ev_time_frames) {
353 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
354 return;
357 BeatsFramesConverter converter(_session.tempo_map(), position);
358 const double ev_time_beats = converter.from(ev.time());
359 Evoral::event_id_t event_id;
361 if (ev.id() < 0) {
362 event_id = Evoral::next_event_id();
363 } else {
364 event_id = ev.id();
367 if (_model) {
368 const Evoral::Event<double> beat_ev (ev.event_type(),
369 ev_time_beats,
370 ev.size(),
371 (uint8_t*)ev.buffer());
372 _model->append (beat_ev, event_id);
375 _length_beats = max(_length_beats, ev_time_beats);
377 const framepos_t delta_time_frames = ev.time() - _last_ev_time_frames;
378 const double delta_time_beats = converter.from(delta_time_frames);
379 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
381 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
382 _last_ev_time_frames = ev.time();
384 _write_data_count += ev.size();
388 XMLNode&
389 SMFSource::get_state ()
391 XMLNode& node = MidiSource::get_state();
392 node.add_property (X_("origin"), _origin);
393 return node;
397 SMFSource::set_state (const XMLNode& node, int version)
399 if (Source::set_state (node, version)) {
400 return -1;
403 if (MidiSource::set_state (node, version)) {
404 return -1;
407 if (FileSource::set_state (node, version)) {
408 return -1;
411 return 0;
414 void
415 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
417 /* CALLER MUST HOLD LOCK */
419 if (!_open && open_for_write()) {
420 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
421 /* XXX should probably throw or return something */
422 return;
425 MidiSource::mark_streaming_midi_write_started (mode);
426 Evoral::SMF::begin_write ();
427 _last_ev_time_beats = 0.0;
428 _last_ev_time_frames = 0;
431 void
432 SMFSource::mark_streaming_write_completed ()
434 Glib::Mutex::Lock lm (_lock);
435 MidiSource::mark_streaming_write_completed();
437 if (!writable()) {
438 return;
441 if (_model) {
442 _model->set_edited(false);
445 Evoral::SMF::end_write ();
447 /* data in the file now, not removable */
449 mark_nonremovable ();
452 bool
453 SMFSource::safe_midi_file_extension (const string& file)
455 return (file.rfind(".mid") != string::npos) || (file.rfind (".MID") != string::npos);
458 void
459 SMFSource::load_model (bool lock, bool force_reload)
461 if (_writing) {
462 return;
465 boost::shared_ptr<Glib::Mutex::Lock> lm;
466 if (lock)
467 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
469 if (_model && !force_reload) {
470 return;
473 if (!_model) {
474 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
475 } else {
476 _model->clear();
479 if (writable() && !_open) {
480 return;
483 _model->start_write();
484 Evoral::SMF::seek_to_start();
486 uint64_t time = 0; /* in SMF ticks */
487 Evoral::Event<double> ev;
489 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
491 uint32_t delta_t = 0;
492 uint32_t size = 0;
493 uint8_t* buf = NULL;
494 int ret;
495 gint event_id;
496 bool have_event_id = false;
498 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
500 time += delta_t;
502 if (ret == 0) {
504 /* meta-event : did we get an event ID ?
507 if (event_id >= 0) {
508 have_event_id = true;
511 continue;
514 if (ret > 0) {
516 /* not a meta-event */
518 ev.set (buf, size, time / (double)ppqn());
519 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
521 if (!have_event_id) {
522 event_id = Evoral::next_event_id();
524 #ifndef NDEBUG
525 std::string ss;
527 for (uint32_t xx = 0; xx < size; ++xx) {
528 char b[8];
529 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
530 ss += b;
533 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
534 delta_t, time, size, ss , ev.event_type(), name()));
535 #endif
537 _model->append (ev, event_id);
539 if (ev.size() > scratch_size) {
540 scratch_size = ev.size();
543 ev.size() = scratch_size; // ensure read_event only allocates if necessary
545 _length_beats = max(_length_beats, ev.time());
548 /* event ID's must immediately precede the event they are for
551 have_event_id = false;
554 _model->end_write (_length_beats, false, true);
555 //_model->end_write (false);
556 _model->set_edited (false);
558 _model_iter = _model->begin();
560 free(buf);
563 void
564 SMFSource::destroy_model ()
566 //cerr << _name << " destroying model " << _model.get() << endl;
567 _model.reset();
570 void
571 SMFSource::flush_midi ()
573 if (!writable() || (writable() && !_open)) {
574 return;
577 Evoral::SMF::end_write ();
578 /* data in the file means its no longer removable */
579 mark_nonremovable ();
582 void
583 SMFSource::set_path (const string& p)
585 FileSource::set_path (p);
586 SMF::set_path (_path);
589 /** Ensure that this source has some file on disk, even if it's just a SMF header */
590 void
591 SMFSource::ensure_disk_file ()
593 if (_model) {
594 /* We have a model, so write it to disk; see MidiSource::session_saved
595 for an explanation of what we are doing here.
597 boost::shared_ptr<MidiModel> mm = _model;
598 _model.reset ();
599 mm->sync_to_source ();
600 _model = mm;
601 } else {
602 /* No model; if it's not already open, it's an empty source, so create
603 and open it for writing.
605 if (!_open) {
606 open_for_write ();
609 /* Flush, which will definitely put something on disk */
610 flush_midi ();