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>
42 using namespace ARDOUR;
44 string SMFSource::_search_path;
46 /*sigc::signal<void,struct tm*, time_t> SMFSource::HeaderPositionOffsetChanged;
47 bool SMFSource::header_position_negative;
48 uint64_t SMFSource::header_position_offset;
51 SMFSource::SMFSource (Session& s, std::string path, Flag flags)
52 : MidiSource (s, region_name_from_path(path, false))
54 , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
55 , _allow_remove_if_empty(true)
56 , _timeline_position (0)
59 , _track_size(4) // 4 bytes for the ever-present EOT event
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)
78 , _flags (Flag (Writable|CanRename))
79 , _allow_remove_if_empty(true)
80 , _timeline_position (0)
83 , _track_size(4) // 4 bytes for the ever-present EOT event
86 /* constructor used for existing internal-to-session files. file must exist */
88 if (set_state (node)) {
89 throw failed_constructor ();
92 if (init (_name, true)) {
93 throw failed_constructor ();
97 throw failed_constructor ();
100 assert(_name.find("/") == string::npos);
103 SMFSource::~SMFSource ()
106 unlink (_path.c_str());
111 SMFSource::removable () const
113 return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
114 ((_flags & RemovableIfEmpty) && is_empty (_path)));
118 SMFSource::init (string pathstr, bool must_exist)
122 if (!find (pathstr, must_exist, is_new)) {
123 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
127 if (is_new && must_exist) {
131 assert(_name.find("/") == string::npos);
138 cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
140 assert(writable()); // FIXME;
142 _fd = fopen(path().c_str(), "r+");
144 // File already exists
146 fseek(_fd, _header_size - 4, 0);
147 uint32_t track_size_be = 0;
148 fread(&track_size_be, 4, 1, _fd);
149 _track_size = GUINT32_FROM_BE(track_size_be);
150 cerr << "SMF - read track size " << _track_size;
152 // We're making a new file
154 _fd = fopen(path().c_str(), "w+");
157 // write a tentative header just to pad things out so writing happens in the right spot
159 // FIXME: write the footer here too so it's a valid SMF (screw up writing ATM though)
162 return (_fd == 0) ? -1 : 0;
166 SMFSource::update_header (jack_nframes_t when, struct tm&, time_t)
168 _timeline_position = when;
169 return flush_header();
173 SMFSource::flush_header ()
175 // FIXME: write timeline position somehow?
177 cerr << "SMF Flushing header\n";
181 const uint16_t type = GUINT16_TO_BE(0); // SMF Type 0 (single track)
182 const uint16_t ntracks = GUINT16_TO_BE(1); // Number of tracks (always 1 for Type 0)
183 const uint16_t division = GUINT16_TO_BE(1920); // FIXME FIXME FIXME PPQN
186 memcpy(data, &type, 2);
187 memcpy(data+2, &ntracks, 2);
188 memcpy(data+4, &division, 2);
190 _fd = freopen(path().c_str(), "r+", _fd);
193 write_chunk("MThd", 6, data);
194 //if (_track_size > 0) {
195 write_chunk_header("MTrk", _track_size);
204 SMFSource::flush_footer()
206 cerr << "SMF - Writing EOT\n";
208 fseek(_fd, 0, SEEK_END);
209 write_var_len(1); // whatever...
210 char eot[4] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
211 fwrite(eot, 1, 4, _fd);
216 /** Returns the offset of the first event in the file with a time past @a start,
217 * relative to the start of the source.
219 * Returns -1 if not found.
223 SMFSource::find_first_event_after(jack_nframes_t start)
225 // FIXME: obviously this is slooow
227 fseek(_fd, _header_size, 0);
229 while ( ! feof(_fd) ) {
230 const uint32_t delta_time = read_var_len();
232 if (delta_time > start)
240 /** Read an event from the current position in file.
242 * File position MUST be at the beginning of a delta time, or this will die very messily.
243 * ev.buffer must be of size ev.size, and large enough for the event. The returned event
244 * will have it's time field set to it's delta time (so it's the caller's responsibility
245 * to calculate a real time for the event).
247 * Returns event length (including status byte) on success, 0 if event was
248 * skipped (eg a meta event), or -1 on EOF (or end of track).
251 SMFSource::read_event(MidiEvent& ev) const
253 // - 4 is for the EOT event, which we don't actually want to read
254 //if (feof(_fd) || ftell(_fd) >= _header_size + _track_size - 4) {
259 uint32_t delta_time = read_var_len();
260 int status = fgetc(_fd);
261 assert(status != EOF); // FIXME die gracefully
262 if (status == 0xFF) {
264 int type = fgetc(_fd);
265 if ((unsigned char)type == 0x2F) {
266 //cerr << "SMF - hit EOT" << endl;
267 return -1; // we hit the logical EOF anyway...
270 ev.time = delta_time; // this is needed regardless
275 ev.buffer[0] = (unsigned char)status;
276 ev.size = midi_event_size(ev.buffer[0]) + 1;
277 fread(ev.buffer+1, 1, ev.size - 1, _fd);
278 ev.time = delta_time;
280 /*printf("SMF - read event, delta = %u, size = %zu, data = ",
281 delta_time, ev.size);
282 for (size_t i=0; i < ev.size; ++i) {
283 printf("%X ", ev.buffer[i]);
291 SMFSource::read_unlocked (MidiRingBuffer& dst, jack_nframes_t start, jack_nframes_t cnt, jack_nframes_t stamp_offset) const
293 //cerr << "SMF - read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
295 jack_nframes_t time = 0;
298 unsigned char ev_buf[MidiBuffer::max_event_size()];
301 ev.size = MidiBuffer::max_event_size();
304 // FIXME: it would be an impressive feat to actually make this any slower :)
306 fseek(_fd, _header_size, 0);
309 int ret = read_event(ev);
310 if (ret == -1) { // EOF
311 //cerr << "SMF - EOF\n";
315 if (ret == 0) { // meta-event (skipped)
316 //cerr << "SMF - META\n";
317 time += ev.time; // just accumulate delta time and ignore event
321 time += ev.time; // accumulate delta time
322 ev.time = time; // set ev.time to actual time (relative to source start)
324 if (ev.time >= start) {
325 if (ev.time > start + cnt) {
328 ev.time += stamp_offset;
338 SMFSource::write_unlocked (MidiRingBuffer& src, jack_nframes_t cnt)
340 //cerr << "SMF WRITE -- " << _length << "--" << cnt << endl;
342 MidiBuffer buf(1024); // FIXME: allocation, size?
343 src.read(buf, /*_length*/0, _length + cnt); // FIXME?
345 fseek(_fd, 0, SEEK_END);
347 // FIXME: start of source time?
349 for (size_t i=0; i < buf.size(); ++i) {
350 const MidiEvent& ev = buf[i];
351 assert(ev.time >= _timeline_position);
352 uint32_t delta_time = (ev.time - _timeline_position) - _last_ev_time;
354 /*printf("SMF - writing event, delta = %u, size = %zu, data = ",
355 delta_time, ev.size);
356 for (size_t i=0; i < ev.size; ++i) {
357 printf("%X ", ev.buffer[i]);
361 size_t stamp_size = write_var_len(delta_time);
362 fwrite(ev.buffer, 1, ev.size, _fd);
363 _last_ev_time += delta_time;
364 _track_size += stamp_size + ev.size;
369 if (buf.size() > 0) {
370 ViewDataRangeReady (_length, cnt); /* EMIT SIGNAL */
373 update_length(_length, cnt);
378 SMFSource::get_state ()
380 XMLNode& root (MidiSource::get_state());
382 snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
383 root.add_property ("flags", buf);
388 SMFSource::set_state (const XMLNode& node)
390 const XMLProperty* prop;
392 if (MidiSource::set_state (node)) {
396 if ((prop = node.property (X_("flags"))) != 0) {
399 sscanf (prop->value().c_str(), "0x%x", &ival);
400 _flags = Flag (ival);
408 assert(_name.find("/") == string::npos);
414 SMFSource::mark_for_remove ()
419 _flags = Flag (_flags | RemoveAtDestroy);
423 SMFSource::mark_streaming_write_completed ()
432 Glib::Mutex::Lock lm (_lock);
435 next_peak_clear_should_notify = true;
437 if (_peaks_built || pending_peak_builds.empty()) {
439 PeaksReady (); /* EMIT SIGNAL */
445 SMFSource::mark_take (string id)
453 SMFSource::move_to_trash (const string trash_dir_name)
461 /* don't move the file across filesystems, just
462 stick it in the 'trash_dir_name' directory
463 on whichever filesystem it was already on.
466 newpath = Glib::path_get_dirname (_path);
467 newpath = Glib::path_get_dirname (newpath);
470 newpath += trash_dir_name;
472 newpath += Glib::path_get_basename (_path);
474 if (access (newpath.c_str(), F_OK) == 0) {
476 /* the new path already exists, try versioning */
478 char buf[PATH_MAX+1];
482 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
485 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
486 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
490 if (version == 999) {
491 PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
500 /* it doesn't exist, or we can't read it or something */
504 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
505 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
506 _path, newpath, strerror (errno))
511 if (::unlink (peakpath.c_str()) != 0) {
512 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
513 peakpath, _path, strerror (errno))
515 /* try to back out */
516 rename (newpath.c_str(), _path.c_str());
523 /* file can not be removed twice, since the operation is not idempotent */
525 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
530 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
532 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
534 string::size_type pos;
539 /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
541 if ((pos = pathstr.find_last_of (':')) == string::npos) {
544 pathstr = pathstr.substr (0, pos);
547 if (pathstr[0] != '/') {
549 /* non-absolute pathname: find pathstr in search path */
556 if (_search_path.length() == 0) {
557 PBD::error << _("FileSource: search path not set") << endmsg;
561 split (_search_path, dirs, ':');
565 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
568 if (fullpath[fullpath.length()-1] != '/') {
573 if (access (fullpath.c_str(), R_OK) == 0) {
581 PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
584 } else if (cnt == 0) {
587 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
600 /* external files and/or very very old style sessions include full paths */
603 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
605 if (access (_path.c_str(), R_OK) != 0) {
607 /* file does not exist or we cannot read it */
610 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
614 if (errno != ENOENT) {
615 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
637 SMFSource::set_search_path (string p)
644 SMFSource::set_allow_remove_if_empty (bool yn)
647 _allow_remove_if_empty = yn;
652 SMFSource::set_name (string newname, bool destructive)
654 //Glib::Mutex::Lock lm (_lock); FIXME
655 string oldpath = _path;
656 string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
658 if (newpath.empty()) {
659 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
663 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
664 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
668 _name = Glib::path_get_basename (newpath);
671 return 0;//rename_peakfile (peak_path (_path));
675 SMFSource::is_empty (string path)
684 SMFSource::write_chunk_header(char id[4], uint32_t length)
686 const uint32_t length_be = GUINT32_TO_BE(length);
688 fwrite(id, 1, 4, _fd);
689 fwrite(&length_be, 4, 1, _fd);
693 SMFSource::write_chunk(char id[4], uint32_t length, void* data)
695 write_chunk_header(id, length);
697 fwrite(data, 1, length, _fd);
700 /** Returns the size (in bytes) of the value written. */
702 SMFSource::write_var_len(uint32_t value)
706 uint32_t buffer = value & 0x7F;
708 while ( (value >>= 7) ) {
710 buffer |= ((value & 0x7F) | 0x80);
714 //printf("Writing var len byte %X\n", (unsigned char)buffer);
727 SMFSource::read_var_len() const
731 //int offset = ftell(_fd);
732 //cerr << "SMF - reading var len at " << offset << endl;
737 if ( (value = getc(_fd)) & 0x80 ) {
741 value = (value << 7) + ((c = getc(_fd)) & 0x7F);