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.
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/SMFReader.hpp>
36 #include <evoral/Control.hpp>
38 #include <ardour/audioengine.h>
39 #include <ardour/event_type_map.h>
40 #include <ardour/midi_model.h>
41 #include <ardour/midi_ring_buffer.h>
42 #include <ardour/session.h>
43 #include <ardour/smf_source.h>
47 using namespace ARDOUR;
49 string SMFSource::_search_path;
51 /** Constructor used for new internal-to-session files. File cannot exist. */
52 SMFSource::SMFSource(Session& s, std::string path, Source::Flag flags)
53 : MidiSource(s, region_name_from_path(path, false))
55 , _allow_remove_if_empty(true)
56 , _last_ev_time_beats(0.0)
57 , _last_ev_time_frames(0)
59 if (init(path, false)) {
60 throw failed_constructor ();
64 throw failed_constructor ();
67 assert(_name.find("/") == string::npos);
70 /** Constructor used for existing internal-to-session files. File must exist. */
71 SMFSource::SMFSource(Session& s, const XMLNode& node)
73 , _allow_remove_if_empty(true)
74 , _last_ev_time_beats(0.0)
75 , _last_ev_time_frames(0)
77 if (set_state(node)) {
78 throw failed_constructor ();
81 if (init(_name, true)) {
82 throw failed_constructor ();
86 throw failed_constructor ();
89 assert(_name.find("/") == string::npos);
92 SMFSource::~SMFSource ()
95 unlink (_path.c_str());
100 SMFSource::removable () const
102 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
103 ((_flags & RemovableIfEmpty) && is_empty()));
107 SMFSource::init (string pathstr, bool must_exist)
111 if (!find (pathstr, must_exist, is_new)) {
112 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
116 if (is_new && must_exist) {
120 assert(_name.find("/") == string::npos);
124 /** All stamps in audio frames */
126 SMFSource::read_unlocked (MidiRingBuffer<nframes_t>& dst, nframes_t start, nframes_t dur,
127 nframes_t stamp_offset, nframes_t negative_stamp_offset) const
129 //cerr << "SMF read_unlocked " << name() << " read "
130 //<< start << ", count=" << dur << ", offset=" << stamp_offset << endl;
133 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
135 _read_data_count = 0;
137 // Output parameters for read_event (which will allocate scratch in buffer as needed)
138 uint32_t ev_delta_t = 0;
139 uint32_t ev_type = 0;
140 uint32_t ev_size = 0;
141 uint8_t* ev_buffer = 0;
143 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
145 const uint64_t start_ticks = (uint64_t)(_converter.from(start) * ppqn());
147 if (_last_read_end == 0 || start != _last_read_end) {
148 cerr << "SMFSource::read_unlocked seeking to " << start << endl;
149 Evoral::SMF::seek_to_start();
150 while (time < start_ticks) {
151 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
152 if (ret == -1) { // EOF
153 _last_read_end = start + dur;
156 time += ev_delta_t; // accumulate delta time
160 _last_read_end = start + dur;
163 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
164 if (ret == -1) { // EOF
168 time += ev_delta_t; // accumulate delta time
170 if (ret == 0) { // meta-event (skipped, just accumulate time)
174 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
176 assert(time >= start_ticks);
177 const nframes_t ev_frame_time = _converter.to(time / (double)ppqn()) + stamp_offset;
179 if (ev_frame_time < start + dur) {
180 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
185 _read_data_count += ev_size;
187 if (ev_size > scratch_size) {
188 scratch_size = ev_size;
190 ev_size = scratch_size; // ensure read_event only allocates if necessary
196 /** All stamps in audio frames */
198 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& src, nframes_t dur)
200 _write_data_count = 0;
203 Evoral::EventType type;
206 size_t buf_capacity = 4;
207 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
209 if (_model && ! _model->writing()) {
210 _model->start_write();
213 Evoral::MIDIEvent<nframes_t> ev(0, 0.0, 4, NULL, true);
216 bool ret = src.peek_time(&time);
217 if (!ret || time - _timeline_position > _length + dur) {
221 ret = src.read_prefix(&time, &type, &size);
226 if (size > buf_capacity) {
228 buf = (uint8_t*)realloc(buf, size);
231 ret = src.read_contents(size, buf);
233 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
237 assert(time >= _timeline_position);
238 time -= _timeline_position;
240 ev.set(buf, size, time);
241 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
242 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
243 cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
244 << std::hex << int(ev.buffer()[0]) << endl;
248 append_event_unlocked_frames(ev);
252 set_default_controls_interpolation();
255 Evoral::SMF::flush();
258 const nframes_t oldlen = _length;
259 update_length(oldlen, dur);
261 ViewDataRangeReady(_timeline_position + oldlen, dur); /* EMIT SIGNAL */
267 /** Append an event with a timestamp in beats (double) */
269 SMFSource::append_event_unlocked_beats(const Evoral::Event<double>& ev)
271 if (ev.size() == 0) {
275 /*printf("SMFSource: %s - append_event_unlocked_beats time = %lf, size = %u, data = ",
276 name().c_str(), ev.time(), ev.size());
277 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
279 assert(ev.time() >= 0);
280 if (ev.time() < _last_ev_time_beats) {
281 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
285 const double delta_time_beats = ev.time() - _last_ev_time_beats;
286 const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
288 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer());
289 _last_ev_time_beats = ev.time();
291 _write_data_count += ev.size();
298 /** Append an event with a timestamp in frames (nframes_t) */
300 SMFSource::append_event_unlocked_frames(const Evoral::Event<nframes_t>& ev)
302 if (ev.size() == 0) {
306 /*printf("SMFSource: %s - append_event_unlocked_frames time = %u, size = %u, data = ",
307 name().c_str(), ev.time(), ev.size());
308 for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
310 assert(ev.time() >= 0);
311 if (ev.time() < _last_ev_time_frames) {
312 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
316 const nframes_t delta_time_frames = ev.time() - _last_ev_time_frames;
317 const double delta_time_beats = _converter.from(delta_time_frames);
318 const uint32_t delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
320 Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer());
321 _last_ev_time_frames = ev.time();
323 _write_data_count += ev.size();
326 const double ev_time_beats = _converter.from(ev.time());
327 const Evoral::Event<double> beat_ev(
328 ev.event_type(), ev_time_beats, ev.size(), (uint8_t*)ev.buffer());
329 _model->append(beat_ev);
335 SMFSource::get_state ()
337 XMLNode& root (MidiSource::get_state());
339 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
340 root.add_property ("flags", buf);
345 SMFSource::set_state (const XMLNode& node)
347 const XMLProperty* prop;
349 if (MidiSource::set_state (node)) {
353 if ((prop = node.property (X_("flags"))) != 0) {
355 sscanf (prop->value().c_str(), "0x%x", &ival);
356 _flags = Flag (ival);
361 assert(_name.find("/") == string::npos);
367 SMFSource::mark_for_remove ()
372 _flags = Flag (_flags | RemoveAtDestroy);
376 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
378 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
379 Evoral::SMF::begin_write ();
380 _last_ev_time_beats = 0.0;
381 _last_ev_time_frames = 0;
385 SMFSource::mark_streaming_write_completed ()
387 MidiSource::mark_streaming_write_completed();
393 _model->set_edited(false);
394 Evoral::SMF::end_write ();
398 SMFSource::mark_take (string id)
406 SMFSource::move_to_trash (const string trash_dir_name)
412 /* don't move the file across filesystems, just stick it in the
413 trash_dir_name directory on whichever filesystem it was already on
416 Glib::ustring newpath;
417 newpath = Glib::path_get_dirname (_path);
418 newpath = Glib::path_get_dirname (newpath);
420 newpath += string("/") + trash_dir_name + "/";
421 newpath += Glib::path_get_basename (_path);
423 /* the new path already exists, try versioning */
424 if (access (newpath.c_str(), F_OK) == 0) {
425 char buf[PATH_MAX+1];
429 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
432 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
433 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
437 if (version == 999) {
438 PBD::error << string_compose (
439 _("there are already 1000 files with names like %1; versioning discontinued"),
446 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
447 PBD::error << string_compose (
448 _("cannot rename midi file source from %1 to %2 (%3)"),
449 _path, newpath, strerror (errno)) << endmsg;
455 /* file can not be removed twice, since the operation is not idempotent */
456 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
462 SMFSource::safe_file_extension(const Glib::ustring& file)
464 return (file.rfind(".mid") != Glib::ustring::npos);
467 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
469 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
475 if (pathstr[0] != '/') {
477 /* non-absolute pathname: find pathstr in search path */
484 if (_search_path.length() == 0) {
485 PBD::error << _("FileSource: search path not set") << endmsg;
489 split (_search_path, dirs, ':');
493 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
495 if (fullpath[fullpath.length()-1] != '/') {
500 if (access (fullpath.c_str(), R_OK) == 0) {
508 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
511 } else if (cnt == 0) {
514 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
527 /* external files and/or very very old style sessions include full paths */
530 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
532 if (access (_path.c_str(), R_OK) != 0) {
534 /* file does not exist or we cannot read it */
537 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
541 if (errno != ENOENT) {
542 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
564 SMFSource::set_search_path (string p)
571 SMFSource::set_allow_remove_if_empty (bool yn)
574 _allow_remove_if_empty = yn;
579 SMFSource::set_source_name (string newname, bool destructive)
581 //Glib::Mutex::Lock lm (_lock); FIXME
582 string oldpath = _path;
583 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
585 if (newpath.empty()) {
586 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
590 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
591 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
595 _name = Glib::path_get_basename (newpath);
602 SMFSource::load_model(bool lock, bool force_reload)
609 Glib::Mutex::Lock lm (_lock);
612 if (_model && !force_reload) {
617 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
618 cerr << _name << " loaded new model " << _model.get() << endl;
620 cerr << _name << " reloading model " << _model.get()
621 << " (" << _model->n_notes() << " notes)" <<endl;
625 _model->start_write();
626 Evoral::SMF::seek_to_start();
628 uint64_t time = 0; /* in SMF ticks */
629 Evoral::Event<double> ev;
631 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
633 uint32_t delta_t = 0;
637 while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
639 ev.set(buf, size, time / (double)ppqn());
641 if (ret > 0) { // didn't skip (meta) event
642 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
646 if (ev.size() > scratch_size) {
647 scratch_size = ev.size();
649 ev.size() = scratch_size; // ensure read_event only allocates if necessary
652 set_default_controls_interpolation();
654 _model->end_write(false);
655 _model->set_edited(false);
657 _model_iter = _model->begin();
662 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
665 SMFSource::set_default_controls_interpolation()
667 // set interpolation style to defaults, can be changed by the GUI later
668 Evoral::ControlSet::Controls controls = _model->controls();
669 for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
670 (*c).second->list()->set_interpolation(
671 // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
672 #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
673 EventTypeMap::instance().interpolation_of((*c).first));
675 Evoral::ControlList::Discrete);
682 SMFSource::destroy_model()
684 //cerr << _name << " destroying model " << _model.get() << endl;
689 SMFSource::flush_midi()
691 Evoral::SMF::end_write();