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)
272 /*printf("SMFSource: %s - append_event_unlocked chan = %u, time = %lf, size = %u, data = ",
273 name().c_str(), (unsigned)ev.channel(), ev.time(), ev.size());
274 for (size_t i=0; i < ev.size(); ++i) {
275 printf("%X ", ev.buffer()[i]);
279 assert(ev.time() >= 0);
281 if (ev.time() < last_event_time()) {
282 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
286 uint32_t delta_time = 0;
288 if (unit == Frames) {
289 // FIXME: assumes tempo never changes after start
290 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
291 _session.engine().frame_rate(),
292 _session.tempo_map().meter_at(_timeline_position));
294 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
296 assert(unit == Beats);
297 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
300 SMF::append_event_unlocked(delta_time, ev);
302 _write_data_count += ev.size();
307 SMFSource::get_state ()
309 XMLNode& root (MidiSource::get_state());
311 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
312 root.add_property ("flags", buf);
317 SMFSource::set_state (const XMLNode& node)
319 const XMLProperty* prop;
321 if (MidiSource::set_state (node)) {
325 if ((prop = node.property (X_("flags"))) != 0) {
328 sscanf (prop->value().c_str(), "0x%x", &ival);
329 _flags = Flag (ival);
337 assert(_name.find("/") == string::npos);
343 SMFSource::mark_for_remove ()
348 _flags = Flag (_flags | RemoveAtDestroy);
352 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
354 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
355 SMF::begin_write (start_frame);
359 SMFSource::mark_streaming_write_completed ()
361 MidiSource::mark_streaming_write_completed();
367 _model->set_edited(false);
372 SMFSource::mark_take (string id)
380 SMFSource::move_to_trash (const string trash_dir_name)
388 /* don't move the file across filesystems, just
389 stick it in the 'trash_dir_name' directory
390 on whichever filesystem it was already on.
393 newpath = Glib::path_get_dirname (_path);
394 newpath = Glib::path_get_dirname (newpath);
397 newpath += trash_dir_name;
399 newpath += Glib::path_get_basename (_path);
401 if (access (newpath.c_str(), F_OK) == 0) {
403 /* the new path already exists, try versioning */
405 char buf[PATH_MAX+1];
409 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
412 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
413 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
417 if (version == 999) {
418 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
427 /* it doesn't exist, or we can't read it or something */
431 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
432 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
433 _path, newpath, strerror (errno))
438 if (::unlink (peakpath.c_str()) != 0) {
439 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
440 peakpath, _path, strerror (errno))
442 /* try to back out */
443 rename (newpath.c_str(), _path.c_str());
450 /* file can not be removed twice, since the operation is not idempotent */
452 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
458 SMFSource::safe_file_extension(const Glib::ustring& file)
460 return (file.rfind(".mid") != Glib::ustring::npos);
463 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
465 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
467 string::size_type pos;
472 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
474 if ((pos = pathstr.find_last_of (':')) == string::npos) {
477 pathstr = pathstr.substr (0, pos);
480 if (pathstr[0] != '/') {
482 /* non-absolute pathname: find pathstr in search path */
489 if (_search_path.length() == 0) {
490 PBD::error << _("FileSource: search path not set") << endmsg;
494 split (_search_path, dirs, ':');
498 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
501 if (fullpath[fullpath.length()-1] != '/') {
506 if (access (fullpath.c_str(), R_OK) == 0) {
514 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
517 } else if (cnt == 0) {
520 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
533 /* external files and/or very very old style sessions include full paths */
536 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
538 if (access (_path.c_str(), R_OK) != 0) {
540 /* file does not exist or we cannot read it */
543 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
547 if (errno != ENOENT) {
548 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
570 SMFSource::set_search_path (string p)
577 SMFSource::set_allow_remove_if_empty (bool yn)
580 _allow_remove_if_empty = yn;
585 SMFSource::set_source_name (string newname, bool destructive)
587 //Glib::Mutex::Lock lm (_lock); FIXME
588 string oldpath = _path;
589 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
591 if (newpath.empty()) {
592 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
596 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
597 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
601 _name = Glib::path_get_basename (newpath);
604 return 0;//rename_peakfile (peak_path (_path));
608 SMFSource::load_model(bool lock, bool force_reload)
616 Glib::Mutex::Lock lm (_lock);
619 if (_model && !force_reload && !_model->empty()) {
624 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
625 cerr << _name << " loaded new model " << _model.get() << endl;
627 cerr << _name << " reloading model " << _model.get()
628 << " (" << _model->n_notes() << " notes)" <<endl;
632 _model->start_write();
633 SMF::seek_to_start();
635 uint64_t time = 0; /* in SMF ticks */
638 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
640 // FIXME: assumes tempo never changes after start
641 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
642 _session.engine().frame_rate(),
643 _session.tempo_map().meter_at(_timeline_position));
645 uint32_t delta_t = 0;
649 while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
651 ev.set(buf, size, 0.0);
654 if (ret > 0) { // didn't skip (meta) event
655 // make ev.time absolute time in frames
656 ev.time() = time * frames_per_beat / (Evoral::EventTime)ppqn();
657 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
661 if (ev.size() > scratch_size) {
662 scratch_size = ev.size();
664 ev.size() = scratch_size;
668 make_sure_controls_have_the_right_interpolation();
670 _model->end_write(false);
671 _model->set_edited(false);
676 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
679 SMFSource::make_sure_controls_have_the_right_interpolation()
681 // set interpolation style to defaults, can be changed by the GUI later
682 Evoral::ControlSet::Controls controls = _model->controls();
683 for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
684 (*c).second->list()->set_interpolation(
685 // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
686 #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
687 EventTypeMap::instance().interpolation_of((*c).first));
689 Evoral::ControlList::Discrete);
696 SMFSource::destroy_model()
698 //cerr << _name << " destroying model " << _model.get() << endl;
703 SMFSource::flush_midi()