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>
41 #include <ardour/smf_reader.h>
45 using namespace ARDOUR;
47 string SMFSource::_search_path;
49 /*sigc::signal<void,struct tm*, time_t> SMFSource::HeaderPositionOffsetChanged;
50 bool SMFSource::header_position_negative;
51 uint64_t SMFSource::header_position_offset;
54 SMFSource::SMFSource (Session& s, std::string path, Flag flags)
55 : 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)
80 , _flags (Flag (Writable|CanRename))
81 , _allow_remove_if_empty(true)
84 , _track_size(4) // 4 bytes for the ever-present EOT event
87 /* constructor used for existing internal-to-session files. file must exist */
89 if (set_state (node)) {
90 throw failed_constructor ();
93 if (init (_name, true)) {
94 throw failed_constructor ();
98 throw failed_constructor ();
101 assert(_name.find("/") == string::npos);
104 SMFSource::~SMFSource ()
107 unlink (_path.c_str());
112 SMFSource::removable () const
114 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
115 ((_flags & RemovableIfEmpty) && is_empty()));
119 SMFSource::init (string pathstr, bool must_exist)
123 if (!find (pathstr, must_exist, is_new)) {
124 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
128 if (is_new && must_exist) {
132 assert(_name.find("/") == string::npos);
136 /** Attempt to open the SMF file for reading and writing.
138 * Currently SMFSource is always read/write.
140 * \return 0 on success
141 * -1 if the file can not be opened for reading,
142 * -2 if the file can not be opened for writing
147 //cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
149 assert(writable()); // FIXME;
151 _fd = fopen(path().c_str(), "r+");
153 // File already exists
155 fseek(_fd, _header_size - 4, 0);
156 uint32_t track_size_be = 0;
157 fread(&track_size_be, 4, 1, _fd);
158 _track_size = GUINT32_FROM_BE(track_size_be);
159 //cerr << "SMF - read track size " << _track_size << endl;
161 // We're making a new file
163 _fd = fopen(path().c_str(), "w+");
165 cerr << "ERROR: Can not open SMF file " << path() << " for writing: " <<
166 strerror(errno) << endl;
171 // Write a tentative header just to pad things out so writing happens in the right spot
177 return (_fd == 0) ? -1 : 0;
192 SMFSource::seek_to_end()
194 fseek(_fd, -4, SEEK_END);
198 SMFSource::flush_header()
200 // FIXME: write timeline position somehow?
202 //cerr << "SMF Flushing header\n";
206 const uint16_t type = GUINT16_TO_BE(0); // SMF Type 0 (single track)
207 const uint16_t ntracks = GUINT16_TO_BE(1); // Number of tracks (always 1 for Type 0)
208 const uint16_t division = GUINT16_TO_BE(_ppqn); // Pulses per quarter note (beat)
211 memcpy(data, &type, 2);
212 memcpy(data+2, &ntracks, 2);
213 memcpy(data+4, &division, 2);
215 _fd = freopen(path().c_str(), "r+", _fd);
217 fseek(_fd, 0, SEEK_SET);
218 write_chunk("MThd", 6, data);
219 write_chunk_header("MTrk", _track_size);
227 SMFSource::flush_footer()
229 fseek(_fd, 0, SEEK_END);
236 SMFSource::write_footer()
239 char eot[3] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
240 fwrite(eot, 1, 3, _fd);
244 /** Returns the offset of the first event in the file with a time past @a start,
245 * relative to the start of the source.
247 * Returns -1 if not found.
251 SMFSource::find_first_event_after(nframes_t start)
253 // FIXME: obviously this is slooow
255 fseek(_fd, _header_size, 0);
257 while ( ! feof(_fd) ) {
258 const uint32_t delta_time = read_var_len();
260 if (delta_time > start)
268 /** Read an event from the current position in file.
270 * File position MUST be at the beginning of a delta time, or this will die very messily.
271 * ev.buffer must be of size ev.size, and large enough for the event. The returned event
272 * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
273 * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
275 * \a size should be the capacity of \a buf. If it is not large enough, \a buf will
276 * be freed and a new buffer allocated in its place, the size of which will be placed
279 * Returns event length (including status byte) on success, 0 if event was
280 * skipped (eg a meta event), or -1 on EOF (or end of track).
283 SMFSource::read_event(uint32_t* delta_t, uint32_t* size, Byte** buf) const
294 *delta_t = SMFReader::read_var_len(_fd);
296 return -1; // Premature EOF
300 return -1; // Premature EOF
303 const int status = fgetc(_fd);
306 return -1; // Premature EOF
309 //printf("Status @ %X = %X\n", (unsigned)ftell(_fd) - 1, status);
311 if (status == 0xFF) {
313 return -1; // Premature EOF
315 const int type = fgetc(_fd);
316 if ((unsigned char)type == 0x2F) {
317 return -1; // hit end of track
324 const int event_size = midi_event_size((unsigned char)status) + 1;
325 if (event_size <= 0) {
330 // Make sure we have enough scratch buffer
331 if (*size < (unsigned)event_size)
332 *buf = (Byte*)realloc(*buf, event_size);
336 /*if (ev.buffer == NULL)
337 ev.buffer = (Byte*)malloc(sizeof(Byte) * ev.size);*/
339 (*buf)[0] = (unsigned char)status;
341 fread((*buf) + 1, 1, *size - 1, _fd);
343 /*printf("%s read event: delta = %u, size = %u, data = ", _name.c_str(), *delta_t, *size);
344 for (size_t i=0; i < *size; ++i) {
345 printf("%X ", (*buf)[i]);
352 /** All stamps in audio frames */
354 SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
356 cerr << "SMF read_unlocked " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
358 // 64 bits ought to be enough for anybody
359 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
361 _read_data_count = 0;
363 // Output parameters for read_event (which will allocate scratch in buffer as needed)
364 uint32_t ev_delta_t = 0;
365 uint32_t ev_size = 0;
368 size_t scratch_size = 0; // keep track of scratch to minimize reallocs
370 // FIXME: don't seek to start and search every read (brutal!)
371 fseek(_fd, _header_size, SEEK_SET);
373 // FIXME: assumes tempo never changes after start
374 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
375 _session.engine().frame_rate(),
376 _session.tempo_map().meter_at(_timeline_position));
378 const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * _ppqn);
381 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
382 if (ret == -1) { // EOF
383 //cerr << "SMF - EOF\n";
387 if (ret == 0) { // meta-event (skipped)
388 //cerr << "SMF - META\n";
389 time += ev_delta_t; // just accumulate delta time and ignore event
393 time += ev_delta_t; // accumulate delta time
395 if (time >= start_ticks) {
396 const nframes_t ev_frame_time = (nframes_t)(
397 ((time / (double)_ppqn) * frames_per_beat)) + stamp_offset;
399 if (ev_frame_time <= start + cnt)
400 dst.write(ev_frame_time - negative_stamp_offset, ev_size, ev_buffer);
405 _read_data_count += ev_size;
407 if (ev_size > scratch_size)
408 scratch_size = ev_size;
410 ev_size = scratch_size; // minimize realloc in read_event
416 /** All stamps in audio frames */
418 SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
420 _write_data_count = 0;
425 size_t buf_capacity = 4;
426 Byte* buf = (Byte*)malloc(buf_capacity);
428 if (_model && ! _model->writing())
429 _model->start_write();
432 bool ret = src.full_peek(sizeof(double), (Byte*)&time);
433 if (!ret || time - _timeline_position > _length + cnt)
436 ret = src.read_prefix(&time, &size);
440 if (size > buf_capacity) {
442 buf = (Byte*)realloc(buf, size);
445 ret = src.read_contents(size, buf);
447 cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
451 assert(time >= _timeline_position);
452 time -= _timeline_position;
454 const MIDI::Event ev(time, size, buf);
455 append_event_unlocked(Frames, ev);
464 const nframes_t oldlen = _length;
465 update_length(oldlen, cnt);
467 ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
474 SMFSource::append_event_unlocked(EventTimeUnit unit, const MIDI::Event& ev)
476 /*printf("%s - append chan = %u, time = %lf, size = %u, data = ",
477 name().c_str(), (unsigned)ev.channel(), ev.time(), ev.size());
478 for (size_t i=0; i < ev.size(); ++i) {
479 printf("%X ", ev.buffer()[i]);
483 assert(ev.time() >= 0);
484 assert(ev.time() >= _last_ev_time);
486 uint32_t delta_time = 0;
488 if (unit == Frames) {
489 // FIXME: assumes tempo never changes after start
490 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
491 _session.engine().frame_rate(),
492 _session.tempo_map().meter_at(_timeline_position));
494 delta_time = (uint32_t)((ev.time() - _last_ev_time) / frames_per_beat * _ppqn);
496 assert(unit == Beats);
497 delta_time = (uint32_t)((ev.time() - _last_ev_time) * _ppqn);
501 const size_t stamp_size = write_var_len(delta_time);
502 fwrite(ev.buffer(), 1, ev.size(), _fd);
504 _track_size += stamp_size + ev.size();
505 _write_data_count += ev.size();
507 _last_ev_time = ev.time();
512 SMFSource::get_state ()
514 XMLNode& root (MidiSource::get_state());
516 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
517 root.add_property ("flags", buf);
522 SMFSource::set_state (const XMLNode& node)
524 const XMLProperty* prop;
526 if (MidiSource::set_state (node)) {
530 if ((prop = node.property (X_("flags"))) != 0) {
533 sscanf (prop->value().c_str(), "0x%x", &ival);
534 _flags = Flag (ival);
542 assert(_name.find("/") == string::npos);
548 SMFSource::mark_for_remove ()
553 _flags = Flag (_flags | RemoveAtDestroy);
557 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
559 MidiSource::mark_streaming_midi_write_started (mode, start_frame);
561 fseek(_fd, _header_size, 0);
565 SMFSource::mark_streaming_write_completed ()
567 MidiSource::mark_streaming_write_completed();
573 _model->set_edited(false);
579 SMFSource::mark_take (string id)
587 SMFSource::move_to_trash (const string trash_dir_name)
595 /* don't move the file across filesystems, just
596 stick it in the 'trash_dir_name' directory
597 on whichever filesystem it was already on.
600 newpath = Glib::path_get_dirname (_path);
601 newpath = Glib::path_get_dirname (newpath);
604 newpath += trash_dir_name;
606 newpath += Glib::path_get_basename (_path);
608 if (access (newpath.c_str(), F_OK) == 0) {
610 /* the new path already exists, try versioning */
612 char buf[PATH_MAX+1];
616 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
619 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
620 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
624 if (version == 999) {
625 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
634 /* it doesn't exist, or we can't read it or something */
638 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
639 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
640 _path, newpath, strerror (errno))
645 if (::unlink (peakpath.c_str()) != 0) {
646 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
647 peakpath, _path, strerror (errno))
649 /* try to back out */
650 rename (newpath.c_str(), _path.c_str());
657 /* file can not be removed twice, since the operation is not idempotent */
659 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
665 SMFSource::safe_file_extension(const Glib::ustring& file)
667 return (file.rfind(".mid") != Glib::ustring::npos);
670 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
672 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
674 string::size_type pos;
679 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
681 if ((pos = pathstr.find_last_of (':')) == string::npos) {
684 pathstr = pathstr.substr (0, pos);
687 if (pathstr[0] != '/') {
689 /* non-absolute pathname: find pathstr in search path */
696 if (_search_path.length() == 0) {
697 PBD::error << _("FileSource: search path not set") << endmsg;
701 split (_search_path, dirs, ':');
705 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
708 if (fullpath[fullpath.length()-1] != '/') {
713 if (access (fullpath.c_str(), R_OK) == 0) {
721 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
724 } else if (cnt == 0) {
727 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
740 /* external files and/or very very old style sessions include full paths */
743 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
745 if (access (_path.c_str(), R_OK) != 0) {
747 /* file does not exist or we cannot read it */
750 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
754 if (errno != ENOENT) {
755 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
777 SMFSource::set_search_path (string p)
784 SMFSource::set_allow_remove_if_empty (bool yn)
787 _allow_remove_if_empty = yn;
792 SMFSource::set_source_name (string newname, bool destructive)
794 //Glib::Mutex::Lock lm (_lock); FIXME
795 string oldpath = _path;
796 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
798 if (newpath.empty()) {
799 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
803 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
804 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
808 _name = Glib::path_get_basename (newpath);
811 return 0;//rename_peakfile (peak_path (_path));
815 SMFSource::is_empty () const
817 bool ret = (_track_size > 4);
819 //cerr << name() << " IS EMPTY: " << ret << endl;
826 SMFSource::write_chunk_header(const char id[4], uint32_t length)
828 const uint32_t length_be = GUINT32_TO_BE(length);
830 fwrite(id, 1, 4, _fd);
831 fwrite(&length_be, 4, 1, _fd);
835 SMFSource::write_chunk(const char id[4], uint32_t length, void* data)
837 write_chunk_header(id, length);
839 fwrite(data, 1, length, _fd);
842 /** Returns the size (in bytes) of the value written. */
844 SMFSource::write_var_len(uint32_t value)
848 uint32_t buffer = value & 0x7F;
850 while ( (value >>= 7) ) {
852 buffer |= ((value & 0x7F) | 0x80);
856 //printf("Writing var len byte %X\n", (unsigned char)buffer);
869 SMFSource::load_model(bool lock, bool force_reload)
875 Glib::Mutex::Lock lm (_lock);
877 if (_model && !force_reload && !_model->empty())
881 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
882 cerr << _name << " loaded new model " << _model.get() << endl;
884 cerr << _name << " reloading model " << _model.get()
885 << " (" << _model->n_notes() << " notes)" <<endl;
889 _model->start_write();
891 fseek(_fd, _header_size, 0);
893 uint64_t time = 0; /* in SMF ticks */
896 size_t scratch_size = 0; // keep track of scratch and minimize reallocs
898 // FIXME: assumes tempo never changes after start
899 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
900 _session.engine().frame_rate(),
901 _session.tempo_map().meter_at(_timeline_position));
903 uint32_t delta_t = 0;
905 while ((ret = read_event(&delta_t, &ev.size(), &ev.buffer())) >= 0) {
909 if (ret > 0) { // didn't skip (meta) event
910 // make ev.time absolute time in frames
911 ev.time() = (double)time * frames_per_beat / (double)_ppqn;
916 if (ev.size() > scratch_size)
917 scratch_size = ev.size();
919 ev.size() = scratch_size;
922 _model->end_write(false);
923 _model->set_edited(false);
930 SMFSource::destroy_model()
932 //cerr << _name << " destroying model " << _model.get() << endl;