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/smf_source.h>
39 #include <ardour/session.h>
40 #include <ardour/midi_ring_buffer.h>
41 #include <ardour/tempo.h>
42 #include <ardour/audioengine.h>
43 #include <ardour/event_type_map.h>
47 using namespace ARDOUR;
49 string SMFSource::_search_path;
51 SMFSource::SMFSource (Session& s, std::string path, Flag flags)
52 : MidiSource (s, region_name_from_path(path, false))
54 , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
55 , _allow_remove_if_empty(true)
58 /* constructor used for new internal-to-session files. file cannot exist */
60 if (init (path, false)) {
61 throw failed_constructor ();
65 throw failed_constructor ();
68 assert(_name.find("/") == string::npos);
71 SMFSource::SMFSource (Session& s, const XMLNode& node)
72 : MidiSource (s, node)
73 , _flags (Flag (Writable|CanRename))
74 , _allow_remove_if_empty(true)
77 /* constructor used for existing internal-to-session files. file must exist */
79 if (set_state (node)) {
80 throw failed_constructor ();
83 if (init (_name, true)) {
84 throw failed_constructor ();
88 throw failed_constructor ();
91 assert(_name.find("/") == string::npos);
94 SMFSource::~SMFSource ()
97 unlink (_path.c_str());
102 SMFSource::removable () const
104 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
105 ((_flags & RemovableIfEmpty) && is_empty()));
109 SMFSource::init (string pathstr, bool must_exist)
113 if (!find (pathstr, must_exist, is_new)) {
114 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
118 if (is_new && must_exist) {
122 assert(_name.find("/") == string::npos);
126 /** All stamps in audio frames */
128 SMFSource::read_unlocked (MidiRingBuffer<nframes_t>& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
130 //cerr << "SMF read_unlocked " << name() << " read "
131 //<< start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
133 // 64 bits ought to be enough for anybody
134 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
136 _read_data_count = 0;
138 // Output parameters for read_event (which will allocate scratch in buffer as needed)
139 uint32_t ev_delta_t = 0;
140 uint32_t ev_type = 0;
141 uint32_t ev_size = 0;
142 uint8_t* ev_buffer = 0;
144 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
146 // FIXME: don't seek to start and search every read (brutal!)
147 Evoral::SMF::seek_to_start();
149 // FIXME: assumes tempo never changes after start
150 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
151 _session.engine().frame_rate(),
152 _session.tempo_map().meter_at(_timeline_position));
154 const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
156 while (!Evoral::SMF::eof()) {
157 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
158 if (ret == -1) { // EOF
159 //cerr << "SMF - EOF\n";
163 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
165 time += ev_delta_t; // accumulate delta time
167 if (ret == 0) { // meta-event (skipped, just accumulate time)
168 //cerr << "SMF - META\n";
172 if (time >= start_ticks) {
173 const nframes_t ev_frame_time = (nframes_t)(
174 ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
176 if (ev_frame_time <= start + cnt)
177 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
182 _read_data_count += ev_size;
184 if (ev_size > scratch_size)
185 scratch_size = ev_size;
187 ev_size = scratch_size; // minimize realloc in read_event
193 /** All stamps in audio frames */
195 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& src, nframes_t cnt)
197 _write_data_count = 0;
200 Evoral::EventType type;
203 size_t buf_capacity = 4;
204 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
206 if (_model && ! _model->writing())
207 _model->start_write();
209 Evoral::MIDIEvent<double> ev(0, 0.0, 4, NULL, true);
212 bool ret = src.peek_time(&time);
213 if (!ret || time - _timeline_position > _length + cnt)
216 ret = src.read_prefix(&time, &type, &size);
220 if (size > buf_capacity) {
222 buf = (uint8_t*)realloc(buf, size);
225 ret = src.read_contents(size, buf);
227 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
231 assert(time >= _timeline_position);
232 time -= _timeline_position;
234 ev.set(buf, size, time);
235 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
236 if (! (ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex()) ) {
237 cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
238 << std::hex << int(ev.buffer()[0]) << endl;
242 append_event_unlocked(Frames, ev);
250 set_default_controls_interpolation();
253 Evoral::SMF::flush();
256 const nframes_t oldlen = _length;
257 update_length(oldlen, cnt);
259 ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
266 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event<double>& ev)
268 if (ev.size() == 0) {
269 cerr << "SMFSource: Warning: skipping empty event" << endl;
274 printf("SMFSource: %s - append_event_unlocked time = %lf, size = %u, data = ",
275 name().c_str(), ev.time(), ev.size());
276 for (size_t i=0; i < ev.size(); ++i) {
277 printf("%X ", ev.buffer()[i]);
282 assert(ev.time() >= 0);
284 if (ev.time() < last_event_time()) {
285 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
289 uint32_t delta_time = 0;
291 if (unit == Frames) {
292 // FIXME: assumes tempo never changes after start
293 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
294 _session.engine().frame_rate(),
295 _session.tempo_map().meter_at(_timeline_position));
297 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
299 assert(unit == Beats);
300 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
303 Evoral::SMF::append_event_delta(delta_time, ev.size(), ev.buffer());
304 _last_ev_time = ev.time();
306 _write_data_count += ev.size();
311 SMFSource::get_state ()
313 XMLNode& root (MidiSource::get_state());
315 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
316 root.add_property ("flags", buf);
321 SMFSource::set_state (const XMLNode& node)
323 const XMLProperty* prop;
325 if (MidiSource::set_state (node)) {
329 if ((prop = node.property (X_("flags"))) != 0) {
332 sscanf (prop->value().c_str(), "0x%x", &ival);
333 _flags = Flag (ival);
341 assert(_name.find("/") == string::npos);
347 SMFSource::mark_for_remove ()
352 _flags = Flag (_flags | RemoveAtDestroy);
356 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
358 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
359 Evoral::SMF::begin_write ();
364 SMFSource::mark_streaming_write_completed ()
366 MidiSource::mark_streaming_write_completed();
372 _model->set_edited(false);
373 Evoral::SMF::end_write ();
377 SMFSource::mark_take (string id)
385 SMFSource::move_to_trash (const string trash_dir_name)
393 /* don't move the file across filesystems, just
394 stick it in the 'trash_dir_name' directory
395 on whichever filesystem it was already on.
398 newpath = Glib::path_get_dirname (_path);
399 newpath = Glib::path_get_dirname (newpath);
402 newpath += trash_dir_name;
404 newpath += Glib::path_get_basename (_path);
406 if (access (newpath.c_str(), F_OK) == 0) {
408 /* the new path already exists, try versioning */
410 char buf[PATH_MAX+1];
414 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
417 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
418 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
422 if (version == 999) {
423 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
432 /* it doesn't exist, or we can't read it or something */
436 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
437 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
438 _path, newpath, strerror (errno))
443 if (::unlink (peakpath.c_str()) != 0) {
444 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
445 peakpath, _path, strerror (errno))
447 /* try to back out */
448 rename (newpath.c_str(), _path.c_str());
455 /* file can not be removed twice, since the operation is not idempotent */
457 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
463 SMFSource::safe_file_extension(const Glib::ustring& file)
465 return (file.rfind(".mid") != Glib::ustring::npos);
468 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
470 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
472 string::size_type pos;
477 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
479 if ((pos = pathstr.find_last_of (':')) == string::npos) {
482 pathstr = pathstr.substr (0, pos);
485 if (pathstr[0] != '/') {
487 /* non-absolute pathname: find pathstr in search path */
494 if (_search_path.length() == 0) {
495 PBD::error << _("FileSource: search path not set") << endmsg;
499 split (_search_path, dirs, ':');
503 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
506 if (fullpath[fullpath.length()-1] != '/') {
511 if (access (fullpath.c_str(), R_OK) == 0) {
519 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
522 } else if (cnt == 0) {
525 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
538 /* external files and/or very very old style sessions include full paths */
541 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
543 if (access (_path.c_str(), R_OK) != 0) {
545 /* file does not exist or we cannot read it */
548 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
552 if (errno != ENOENT) {
553 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
575 SMFSource::set_search_path (string p)
582 SMFSource::set_allow_remove_if_empty (bool yn)
585 _allow_remove_if_empty = yn;
590 SMFSource::set_source_name (string newname, bool destructive)
592 //Glib::Mutex::Lock lm (_lock); FIXME
593 string oldpath = _path;
594 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
596 if (newpath.empty()) {
597 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
601 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
602 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
606 _name = Glib::path_get_basename (newpath);
609 return 0;//rename_peakfile (peak_path (_path));
613 SMFSource::load_model(bool lock, bool force_reload)
620 Glib::Mutex::Lock lm (_lock);
623 if (_model && !force_reload && !_model->empty()) {
628 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
629 cerr << _name << " loaded new model " << _model.get() << endl;
631 cerr << _name << " reloading model " << _model.get()
632 << " (" << _model->n_notes() << " notes)" <<endl;
636 _model->start_write();
637 Evoral::SMF::seek_to_start();
639 uint64_t time = 0; /* in SMF ticks */
640 Evoral::Event<double> ev;
642 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
644 // FIXME: assumes tempo never changes after start
645 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
646 _session.engine().frame_rate(),
647 _session.tempo_map().meter_at(_timeline_position));
649 uint32_t delta_t = 0;
653 while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
655 ev.set(buf, size, 0.0);
658 if (ret > 0) { // didn't skip (meta) event
659 // make ev.time absolute time in frames
660 ev.time() = time * frames_per_beat / (double)ppqn();
661 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
665 if (ev.size() > scratch_size) {
666 scratch_size = ev.size();
668 ev.size() = scratch_size;
672 set_default_controls_interpolation();
674 _model->end_write(false);
675 _model->set_edited(false);
680 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
683 SMFSource::set_default_controls_interpolation()
685 // set interpolation style to defaults, can be changed by the GUI later
686 Evoral::ControlSet::Controls controls = _model->controls();
687 for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
688 (*c).second->list()->set_interpolation(
689 // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
690 #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
691 EventTypeMap::instance().interpolation_of((*c).first));
693 Evoral::ControlList::Discrete);
700 SMFSource::destroy_model()
702 //cerr << _name << " destroying model " << _model.get() << endl;
707 SMFSource::flush_midi()
709 Evoral::SMF::end_write();