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>
37 #include <ardour/smf_source.h>
38 #include <ardour/session.h>
39 #include <ardour/midi_ring_buffer.h>
40 #include <ardour/tempo.h>
41 #include <ardour/audioengine.h>
42 #include <ardour/event_type_map.h>
46 using namespace ARDOUR;
48 string SMFSource::_search_path;
50 /*sigc::signal<void,struct tm*, time_t> SMFSource::HeaderPositionOffsetChanged;
51 bool SMFSource::header_position_negative;
52 uint64_t SMFSource::header_position_offset;
55 SMFSource::SMFSource (Session& s, std::string path, Flag flags)
56 : MidiSource (s, region_name_from_path(path, false))
58 , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
59 , _allow_remove_if_empty(true)
61 /* constructor used for new internal-to-session files. file cannot exist */
63 if (init (path, false)) {
64 throw failed_constructor ();
68 throw failed_constructor ();
71 assert(_name.find("/") == string::npos);
74 SMFSource::SMFSource (Session& s, const XMLNode& node)
75 : MidiSource (s, node)
76 , _flags (Flag (Writable|CanRename))
77 , _allow_remove_if_empty(true)
79 /* constructor used for existing internal-to-session files. file must exist */
81 if (set_state (node)) {
82 throw failed_constructor ();
85 if (init (_name, true)) {
86 throw failed_constructor ();
90 throw failed_constructor ();
93 assert(_name.find("/") == string::npos);
96 SMFSource::~SMFSource ()
99 unlink (_path.c_str());
104 SMFSource::removable () const
106 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
107 ((_flags & RemovableIfEmpty) && is_empty()));
111 SMFSource::init (string pathstr, bool must_exist)
115 if (!find (pathstr, must_exist, is_new)) {
116 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
120 if (is_new && must_exist) {
124 assert(_name.find("/") == string::npos);
128 /** All stamps in audio frames */
130 SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
132 //cerr << "SMF read_unlocked " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
134 // 64 bits ought to be enough for anybody
135 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
137 _read_data_count = 0;
139 // Output parameters for read_event (which will allocate scratch in buffer as needed)
140 uint32_t ev_delta_t = 0;
141 uint32_t ev_type = 0;
142 uint32_t ev_size = 0;
143 uint8_t* ev_buffer = 0;
145 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
147 // FIXME: don't seek to start and search every read (brutal!)
148 SMF::seek_to_start();
150 // FIXME: assumes tempo never changes after start
151 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
152 _session.engine().frame_rate(),
153 _session.tempo_map().meter_at(_timeline_position));
155 const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
157 while (!SMF::eof()) {
158 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
159 if (ret == -1) { // EOF
160 //cerr << "SMF - EOF\n";
164 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
166 time += ev_delta_t; // accumulate delta time
168 if (ret == 0) { // meta-event (skipped, just accumulate time)
169 //cerr << "SMF - META\n";
173 if (time >= start_ticks) {
174 const nframes_t ev_frame_time = (nframes_t)(
175 ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
177 if (ev_frame_time <= start + cnt)
178 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
183 _read_data_count += ev_size;
185 if (ev_size > scratch_size)
186 scratch_size = ev_size;
188 ev_size = scratch_size; // minimize realloc in read_event
194 /** All stamps in audio frames */
196 SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
198 _write_data_count = 0;
200 Evoral::EventTime time;
201 Evoral::EventType type;
204 size_t buf_capacity = 4;
205 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
207 if (_model && ! _model->writing())
208 _model->start_write();
210 Evoral::MIDIEvent ev(0, 0.0, 4, NULL, true);
213 bool ret = src.peek_time(&time);
214 if (!ret || time - _timeline_position > _length + cnt)
217 ret = src.read_prefix(&time, &type, &size);
221 if (size > buf_capacity) {
223 buf = (uint8_t*)realloc(buf, size);
226 ret = src.read_contents(size, buf);
228 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
232 assert(time >= _timeline_position);
233 time -= _timeline_position;
235 ev.set(buf, size, time);
236 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
237 if (! (ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex()) ) {
238 //cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type " << std::hex << int(ev.buffer()[0]) << endl;
242 append_event_unlocked(Frames, ev);
251 const nframes_t oldlen = _length;
252 update_length(oldlen, cnt);
254 ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
261 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event& ev)
266 /*printf("SMFSource: %s - append_event_unlocked chan = %u, time = %lf, size = %u, data = ",
267 name().c_str(), (unsigned)ev.channel(), ev.time(), ev.size());
268 for (size_t i=0; i < ev.size(); ++i) {
269 printf("%X ", ev.buffer()[i]);
273 assert(ev.time() >= 0);
275 if (ev.time() < last_event_time()) {
276 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
280 uint32_t delta_time = 0;
282 if (unit == Frames) {
283 // FIXME: assumes tempo never changes after start
284 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
285 _session.engine().frame_rate(),
286 _session.tempo_map().meter_at(_timeline_position));
288 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
290 assert(unit == Beats);
291 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
294 SMF::append_event_unlocked(delta_time, ev);
296 _write_data_count += ev.size();
301 SMFSource::get_state ()
303 XMLNode& root (MidiSource::get_state());
305 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
306 root.add_property ("flags", buf);
311 SMFSource::set_state (const XMLNode& node)
313 const XMLProperty* prop;
315 if (MidiSource::set_state (node)) {
319 if ((prop = node.property (X_("flags"))) != 0) {
322 sscanf (prop->value().c_str(), "0x%x", &ival);
323 _flags = Flag (ival);
331 assert(_name.find("/") == string::npos);
337 SMFSource::mark_for_remove ()
342 _flags = Flag (_flags | RemoveAtDestroy);
346 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
348 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
349 SMF::begin_write (start_frame);
353 SMFSource::mark_streaming_write_completed ()
355 MidiSource::mark_streaming_write_completed();
361 _model->set_edited(false);
366 SMFSource::mark_take (string id)
374 SMFSource::move_to_trash (const string trash_dir_name)
382 /* don't move the file across filesystems, just
383 stick it in the 'trash_dir_name' directory
384 on whichever filesystem it was already on.
387 newpath = Glib::path_get_dirname (_path);
388 newpath = Glib::path_get_dirname (newpath);
391 newpath += trash_dir_name;
393 newpath += Glib::path_get_basename (_path);
395 if (access (newpath.c_str(), F_OK) == 0) {
397 /* the new path already exists, try versioning */
399 char buf[PATH_MAX+1];
403 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
406 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
407 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
411 if (version == 999) {
412 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
421 /* it doesn't exist, or we can't read it or something */
425 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
426 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
427 _path, newpath, strerror (errno))
432 if (::unlink (peakpath.c_str()) != 0) {
433 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
434 peakpath, _path, strerror (errno))
436 /* try to back out */
437 rename (newpath.c_str(), _path.c_str());
444 /* file can not be removed twice, since the operation is not idempotent */
446 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
452 SMFSource::safe_file_extension(const Glib::ustring& file)
454 return (file.rfind(".mid") != Glib::ustring::npos);
457 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
459 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
461 string::size_type pos;
466 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
468 if ((pos = pathstr.find_last_of (':')) == string::npos) {
471 pathstr = pathstr.substr (0, pos);
474 if (pathstr[0] != '/') {
476 /* non-absolute pathname: find pathstr in search path */
483 if (_search_path.length() == 0) {
484 PBD::error << _("FileSource: search path not set") << endmsg;
488 split (_search_path, dirs, ':');
492 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);
598 return 0;//rename_peakfile (peak_path (_path));
602 SMFSource::load_model(bool lock, bool force_reload)
608 Glib::Mutex::Lock lm (_lock);
610 if (_model && !force_reload && !_model->empty())
614 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
615 cerr << _name << " loaded new model " << _model.get() << endl;
617 cerr << _name << " reloading model " << _model.get()
618 << " (" << _model->n_notes() << " notes)" <<endl;
622 _model->start_write();
623 SMF::seek_to_start();
625 uint64_t time = 0; /* in SMF ticks */
628 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
630 // FIXME: assumes tempo never changes after start
631 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
632 _session.engine().frame_rate(),
633 _session.tempo_map().meter_at(_timeline_position));
635 uint32_t delta_t = 0;
639 while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
641 ev.set(buf, size, 0.0);
644 if (ret > 0) { // didn't skip (meta) event
645 // make ev.time absolute time in frames
646 ev.time() = time * frames_per_beat / (Evoral::EventTime)ppqn();
647 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
651 if (ev.size() > scratch_size)
652 scratch_size = ev.size();
654 ev.size() = scratch_size;
657 _model->end_write(false);
658 _model->set_edited(false);
665 SMFSource::destroy_model()
667 //cerr << _name << " destroying model " << _model.get() << endl;
672 SMFSource::flush_midi()