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)
58 , _timeline_position (0)
61 , _track_size(4) // 4 bytes for the ever-present EOT event
64 /* constructor used for new internal-to-session files. file cannot exist */
66 if (init (path, false)) {
67 throw failed_constructor ();
71 throw failed_constructor ();
74 assert(_name.find("/") == string::npos);
77 SMFSource::SMFSource (Session& s, const XMLNode& node)
78 : MidiSource (s, node)
80 , _flags (Flag (Writable|CanRename))
81 , _allow_remove_if_empty(true)
82 , _timeline_position (0)
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 assert(_name.find("/") == string::npos);
105 SMFSource::~SMFSource ()
108 unlink (_path.c_str());
113 SMFSource::removable () const
115 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
116 ((_flags & RemovableIfEmpty) && is_empty (_path)));
120 SMFSource::init (string pathstr, bool must_exist)
124 if (!find (pathstr, must_exist, is_new)) {
125 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
129 if (is_new && must_exist) {
133 assert(_name.find("/") == string::npos);
140 cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
142 assert(writable()); // FIXME;
144 _fd = fopen(path().c_str(), "r+");
146 // File already exists
148 fseek(_fd, _header_size - 4, 0);
149 uint32_t track_size_be = 0;
150 fread(&track_size_be, 4, 1, _fd);
151 _track_size = GUINT32_FROM_BE(track_size_be);
152 cerr << "SMF - read track size " << _track_size << endl;
154 // We're making a new file
156 _fd = fopen(path().c_str(), "w+");
159 // write a tentative header just to pad things out so writing happens in the right spot
161 // FIXME: write the footer here too so it's a valid SMF (screw up writing ATM though)
164 return (_fd == 0) ? -1 : 0;
168 SMFSource::update_header (nframes_t when, struct tm&, time_t)
170 _timeline_position = when;
171 return flush_header();
175 SMFSource::flush_header ()
177 // FIXME: write timeline position somehow?
179 cerr << "SMF Flushing header\n";
183 const uint16_t type = GUINT16_TO_BE(0); // SMF Type 0 (single track)
184 const uint16_t ntracks = GUINT16_TO_BE(1); // Number of tracks (always 1 for Type 0)
185 const uint16_t division = GUINT16_TO_BE(_ppqn); // Pulses per beat
188 memcpy(data, &type, 2);
189 memcpy(data+2, &ntracks, 2);
190 memcpy(data+4, &division, 2);
192 _fd = freopen(path().c_str(), "r+", _fd);
195 write_chunk("MThd", 6, data);
196 //if (_track_size > 0) {
197 write_chunk_header("MTrk", _track_size);
206 SMFSource::flush_footer()
208 cerr << "SMF - Writing EOT\n";
210 fseek(_fd, 0, SEEK_END);
211 write_var_len(1); // whatever...
212 char eot[4] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
213 fwrite(eot, 1, 4, _fd);
218 /** Returns the offset of the first event in the file with a time past @a start,
219 * relative to the start of the source.
221 * Returns -1 if not found.
225 SMFSource::find_first_event_after(nframes_t start)
227 // FIXME: obviously this is slooow
229 fseek(_fd, _header_size, 0);
231 while ( ! feof(_fd) ) {
232 const uint32_t delta_time = read_var_len();
234 if (delta_time > start)
242 /** Read an event from the current position in file.
244 * File position MUST be at the beginning of a delta time, or this will die very messily.
245 * ev.buffer must be of size ev.size, and large enough for the event. The returned event
246 * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
247 * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
249 * Returns event length (including status byte) on success, 0 if event was
250 * skipped (eg a meta event), or -1 on EOF (or end of track).
253 SMFSource::read_event(jack_midi_event_t& ev) const
255 // - 4 is for the EOT event, which we don't actually want to read
256 //if (feof(_fd) || ftell(_fd) >= _header_size + _track_size - 4) {
261 uint32_t delta_time = read_var_len();
263 int status = fgetc(_fd);
264 assert(status != EOF); // FIXME die gracefully
265 if (status == 0xFF) {
267 int type = fgetc(_fd);
268 if ((unsigned char)type == 0x2F) {
269 //cerr << "SMF - hit EOT" << endl;
270 return -1; // we hit the logical EOF anyway...
273 ev.time = delta_time; // this is needed regardless
278 ev.time = delta_time;
279 ev.size = midi_event_size((unsigned char)status) + 1;
281 if (ev.buffer == NULL)
282 ev.buffer = (Byte*)malloc(sizeof(Byte) * ev.size);
284 ev.buffer[0] = (unsigned char)status;
285 fread(ev.buffer+1, 1, ev.size - 1, _fd);
287 /*printf("SMF - read event, delta = %u, size = %zu, data = ",
288 delta_time, ev.size);
289 for (size_t i=0; i < ev.size; ++i) {
290 printf("%X ", ev.buffer[i]);
297 /** All stamps in audio frames */
299 SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset) const
301 //cerr << "SMF - read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
303 // 64 bits ought to be enough for anybody
304 uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
306 _read_data_count = 0;
309 unsigned char ev_buf[MidiBuffer::max_event_size()];
310 jack_midi_event_t ev; // time in SMF ticks
312 ev.size = MidiBuffer::max_event_size();
315 // FIXME: don't seek to start every read
316 fseek(_fd, _header_size, 0);
318 // FIXME: assumes tempo never changes after start
319 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
320 _session.engine().frame_rate());
322 uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * _ppqn);
325 int ret = read_event(ev);
326 if (ret == -1) { // EOF
327 //cerr << "SMF - EOF\n";
331 if (ret == 0) { // meta-event (skipped)
332 //cerr << "SMF - META\n";
333 time += ev.time; // just accumulate delta time and ignore event
337 time += ev.time; // accumulate delta time
338 ev.time = time; // set ev.time to actual time (relative to source start)
340 if (ev.time >= start_ticks) {
341 if (ev.time < start_ticks + (cnt / frames_per_beat)) {
344 ev.time = (nframes_t)(((ev.time / (double)_ppqn) * frames_per_beat)) + stamp_offset;
345 // write event time in absolute frames
346 dst.write(ev.time, ev.size, ev.buffer);
350 _read_data_count += ev.size;
356 /** All stamps in audio frames */
358 SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
360 _write_data_count = 0;
362 boost::shared_ptr<MidiBuffer> buf_ptr(new MidiBuffer(1024)); // FIXME: size?
363 MidiBuffer& buf = *buf_ptr.get();
364 src.read(buf, /*_length*/0, _length + cnt); // FIXME?
366 fseek(_fd, 0, SEEK_END);
368 // FIXME: assumes tempo never changes after start
369 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
370 _session.engine().frame_rate());
372 for (size_t i=0; i < buf.size(); ++i) {
373 MidiEvent& ev = buf[i];
374 assert(ev.time >= _timeline_position);
375 ev.time -= _timeline_position;
376 assert(ev.time >= _last_ev_time);
377 const uint32_t delta_time = (uint32_t)((ev.time - _last_ev_time) / frames_per_beat * _ppqn);
379 /*printf("SMF - writing event, delta = %u, size = %zu, data = ",
380 delta_time, ev.size);
381 for (size_t i=0; i < ev.size; ++i) {
382 printf("%X ", ev.buffer[i]);
386 size_t stamp_size = write_var_len(delta_time);
387 fwrite(ev.buffer, 1, ev.size, _fd);
389 _track_size += stamp_size + ev.size;
390 _write_data_count += ev.size;
392 _last_ev_time = ev.time;
397 const nframes_t oldlen = _length;
398 update_length(oldlen, cnt);
402 ViewDataRangeReady (buf_ptr, oldlen, cnt); /* EMIT SIGNAL */
408 SMFSource::get_state ()
410 XMLNode& root (MidiSource::get_state());
412 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
413 root.add_property ("flags", buf);
418 SMFSource::set_state (const XMLNode& node)
420 const XMLProperty* prop;
422 if (MidiSource::set_state (node)) {
426 if ((prop = node.property (X_("flags"))) != 0) {
429 sscanf (prop->value().c_str(), "0x%x", &ival);
430 _flags = Flag (ival);
438 assert(_name.find("/") == string::npos);
444 SMFSource::mark_for_remove ()
449 _flags = Flag (_flags | RemoveAtDestroy);
453 SMFSource::mark_streaming_write_completed ()
462 Glib::Mutex::Lock lm (_lock);
465 next_peak_clear_should_notify = true;
467 if (_peaks_built || pending_peak_builds.empty()) {
469 PeaksReady (); /* EMIT SIGNAL */
475 SMFSource::mark_take (string id)
483 SMFSource::move_to_trash (const string trash_dir_name)
491 /* don't move the file across filesystems, just
492 stick it in the 'trash_dir_name' directory
493 on whichever filesystem it was already on.
496 newpath = Glib::path_get_dirname (_path);
497 newpath = Glib::path_get_dirname (newpath);
500 newpath += trash_dir_name;
502 newpath += Glib::path_get_basename (_path);
504 if (access (newpath.c_str(), F_OK) == 0) {
506 /* the new path already exists, try versioning */
508 char buf[PATH_MAX+1];
512 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
515 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
516 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
520 if (version == 999) {
521 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
530 /* it doesn't exist, or we can't read it or something */
534 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
535 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
536 _path, newpath, strerror (errno))
541 if (::unlink (peakpath.c_str()) != 0) {
542 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
543 peakpath, _path, strerror (errno))
545 /* try to back out */
546 rename (newpath.c_str(), _path.c_str());
553 /* file can not be removed twice, since the operation is not idempotent */
555 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
560 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
562 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
564 string::size_type pos;
569 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
571 if ((pos = pathstr.find_last_of (':')) == string::npos) {
574 pathstr = pathstr.substr (0, pos);
577 if (pathstr[0] != '/') {
579 /* non-absolute pathname: find pathstr in search path */
586 if (_search_path.length() == 0) {
587 PBD::error << _("FileSource: search path not set") << endmsg;
591 split (_search_path, dirs, ':');
595 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
598 if (fullpath[fullpath.length()-1] != '/') {
603 if (access (fullpath.c_str(), R_OK) == 0) {
611 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
614 } else if (cnt == 0) {
617 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
630 /* external files and/or very very old style sessions include full paths */
633 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
635 if (access (_path.c_str(), R_OK) != 0) {
637 /* file does not exist or we cannot read it */
640 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
644 if (errno != ENOENT) {
645 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
667 SMFSource::set_search_path (string p)
674 SMFSource::set_allow_remove_if_empty (bool yn)
677 _allow_remove_if_empty = yn;
682 SMFSource::set_name (string newname, bool destructive)
684 //Glib::Mutex::Lock lm (_lock); FIXME
685 string oldpath = _path;
686 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
688 if (newpath.empty()) {
689 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
693 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
694 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
698 _name = Glib::path_get_basename (newpath);
701 return 0;//rename_peakfile (peak_path (_path));
705 SMFSource::is_empty (string path)
714 SMFSource::write_chunk_header(char id[4], uint32_t length)
716 const uint32_t length_be = GUINT32_TO_BE(length);
718 fwrite(id, 1, 4, _fd);
719 fwrite(&length_be, 4, 1, _fd);
723 SMFSource::write_chunk(char id[4], uint32_t length, void* data)
725 write_chunk_header(id, length);
727 fwrite(data, 1, length, _fd);
730 /** Returns the size (in bytes) of the value written. */
732 SMFSource::write_var_len(uint32_t value)
736 uint32_t buffer = value & 0x7F;
738 while ( (value >>= 7) ) {
740 buffer |= ((value & 0x7F) | 0x80);
744 //printf("Writing var len byte %X\n", (unsigned char)buffer);
757 SMFSource::read_var_len() const
761 //int offset = ftell(_fd);
762 //cerr << "SMF - reading var len at " << offset << endl;
767 if ( (value = getc(_fd)) & 0x80 ) {
771 value = (value << 7) + ((c = getc(_fd)) & 0x7F);
779 SMFSource::load_model(bool lock)
782 Glib::Mutex::Lock lm (_lock);
785 _model = new MidiModel();
787 fseek(_fd, _header_size, 0);
789 uint64_t time = 0; /* in SMF ticks */
790 jack_midi_event_t ev;
795 // FIXME: assumes tempo never changes after start
796 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
797 _session.engine().frame_rate());
800 while ((ret = read_event(ev)) >= 0) {
803 const double ev_time = (double)(time * frames_per_beat / (double)_ppqn); // in frames
805 if (ret > 0) { // didn't skip (meta) event
806 //cerr << "ADDING EVENT TO MODEL: " << ev.time << endl;
807 _model->append(ev_time, ev.size, ev.buffer);
814 SMFSource::destroy_model()