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 <ardour/smf_source.h>
36 #include <ardour/session.h>
37 #include <ardour/midi_ring_buffer.h>
38 #include <ardour/midi_util.h>
39 #include <ardour/tempo.h>
40 #include <ardour/audioengine.h>
44 using namespace ARDOUR;
46 string SMFSource::_search_path;
48 /*sigc::signal<void,struct tm*, time_t> SMFSource::HeaderPositionOffsetChanged;
49 bool SMFSource::header_position_negative;
50 uint64_t SMFSource::header_position_offset;
53 SMFSource::SMFSource (Session& s, std::string path, Flag flags)
54 : MidiSource (s, region_name_from_path(path, false))
56 , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
57 , _allow_remove_if_empty(true)
60 , _track_size(4) // 4 bytes for the ever-present EOT event
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 //cerr << "SMF Source path: " << path << endl;
75 assert(_name.find("/") == string::npos);
78 SMFSource::SMFSource (Session& s, const XMLNode& node)
79 : MidiSource (s, node)
81 , _flags (Flag (Writable|CanRename))
82 , _allow_remove_if_empty(true)
85 , _track_size(4) // 4 bytes for the ever-present EOT event
88 /* constructor used for existing internal-to-session files. file must exist */
90 if (set_state (node)) {
91 throw failed_constructor ();
94 if (init (_name, true)) {
95 throw failed_constructor ();
99 throw failed_constructor ();
102 //cerr << "SMF Source name: " << _name << endl;
104 assert(_name.find("/") == string::npos);
107 SMFSource::~SMFSource ()
110 unlink (_path.c_str());
115 SMFSource::removable () const
117 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
118 ((_flags & RemovableIfEmpty) && is_empty()));
122 SMFSource::init (string pathstr, bool must_exist)
126 if (!find (pathstr, must_exist, is_new)) {
127 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
131 if (is_new && must_exist) {
135 assert(_name.find("/") == string::npos);
142 //cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
144 assert(writable()); // FIXME;
146 _fd = fopen(path().c_str(), "r+");
148 // File already exists
150 fseek(_fd, _header_size - 4, 0);
151 uint32_t track_size_be = 0;
152 fread(&track_size_be, 4, 1, _fd);
153 _track_size = GUINT32_FROM_BE(track_size_be);
154 //cerr << "SMF - read track size " << _track_size << endl;
156 // We're making a new file
158 _fd = fopen(path().c_str(), "w+");
161 // Write a tentative header just to pad things out so writing happens in the right spot
162 set_timeline_position(0);
168 return (_fd == 0) ? -1 : 0;
172 SMFSource::seek_to_end()
174 fseek(_fd, -4, SEEK_END);
178 SMFSource::flush_header ()
180 // FIXME: write timeline position somehow?
182 //cerr << "SMF Flushing header\n";
186 const uint16_t type = GUINT16_TO_BE(0); // SMF Type 0 (single track)
187 const uint16_t ntracks = GUINT16_TO_BE(1); // Number of tracks (always 1 for Type 0)
188 const uint16_t division = GUINT16_TO_BE(_ppqn); // Pulses per beat
191 memcpy(data, &type, 2);
192 memcpy(data+2, &ntracks, 2);
193 memcpy(data+4, &division, 2);
195 _fd = freopen(path().c_str(), "r+", _fd);
198 write_chunk("MThd", 6, data);
199 //if (_track_size > 0) {
200 write_chunk_header("MTrk", _track_size);
209 SMFSource::flush_footer()
219 SMFSource::write_footer()
221 //cerr << "SMF " << name() << " writing EOT at byte " << ftell(_fd) << endl;
224 char eot[3] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
225 fwrite(eot, 1, 3, _fd);
229 /** Returns the offset of the first event in the file with a time past @a start,
230 * relative to the start of the source.
232 * Returns -1 if not found.
236 SMFSource::find_first_event_after(nframes_t start)
238 // FIXME: obviously this is slooow
240 fseek(_fd, _header_size, 0);
242 while ( ! feof(_fd) ) {
243 const uint32_t delta_time = read_var_len();
245 if (delta_time > start)
253 /** Read an event from the current position in file.
255 * File position MUST be at the beginning of a delta time, or this will die very messily.
256 * ev.buffer must be of size ev.size, and large enough for the event. The returned event
257 * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
258 * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
260 * \a size should be the capacity of \a buf. If it is not large enough, \a buf will
261 * be freed and a new buffer allocated in its place, the size of which will be placed
264 * Returns event length (including status byte) on success, 0 if event was
265 * skipped (eg a meta event), or -1 on EOF (or end of track).
268 SMFSource::read_event(uint32_t* delta_t, uint32_t* size, Byte** buf) const
278 *delta_t = read_var_len();
281 const int status = fgetc(_fd);
282 assert(status != EOF); // FIXME die gracefully
284 //printf("Status @ %X = %X\n", (unsigned)ftell(_fd) - 1, status);
286 if (status == 0xFF) {
288 const int type = fgetc(_fd);
289 if ((unsigned char)type == 0x2F) {
290 //cerr << _name << " hit EOT" << endl;
298 const int event_size = midi_event_size((unsigned char)status) + 1;
299 if (event_size <= 0) {
304 // Make sure we have enough scratch buffer
305 if (*size < (unsigned)event_size)
306 *buf = (Byte*)realloc(*buf, event_size);
310 /*if (ev.buffer == NULL)
311 ev.buffer = (Byte*)malloc(sizeof(Byte) * ev.size);*/
313 (*buf)[0] = (unsigned char)status;
315 fread((*buf) + 1, 1, *size - 1, _fd);
317 /*printf("%s read event: delta = %u, size = %u, data = ", _name.c_str(), *delta_t, *size);
318 for (size_t i=0; i < *size; ++i) {
319 printf("%X ", (*buf)[i]);
326 /** All stamps in audio frames */
328 SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset) const
330 //cerr << "SMF - read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
332 // 64 bits ought to be enough for anybody
333 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
335 _read_data_count = 0;
337 // Output parameters for read_event (which will allocate scratch in buffer as needed)
338 uint32_t ev_delta_t = 0;
339 uint32_t ev_size = 0;
342 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
344 // FIXME: don't seek to start and search every read (brutal!)
345 fseek(_fd, _header_size, 0);
347 // FIXME: assumes tempo never changes after start
348 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
349 _session.engine().frame_rate());
351 const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * _ppqn);
354 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
355 if (ret == -1) { // EOF
356 //cerr << "SMF - EOF\n";
360 if (ret == 0) { // meta-event (skipped)
361 //cerr << "SMF - META\n";
362 time += ev_delta_t; // just accumulate delta time and ignore event
366 time += ev_delta_t; // accumulate delta time
368 if (time >= start_ticks) {
369 const nframes_t ev_frame_time = (nframes_t)(
370 ((time / (double)_ppqn) * frames_per_beat)) + stamp_offset;
372 if (ev_frame_time <= start + cnt)
373 dst.write(ev_frame_time, ev_size, ev_buffer);
378 _read_data_count += ev_size;
380 if (ev_size > scratch_size)
381 scratch_size = ev_size;
383 ev_size = scratch_size; // minimize realloc in read_event
389 /** All stamps in audio frames */
391 SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
393 _write_data_count = 0;
398 size_t buf_capacity = 4;
399 Byte* buf = (Byte*)malloc(buf_capacity);
401 if (_model && ! _model->currently_writing())
402 _model->start_write();
405 bool ret = src.full_peek(sizeof(double), (Byte*)&time);
406 if (!ret || time > _length + cnt)
409 ret = src.read_prefix(&time, &size);
413 if (size > buf_capacity) {
415 buf = (Byte*)realloc(buf, size);
418 ret = src.read_contents(size, buf);
420 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
424 assert(time >= _timeline_position);
425 time -= _timeline_position;
426 assert(time >= _last_ev_time);
428 const MidiEvent ev(time, size, buf);
429 append_event_unlocked(MidiEvent(ev));
438 const nframes_t oldlen = _length;
439 update_length(oldlen, cnt);
441 ViewDataRangeReady (oldlen, cnt); /* EMIT SIGNAL */
448 SMFSource::append_event_unlocked(const MidiEvent& ev)
450 /*printf("SMF - writing event, time = %lf, size = %u, data = ", ev.time(), ev.size());
451 for (size_t i=0; i < ev.size(); ++i) {
452 printf("%X ", ev.buffer()[i]);
456 assert(ev.time() >= _last_ev_time);
458 // FIXME: assumes tempo never changes after start
459 const double frames_per_beat = _session.tempo_map().tempo_at
460 (_timeline_position).frames_per_beat(_session.engine().frame_rate());
462 const uint32_t delta_time = (uint32_t)((ev.time() - _last_ev_time) / frames_per_beat * _ppqn);
464 const size_t stamp_size = write_var_len(delta_time);
465 fwrite(ev.buffer(), 1, ev.size(), _fd);
467 _track_size += stamp_size + ev.size();
468 _write_data_count += ev.size();
470 _last_ev_time = ev.time();
475 SMFSource::get_state ()
477 XMLNode& root (MidiSource::get_state());
479 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
480 root.add_property ("flags", buf);
485 SMFSource::set_state (const XMLNode& node)
487 const XMLProperty* prop;
489 if (MidiSource::set_state (node)) {
493 if ((prop = node.property (X_("flags"))) != 0) {
496 sscanf (prop->value().c_str(), "0x%x", &ival);
497 _flags = Flag (ival);
505 assert(_name.find("/") == string::npos);
511 SMFSource::mark_for_remove ()
516 _flags = Flag (_flags | RemoveAtDestroy);
520 SMFSource::mark_streaming_write_completed ()
522 MidiSource::mark_streaming_write_completed();
532 Glib::Mutex::Lock lm (_lock);
535 next_peak_clear_should_notify = true;
537 if (_peaks_built || pending_peak_builds.empty()) {
539 PeaksReady (); /* EMIT SIGNAL */
545 SMFSource::mark_take (string id)
553 SMFSource::move_to_trash (const string trash_dir_name)
561 /* don't move the file across filesystems, just
562 stick it in the 'trash_dir_name' directory
563 on whichever filesystem it was already on.
566 newpath = Glib::path_get_dirname (_path);
567 newpath = Glib::path_get_dirname (newpath);
570 newpath += trash_dir_name;
572 newpath += Glib::path_get_basename (_path);
574 if (access (newpath.c_str(), F_OK) == 0) {
576 /* the new path already exists, try versioning */
578 char buf[PATH_MAX+1];
582 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
585 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
586 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
590 if (version == 999) {
591 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
600 /* it doesn't exist, or we can't read it or something */
604 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
605 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
606 _path, newpath, strerror (errno))
611 if (::unlink (peakpath.c_str()) != 0) {
612 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
613 peakpath, _path, strerror (errno))
615 /* try to back out */
616 rename (newpath.c_str(), _path.c_str());
623 /* file can not be removed twice, since the operation is not idempotent */
625 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
630 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
632 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
634 string::size_type pos;
639 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
641 if ((pos = pathstr.find_last_of (':')) == string::npos) {
644 pathstr = pathstr.substr (0, pos);
647 if (pathstr[0] != '/') {
649 /* non-absolute pathname: find pathstr in search path */
656 if (_search_path.length() == 0) {
657 PBD::error << _("FileSource: search path not set") << endmsg;
661 split (_search_path, dirs, ':');
665 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
668 if (fullpath[fullpath.length()-1] != '/') {
673 if (access (fullpath.c_str(), R_OK) == 0) {
681 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
684 } else if (cnt == 0) {
687 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
700 /* external files and/or very very old style sessions include full paths */
703 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
705 if (access (_path.c_str(), R_OK) != 0) {
707 /* file does not exist or we cannot read it */
710 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
714 if (errno != ENOENT) {
715 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
737 SMFSource::set_search_path (string p)
744 SMFSource::set_allow_remove_if_empty (bool yn)
747 _allow_remove_if_empty = yn;
752 SMFSource::set_source_name (string newname, bool destructive)
754 //Glib::Mutex::Lock lm (_lock); FIXME
755 string oldpath = _path;
756 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
758 if (newpath.empty()) {
759 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
763 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
764 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
768 _name = Glib::path_get_basename (newpath);
771 return 0;//rename_peakfile (peak_path (_path));
775 SMFSource::is_empty () const
777 bool ret = (_track_size > 4);
779 //cerr << name() << " IS EMPTY: " << ret << endl;
786 SMFSource::write_chunk_header(char id[4], uint32_t length)
788 const uint32_t length_be = GUINT32_TO_BE(length);
790 fwrite(id, 1, 4, _fd);
791 fwrite(&length_be, 4, 1, _fd);
795 SMFSource::write_chunk(char id[4], uint32_t length, void* data)
797 write_chunk_header(id, length);
799 fwrite(data, 1, length, _fd);
802 /** Returns the size (in bytes) of the value written. */
804 SMFSource::write_var_len(uint32_t value)
808 uint32_t buffer = value & 0x7F;
810 while ( (value >>= 7) ) {
812 buffer |= ((value & 0x7F) | 0x80);
816 //printf("Writing var len byte %X\n", (unsigned char)buffer);
829 SMFSource::read_var_len() const
836 if ( (value = getc(_fd)) & 0x80 ) {
840 value = (value << 7) + ((c = getc(_fd)) & 0x7F);
848 SMFSource::load_model(bool lock, bool force_reload)
854 Glib::Mutex::Lock lm (_lock);
856 if (_model && !force_reload && !_model->empty()) {
857 //cerr << _name << " NOT reloading model " << _model.get() << " (" << _model->n_notes()
858 // << " notes)" << endl;
863 _model = boost::shared_ptr<MidiModel>(new MidiModel(_session));
864 cerr << _name << " loaded new model " << _model.get() << endl;
866 cerr << _name << " reloading model " << _model.get()
867 << " (" << _model->n_notes() << " notes)" <<endl;
871 _model->start_write();
873 fseek(_fd, _header_size, 0);
875 uint64_t time = 0; /* in SMF ticks */
878 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
880 // FIXME: assumes tempo never changes after start
881 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
882 _session.engine().frame_rate());
884 uint32_t delta_t = 0;
886 while ((ret = read_event(&delta_t, &ev.size(), &ev.buffer())) >= 0) {
890 if (ret > 0) { // didn't skip (meta) event
891 // make ev.time absolute time in frames
892 ev.time() = (double)time * frames_per_beat / (double)_ppqn;
897 if (ev.size() > scratch_size)
898 scratch_size = ev.size();
900 ev.size() = scratch_size;
903 _model->end_write(false);
910 SMFSource::destroy_model()
912 //cerr << _name << " destroying model " << _model.get() << endl;