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 /*sigc::signal<void,struct tm*, time_t> SMFSource::HeaderPositionOffsetChanged;
52 bool SMFSource::header_position_negative;
53 uint64_t SMFSource::header_position_offset;
56 SMFSource::SMFSource (Session& s, std::string path, Flag flags)
57 : MidiSource (s, region_name_from_path(path, false))
59 , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
60 , _allow_remove_if_empty(true)
62 /* constructor used for new internal-to-session files. file cannot exist */
64 if (init (path, false)) {
65 throw failed_constructor ();
69 throw failed_constructor ();
72 assert(_name.find("/") == string::npos);
75 SMFSource::SMFSource (Session& s, const XMLNode& node)
76 : MidiSource (s, node)
77 , _flags (Flag (Writable|CanRename))
78 , _allow_remove_if_empty(true)
80 /* constructor used for existing internal-to-session files. file must exist */
82 if (set_state (node)) {
83 throw failed_constructor ();
86 if (init (_name, true)) {
87 throw failed_constructor ();
91 throw failed_constructor ();
94 assert(_name.find("/") == string::npos);
97 SMFSource::~SMFSource ()
100 unlink (_path.c_str());
105 SMFSource::removable () const
107 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
108 ((_flags & RemovableIfEmpty) && is_empty()));
112 SMFSource::init (string pathstr, bool must_exist)
116 if (!find (pathstr, must_exist, is_new)) {
117 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
121 if (is_new && must_exist) {
125 assert(_name.find("/") == string::npos);
129 /** All stamps in audio frames */
131 SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
133 //cerr << "SMF read_unlocked " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
135 // 64 bits ought to be enough for anybody
136 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
138 _read_data_count = 0;
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 // FIXME: don't seek to start and search every read (brutal!)
149 SMF::seek_to_start();
151 // FIXME: assumes tempo never changes after start
152 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
153 _session.engine().frame_rate(),
154 _session.tempo_map().meter_at(_timeline_position));
156 const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
158 while (!SMF::eof()) {
159 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
160 if (ret == -1) { // EOF
161 //cerr << "SMF - EOF\n";
165 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
167 time += ev_delta_t; // accumulate delta time
169 if (ret == 0) { // meta-event (skipped, just accumulate time)
170 //cerr << "SMF - META\n";
174 if (time >= start_ticks) {
175 const nframes_t ev_frame_time = (nframes_t)(
176 ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
178 if (ev_frame_time <= start + cnt)
179 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
184 _read_data_count += ev_size;
186 if (ev_size > scratch_size)
187 scratch_size = ev_size;
189 ev_size = scratch_size; // minimize realloc in read_event
195 /** All stamps in audio frames */
197 SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
199 _write_data_count = 0;
201 Evoral::EventTime time;
202 Evoral::EventType type;
205 size_t buf_capacity = 4;
206 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
208 if (_model && ! _model->writing())
209 _model->start_write();
211 Evoral::MIDIEvent ev(0, 0.0, 4, NULL, true);
214 bool ret = src.peek_time(&time);
215 if (!ret || time - _timeline_position > _length + cnt)
218 ret = src.read_prefix(&time, &type, &size);
222 if (size > buf_capacity) {
224 buf = (uint8_t*)realloc(buf, size);
227 ret = src.read_contents(size, buf);
229 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
233 assert(time >= _timeline_position);
234 time -= _timeline_position;
236 ev.set(buf, size, time);
237 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
238 if (! (ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex()) ) {
239 cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type " << std::hex << int(ev.buffer()[0]) << endl;
243 append_event_unlocked(Frames, ev);
251 make_sure_controls_have_the_right_interpolation();
257 const nframes_t oldlen = _length;
258 update_length(oldlen, cnt);
260 ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
267 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event& ev)
269 if (ev.size() == 0) {
270 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]);
281 assert(ev.time() >= 0);
283 if (ev.time() < last_event_time()) {
284 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
288 uint32_t delta_time = 0;
290 if (unit == Frames) {
291 // FIXME: assumes tempo never changes after start
292 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
293 _session.engine().frame_rate(),
294 _session.tempo_map().meter_at(_timeline_position));
296 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
298 assert(unit == Beats);
299 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
302 SMF::append_event_unlocked(delta_time, ev);
304 _write_data_count += ev.size();
309 SMFSource::get_state ()
311 XMLNode& root (MidiSource::get_state());
313 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
314 root.add_property ("flags", buf);
319 SMFSource::set_state (const XMLNode& node)
321 const XMLProperty* prop;
323 if (MidiSource::set_state (node)) {
327 if ((prop = node.property (X_("flags"))) != 0) {
330 sscanf (prop->value().c_str(), "0x%x", &ival);
331 _flags = Flag (ival);
339 assert(_name.find("/") == string::npos);
345 SMFSource::mark_for_remove ()
350 _flags = Flag (_flags | RemoveAtDestroy);
354 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
356 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
357 SMF::begin_write (start_frame);
361 SMFSource::mark_streaming_write_completed ()
363 MidiSource::mark_streaming_write_completed();
369 _model->set_edited(false);
374 SMFSource::mark_take (string id)
382 SMFSource::move_to_trash (const string trash_dir_name)
390 /* don't move the file across filesystems, just
391 stick it in the 'trash_dir_name' directory
392 on whichever filesystem it was already on.
395 newpath = Glib::path_get_dirname (_path);
396 newpath = Glib::path_get_dirname (newpath);
399 newpath += trash_dir_name;
401 newpath += Glib::path_get_basename (_path);
403 if (access (newpath.c_str(), F_OK) == 0) {
405 /* the new path already exists, try versioning */
407 char buf[PATH_MAX+1];
411 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
414 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
415 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
419 if (version == 999) {
420 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
429 /* it doesn't exist, or we can't read it or something */
433 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
434 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
435 _path, newpath, strerror (errno))
440 if (::unlink (peakpath.c_str()) != 0) {
441 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
442 peakpath, _path, strerror (errno))
444 /* try to back out */
445 rename (newpath.c_str(), _path.c_str());
452 /* file can not be removed twice, since the operation is not idempotent */
454 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
460 SMFSource::safe_file_extension(const Glib::ustring& file)
462 return (file.rfind(".mid") != Glib::ustring::npos);
465 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
467 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
469 string::size_type pos;
474 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
476 if ((pos = pathstr.find_last_of (':')) == string::npos) {
479 pathstr = pathstr.substr (0, pos);
482 if (pathstr[0] != '/') {
484 /* non-absolute pathname: find pathstr in search path */
491 if (_search_path.length() == 0) {
492 PBD::error << _("FileSource: search path not set") << endmsg;
496 split (_search_path, dirs, ':');
500 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
503 if (fullpath[fullpath.length()-1] != '/') {
508 if (access (fullpath.c_str(), R_OK) == 0) {
516 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
519 } else if (cnt == 0) {
522 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
535 /* external files and/or very very old style sessions include full paths */
538 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
540 if (access (_path.c_str(), R_OK) != 0) {
542 /* file does not exist or we cannot read it */
545 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
549 if (errno != ENOENT) {
550 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
572 SMFSource::set_search_path (string p)
579 SMFSource::set_allow_remove_if_empty (bool yn)
582 _allow_remove_if_empty = yn;
587 SMFSource::set_source_name (string newname, bool destructive)
589 //Glib::Mutex::Lock lm (_lock); FIXME
590 string oldpath = _path;
591 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
593 if (newpath.empty()) {
594 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
598 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
599 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
603 _name = Glib::path_get_basename (newpath);
606 return 0;//rename_peakfile (peak_path (_path));
610 SMFSource::load_model(bool lock, bool force_reload)
618 Glib::Mutex::Lock lm (_lock);
621 if (_model && !force_reload && !_model->empty()) {
626 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
627 cerr << _name << " loaded new model " << _model.get() << endl;
629 cerr << _name << " reloading model " << _model.get()
630 << " (" << _model->n_notes() << " notes)" <<endl;
634 _model->start_write();
635 SMF::seek_to_start();
637 uint64_t time = 0; /* in SMF ticks */
640 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
642 // FIXME: assumes tempo never changes after start
643 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
644 _session.engine().frame_rate(),
645 _session.tempo_map().meter_at(_timeline_position));
647 uint32_t delta_t = 0;
651 while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
653 ev.set(buf, size, 0.0);
656 if (ret > 0) { // didn't skip (meta) event
657 // make ev.time absolute time in frames
658 ev.time() = time * frames_per_beat / (Evoral::EventTime)ppqn();
659 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
663 if (ev.size() > scratch_size) {
664 scratch_size = ev.size();
666 ev.size() = scratch_size;
670 make_sure_controls_have_the_right_interpolation();
672 _model->end_write(false);
673 _model->set_edited(false);
678 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
681 SMFSource::make_sure_controls_have_the_right_interpolation()
683 // set interpolation style to defaults, can be changed by the GUI later
684 Evoral::ControlSet::Controls controls = _model->controls();
685 for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
686 (*c).second->list()->set_interpolation(
687 // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
688 #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
689 EventTypeMap::instance().interpolation_of((*c).first));
691 Evoral::ControlList::Discrete);
698 SMFSource::destroy_model()
700 //cerr << _name << " destroying model " << _model.get() << endl;
705 SMFSource::flush_midi()