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))
58 , Evoral::SMF<double> ()
59 , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
60 , _allow_remove_if_empty(true)
63 /* constructor used for new internal-to-session files. file cannot exist */
65 if (init (path, false)) {
66 throw failed_constructor ();
70 throw failed_constructor ();
73 assert(_name.find("/") == string::npos);
76 SMFSource::SMFSource (Session& s, const XMLNode& node)
77 : MidiSource (s, node)
78 , _flags (Flag (Writable|CanRename))
79 , _allow_remove_if_empty(true)
82 /* constructor used for existing internal-to-session files. file must exist */
84 if (set_state (node)) {
85 throw failed_constructor ();
88 if (init (_name, true)) {
89 throw failed_constructor ();
93 throw failed_constructor ();
96 assert(_name.find("/") == string::npos);
99 SMFSource::~SMFSource ()
102 unlink (_path.c_str());
107 SMFSource::removable () const
109 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
110 ((_flags & RemovableIfEmpty) && is_empty()));
114 SMFSource::init (string pathstr, bool must_exist)
118 if (!find (pathstr, must_exist, is_new)) {
119 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
123 if (is_new && must_exist) {
127 assert(_name.find("/") == string::npos);
131 /** All stamps in audio frames */
133 SMFSource::read_unlocked (MidiRingBuffer<double>& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
135 //cerr << "SMF read_unlocked " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
137 // 64 bits ought to be enough for anybody
138 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
140 _read_data_count = 0;
142 // Output parameters for read_event (which will allocate scratch in buffer as needed)
143 uint32_t ev_delta_t = 0;
144 uint32_t ev_type = 0;
145 uint32_t ev_size = 0;
146 uint8_t* ev_buffer = 0;
148 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
150 // FIXME: don't seek to start and search every read (brutal!)
151 Evoral::SMF<double>::seek_to_start();
153 // FIXME: assumes tempo never changes after start
154 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
155 _session.engine().frame_rate(),
156 _session.tempo_map().meter_at(_timeline_position));
158 const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
160 while (!Evoral::SMF<double>::eof()) {
161 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
162 if (ret == -1) { // EOF
163 //cerr << "SMF - EOF\n";
167 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
169 time += ev_delta_t; // accumulate delta time
171 if (ret == 0) { // meta-event (skipped, just accumulate time)
172 //cerr << "SMF - META\n";
176 if (time >= start_ticks) {
177 const nframes_t ev_frame_time = (nframes_t)(
178 ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
180 if (ev_frame_time <= start + cnt)
181 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
186 _read_data_count += ev_size;
188 if (ev_size > scratch_size)
189 scratch_size = ev_size;
191 ev_size = scratch_size; // minimize realloc in read_event
197 /** All stamps in audio frames */
199 SMFSource::write_unlocked (MidiRingBuffer<double>& src, nframes_t cnt)
201 _write_data_count = 0;
204 Evoral::EventType type;
207 size_t buf_capacity = 4;
208 uint8_t* buf = (uint8_t*)malloc(buf_capacity);
210 if (_model && ! _model->writing())
211 _model->start_write();
213 Evoral::MIDIEvent<double> ev(0, 0.0, 4, NULL, true);
216 bool ret = src.peek_time(&time);
217 if (!ret || time - _timeline_position > _length + cnt)
220 ret = src.read_prefix(&time, &type, &size);
224 if (size > buf_capacity) {
226 buf = (uint8_t*)realloc(buf, size);
229 ret = src.read_contents(size, buf);
231 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
235 assert(time >= _timeline_position);
236 time -= _timeline_position;
238 ev.set(buf, size, time);
239 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
240 if (! (ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex()) ) {
241 cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type " << std::hex << int(ev.buffer()[0]) << endl;
245 append_event_unlocked(Frames, ev);
253 set_default_controls_interpolation();
256 Evoral::SMF<double>::flush();
259 const nframes_t oldlen = _length;
260 update_length(oldlen, cnt);
262 ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
269 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event<double>& ev)
271 if (ev.size() == 0) {
272 cerr << "SMFSource: Warning: skipping empty event" << endl;
277 printf("SMFSource: %s - append_event_unlocked time = %lf, size = %u, data = ",
278 name().c_str(), ev.time(), ev.size());
279 for (size_t i=0; i < ev.size(); ++i) {
280 printf("%X ", ev.buffer()[i]);
285 assert(ev.time() >= 0);
287 if (ev.time() < last_event_time()) {
288 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
292 uint32_t delta_time = 0;
294 if (unit == Frames) {
295 // FIXME: assumes tempo never changes after start
296 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
297 _session.engine().frame_rate(),
298 _session.tempo_map().meter_at(_timeline_position));
300 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
302 assert(unit == Beats);
303 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
306 Evoral::SMF<double>::append_event_delta(delta_time, ev);
307 _last_ev_time = ev.time();
309 _write_data_count += ev.size();
314 SMFSource::get_state ()
316 XMLNode& root (MidiSource::get_state());
318 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
319 root.add_property ("flags", buf);
324 SMFSource::set_state (const XMLNode& node)
326 const XMLProperty* prop;
328 if (MidiSource::set_state (node)) {
332 if ((prop = node.property (X_("flags"))) != 0) {
335 sscanf (prop->value().c_str(), "0x%x", &ival);
336 _flags = Flag (ival);
344 assert(_name.find("/") == string::npos);
350 SMFSource::mark_for_remove ()
355 _flags = Flag (_flags | RemoveAtDestroy);
359 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
361 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
362 Evoral::SMF<double>::begin_write ();
367 SMFSource::mark_streaming_write_completed ()
369 MidiSource::mark_streaming_write_completed();
375 _model->set_edited(false);
376 Evoral::SMF<double>::end_write ();
380 SMFSource::mark_take (string id)
388 SMFSource::move_to_trash (const string trash_dir_name)
396 /* don't move the file across filesystems, just
397 stick it in the 'trash_dir_name' directory
398 on whichever filesystem it was already on.
401 newpath = Glib::path_get_dirname (_path);
402 newpath = Glib::path_get_dirname (newpath);
405 newpath += trash_dir_name;
407 newpath += Glib::path_get_basename (_path);
409 if (access (newpath.c_str(), F_OK) == 0) {
411 /* the new path already exists, try versioning */
413 char buf[PATH_MAX+1];
417 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
420 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
421 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
425 if (version == 999) {
426 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
435 /* it doesn't exist, or we can't read it or something */
439 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
440 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
441 _path, newpath, strerror (errno))
446 if (::unlink (peakpath.c_str()) != 0) {
447 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
448 peakpath, _path, strerror (errno))
450 /* try to back out */
451 rename (newpath.c_str(), _path.c_str());
458 /* file can not be removed twice, since the operation is not idempotent */
460 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
466 SMFSource::safe_file_extension(const Glib::ustring& file)
468 return (file.rfind(".mid") != Glib::ustring::npos);
471 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
473 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
475 string::size_type pos;
480 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
482 if ((pos = pathstr.find_last_of (':')) == string::npos) {
485 pathstr = pathstr.substr (0, pos);
488 if (pathstr[0] != '/') {
490 /* non-absolute pathname: find pathstr in search path */
497 if (_search_path.length() == 0) {
498 PBD::error << _("FileSource: search path not set") << endmsg;
502 split (_search_path, dirs, ':');
506 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
509 if (fullpath[fullpath.length()-1] != '/') {
514 if (access (fullpath.c_str(), R_OK) == 0) {
522 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
525 } else if (cnt == 0) {
528 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
541 /* external files and/or very very old style sessions include full paths */
544 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
546 if (access (_path.c_str(), R_OK) != 0) {
548 /* file does not exist or we cannot read it */
551 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
555 if (errno != ENOENT) {
556 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
578 SMFSource::set_search_path (string p)
585 SMFSource::set_allow_remove_if_empty (bool yn)
588 _allow_remove_if_empty = yn;
593 SMFSource::set_source_name (string newname, bool destructive)
595 //Glib::Mutex::Lock lm (_lock); FIXME
596 string oldpath = _path;
597 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
599 if (newpath.empty()) {
600 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
604 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
605 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
609 _name = Glib::path_get_basename (newpath);
612 return 0;//rename_peakfile (peak_path (_path));
616 SMFSource::load_model(bool lock, bool force_reload)
624 Glib::Mutex::Lock lm (_lock);
627 if (_model && !force_reload && !_model->empty()) {
632 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
633 cerr << _name << " loaded new model " << _model.get() << endl;
635 cerr << _name << " reloading model " << _model.get()
636 << " (" << _model->n_notes() << " notes)" <<endl;
640 _model->start_write();
641 Evoral::SMF<double>::seek_to_start();
643 uint64_t time = 0; /* in SMF ticks */
644 Evoral::Event<double> ev;
646 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
648 // FIXME: assumes tempo never changes after start
649 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
650 _session.engine().frame_rate(),
651 _session.tempo_map().meter_at(_timeline_position));
653 uint32_t delta_t = 0;
657 while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
659 ev.set(buf, size, 0.0);
662 if (ret > 0) { // didn't skip (meta) event
663 // make ev.time absolute time in frames
664 ev.time() = time * frames_per_beat / (double)ppqn();
665 ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
669 if (ev.size() > scratch_size) {
670 scratch_size = ev.size();
672 ev.size() = scratch_size;
676 set_default_controls_interpolation();
678 _model->end_write(false);
679 _model->set_edited(false);
684 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
687 SMFSource::set_default_controls_interpolation()
689 // set interpolation style to defaults, can be changed by the GUI later
690 Evoral::ControlSet::Controls controls = _model->controls();
691 for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
692 (*c).second->list()->set_interpolation(
693 // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
694 #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
695 EventTypeMap::instance().interpolation_of((*c).first));
697 Evoral::ControlList::Discrete);
704 SMFSource::destroy_model()
706 //cerr << _name << " destroying model " << _model.get() << endl;
711 SMFSource::flush_midi()
713 Evoral::SMF<double>::end_write();