* bugfix: SMFSource: track footer at beginning of track not overwritten
[ardour.git] / libs / ardour / smf_source.cc
1 /*
2     Copyright (C) 2006 Paul Davis 
3         Written by Dave Robillard, 2006
4
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.
9
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.
14
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.
18
19 */
20
21 #include <vector>
22
23 #include <sys/time.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <errno.h>
27
28 #include <pbd/mountpoint.h>
29 #include <pbd/pathscanner.h>
30 #include <pbd/stl_delete.h>
31 #include <pbd/strsplit.h>
32
33 #include <glibmm/miscutils.h>
34
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>
42
43 #include "i18n.h"
44
45 using namespace ARDOUR;
46
47 string SMFSource::_search_path;
48
49 /*sigc::signal<void,struct tm*, time_t> SMFSource::HeaderPositionOffsetChanged;
50 bool                                  SMFSource::header_position_negative;
51 uint64_t                              SMFSource::header_position_offset;
52 */
53
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)
58         , _fd (0)
59         , _last_ev_time(0)
60         , _track_size(4) // 4 bytes for the ever-present EOT event
61         , _header_size(22)
62 {
63         /* constructor used for new internal-to-session files. file cannot exist */
64
65         if (init (path, false)) {
66                 throw failed_constructor ();
67         }
68         
69         if (open()) {
70                 throw failed_constructor ();
71         }
72
73         cerr << "SMF Source path: " << path << endl;
74         
75         assert(_name.find("/") == string::npos);
76 }
77
78 SMFSource::SMFSource (Session& s, const XMLNode& node)
79         : MidiSource (s, node)
80         , _flags (Flag (Writable|CanRename))
81         , _allow_remove_if_empty(true)
82         , _fd (0)
83         , _last_ev_time(0)
84         , _track_size(4) // 4 bytes for the ever-present EOT event
85         , _header_size(22)
86 {
87         /* constructor used for existing internal-to-session files. file must exist */
88
89         if (set_state (node)) {
90                 throw failed_constructor ();
91         }
92         
93         if (init (_name, true)) {
94                 throw failed_constructor ();
95         }
96         
97         if (open()) {
98                 throw failed_constructor ();
99         }
100         
101         assert(_name.find("/") == string::npos);
102 }
103
104 SMFSource::~SMFSource ()
105 {
106         if (removable()) {
107                 unlink (_path.c_str());
108         }
109 }
110
111 bool
112 SMFSource::removable () const
113 {
114         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || 
115                                       ((_flags & RemovableIfEmpty) && is_empty()));
116 }
117
118 int
119 SMFSource::init (string pathstr, bool must_exist)
120 {
121         bool is_new = false;
122
123         if (!find (pathstr, must_exist, is_new)) {
124                 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
125                 return -1;
126         }
127
128         if (is_new && must_exist) {
129                 return -1;
130         }
131
132         assert(_name.find("/") == string::npos);
133         return 0;
134 }
135
136 /** Attempt to open the SMF file for reading and writing.
137  *
138  * Currently SMFSource is always read/write.
139  *
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
143  */
144 int
145 SMFSource::open()
146 {
147         //cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
148
149         assert(writable()); // FIXME;
150
151         _fd = fopen(path().c_str(), "r+");
152
153         // File already exists
154         if (_fd) {
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;
160
161         // We're making a new file
162         } else {
163                 _fd = fopen(path().c_str(), "w+");
164                 if (_fd == NULL) {
165                         cerr << "ERROR: Can not open SMF file " << path() << " for writing: " <<
166                                 strerror(errno) << endl;
167                         return -2;
168                 }
169                 _track_size = 4;
170
171                 // Write a tentative header just to pad things out so writing happens in the right spot
172                 flush_header();
173                 flush_footer();
174         }
175                 
176         return (_fd == 0) ? -1 : 0;
177 }
178
179 void
180 SMFSource::close()
181 {
182         if (_fd) {
183                 flush_header();
184                 flush_footer();
185                 fclose(_fd);
186                 _fd = NULL;
187         }
188 }
189
190 void
191 SMFSource::seek_to_footer_position()
192 {
193         uint8_t buffer[4];
194         
195         // lets check if there is a track end marker at the end of the data
196         fseek(_fd, -4, SEEK_END);
197         size_t read_bytes = fread(buffer, sizeof(uint8_t), 4, _fd);
198         if( (read_bytes == 4) && 
199             buffer[0] == 0x00 && 
200             buffer[1] == 0xFF && 
201             buffer[2] == 0x2F && 
202             buffer[3] == 0x00) {
203                 // there is one, so overwrite it
204                 fseek(_fd, -4, SEEK_END);
205         } else {
206                 // there is none, so append
207                 fseek(_fd, 0, SEEK_END);
208         }
209 }
210
211 int
212 SMFSource::flush_header()
213 {
214         // FIXME: write timeline position somehow?
215         
216         //cerr << path() << " SMF Flushing header\n";
217
218         assert(_fd);
219
220         const uint16_t type     = GUINT16_TO_BE(0);     // SMF Type 0 (single track)
221         const uint16_t ntracks  = GUINT16_TO_BE(1);     // Number of tracks (always 1 for Type 0)
222         const uint16_t division = GUINT16_TO_BE(_ppqn); // Pulses per quarter note (beat)
223
224         char data[6];
225         memcpy(data, &type, 2);
226         memcpy(data+2, &ntracks, 2);
227         memcpy(data+4, &division, 2);
228
229         _fd = freopen(path().c_str(), "r+", _fd);
230         assert(_fd);
231         fseek(_fd, 0, SEEK_SET);
232         write_chunk("MThd", 6, data);
233         write_chunk_header("MTrk", _track_size); 
234
235         fflush(_fd);
236
237         return 0;
238 }
239
240 int
241 SMFSource::flush_footer()
242 {
243         //cerr << path() << " SMF Flushing footer\n";
244         seek_to_footer_position();
245         write_footer();
246
247         return 0;
248 }
249
250 void
251 SMFSource::write_footer()
252 {
253         write_var_len(0);
254         char eot[3] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
255         fwrite(eot, 1, 3, _fd);
256         fflush(_fd);
257 }
258
259 /** Returns the offset of the first event in the file with a time past @a start,
260  * relative to the start of the source.
261  *
262  * Returns -1 if not found.
263  */
264 /*
265 long
266 SMFSource::find_first_event_after(nframes_t start)
267 {
268         // FIXME: obviously this is slooow
269         
270         fseek(_fd, _header_size, 0);
271
272         while ( ! feof(_fd) ) {
273                 const uint32_t delta_time = read_var_len();
274
275                 if (delta_time > start)
276                         return delta_time;
277         }
278
279         return -1;
280 }
281 */
282
283 /** Read an event from the current position in file.
284  *
285  * File position MUST be at the beginning of a delta time, or this will die very messily.
286  * ev.buffer must be of size ev.size, and large enough for the event.  The returned event
287  * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
288  * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
289  *
290  * \a size should be the capacity of \a buf.  If it is not large enough, \a buf will
291  * be freed and a new buffer allocated in its place, the size of which will be placed
292  * in size.
293  *
294  * Returns event length (including status byte) on success, 0 if event was
295  * skipped (eg a meta event), or -1 on EOF (or end of track).
296  */
297 int
298 SMFSource::read_event(uint32_t* delta_t, uint32_t* size, Byte** buf) const
299 {
300         if (feof(_fd)) {
301                 return -1;
302         }
303
304         assert(delta_t);
305         assert(size);
306         assert(buf);
307
308         try {
309                 *delta_t = SMFReader::read_var_len(_fd);
310         } catch (...) {
311                 return -1; // Premature EOF
312         }
313         
314         if (feof(_fd)) {
315                 return -1; // Premature EOF
316         }
317
318         const int status = fgetc(_fd);
319
320         if (status == EOF) {
321                 return -1; // Premature EOF
322         }
323
324         //printf("Status @ %X = %X\n", (unsigned)ftell(_fd) - 1, status);
325
326         if (status == 0xFF) {
327                 if (feof(_fd)) {
328                         return -1; // Premature EOF
329                 }
330                 const int type = fgetc(_fd);
331                 if ((unsigned char)type == 0x2F) {
332                         return -1; // hit end of track
333                 } else {
334                         *size = 0;
335                         return 0;
336                 }
337         }
338         
339         const int event_size = midi_event_size((unsigned char)status) + 1;
340         if (event_size <= 0) {
341                 *size = 0;
342                 return 0;
343         }
344         
345         // Make sure we have enough scratch buffer
346         if (*size < (unsigned)event_size)
347                 *buf = (Byte*)realloc(*buf, event_size);
348         
349         *size = event_size;
350
351         (*buf)[0] = (unsigned char)status;
352         if (event_size > 1)
353                 fread((*buf) + 1, 1, *size - 1, _fd);
354
355         /*printf("SMFSource %s read event: delta = %u, size = %u, data = ", _name.c_str(), *delta_t, *size);
356         for (size_t i=0; i < *size; ++i) {
357                 printf("%X ", (*buf)[i]);
358         }
359         printf("\n"); */
360         
361         return (int)*size;
362 }
363
364 /** All stamps in audio frames */
365 nframes_t
366 SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
367 {
368         cerr << "SMF read_unlocked " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
369
370         // 64 bits ought to be enough for anybody
371         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
372
373         _read_data_count = 0;
374
375         // Output parameters for read_event (which will allocate scratch in buffer as needed)
376         uint32_t ev_delta_t = 0;
377         uint32_t ev_size = 0;
378         Byte*    ev_buffer = 0;
379
380         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
381
382         // FIXME: don't seek to start and search every read (brutal!)
383         fseek(_fd, _header_size, SEEK_SET);
384         
385         // FIXME: assumes tempo never changes after start
386         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
387                         _session.engine().frame_rate(),
388                         _session.tempo_map().meter_at(_timeline_position));
389         
390         const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * _ppqn);
391
392         while (!feof(_fd)) {
393                 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
394                 if (ret == -1) { // EOF
395                         //cerr << "SMF - EOF\n";
396                         break;
397                 }
398
399                 if (ret == 0) { // meta-event (skipped)
400                         //cerr << "SMF - META\n";
401                         time += ev_delta_t; // just accumulate delta time and ignore event
402                         continue;
403                 }
404
405                 time += ev_delta_t; // accumulate delta time
406
407                 if (time >= start_ticks) {
408                         const nframes_t ev_frame_time = (nframes_t)(
409                                         ((time / (double)_ppqn) * frames_per_beat)) + stamp_offset;
410
411                         if (ev_frame_time <= start + cnt)
412                                 dst.write(ev_frame_time - negative_stamp_offset, ev_size, ev_buffer);
413                         else
414                                 break;
415                 }
416
417                 _read_data_count += ev_size;
418
419                 if (ev_size > scratch_size)
420                         scratch_size = ev_size;
421                 else
422                         ev_size = scratch_size; // minimize realloc in read_event
423         }
424         
425         return cnt;
426 }
427
428 /** All stamps in audio frames */
429 nframes_t
430 SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
431 {
432         _write_data_count = 0;
433                 
434         double time;
435         size_t size;
436
437         size_t buf_capacity = 4;
438         Byte* buf = (Byte*)malloc(buf_capacity);
439         
440         if (_model && ! _model->writing())
441                 _model->start_write();
442
443         while (true) {
444                 bool ret = src.full_peek(sizeof(double), (Byte*)&time);
445                 if (!ret || time - _timeline_position > _length + cnt)
446                         break;
447
448                 ret = src.read_prefix(&time, &size);
449                 if (!ret)
450                         break;
451
452                 if (size > buf_capacity) {
453                         buf_capacity = size;
454                         buf = (Byte*)realloc(buf, size);
455                 }
456
457                 ret = src.read_contents(size, buf);
458                 if (!ret) {
459                         cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
460                         break;
461                 }
462                 
463                 assert(time >= _timeline_position);
464                 time -= _timeline_position;
465                 
466                 const MIDI::Event ev(time, size, buf);
467                 if (! (ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex()) ) {
468                         //cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type " << std::hex << int(ev.buffer()[0]) << endl;
469                         continue;
470                 }
471                 
472                 append_event_unlocked(Frames, ev);
473
474                 if (_model)
475                         _model->append(ev);
476         }
477
478         fflush(_fd);
479         free(buf);
480
481         const nframes_t oldlen = _length;
482         update_length(oldlen, cnt);
483
484         ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
485         
486         return cnt;
487 }
488                 
489
490 void
491 SMFSource::append_event_unlocked(EventTimeUnit unit, const MIDI::Event& ev)
492 {
493         /*printf("SMFSource: %s - append_event_unlocked chan = %u, time = %lf, size = %u, data = ",
494                         name().c_str(), (unsigned)ev.channel(), ev.time(), ev.size()); */
495         for (size_t i=0; i < ev.size(); ++i) {
496                 printf("%X ", ev.buffer()[i]);
497         }
498         printf("\n");
499         
500         assert(ev.time() >= 0);
501         assert(ev.time() >= _last_ev_time);
502         
503         uint32_t delta_time = 0;
504         
505         if (unit == Frames) {
506                 // FIXME: assumes tempo never changes after start
507                 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
508                                 _session.engine().frame_rate(),
509                                 _session.tempo_map().meter_at(_timeline_position));
510
511                 delta_time = (uint32_t)((ev.time() - _last_ev_time) / frames_per_beat * _ppqn);
512         } else {
513                 assert(unit == Beats);
514                 delta_time = (uint32_t)((ev.time() - _last_ev_time) * _ppqn);
515         }
516
517         
518         const size_t stamp_size = write_var_len(delta_time);
519         fwrite(ev.buffer(), 1, ev.size(), _fd);
520
521         _track_size += stamp_size + ev.size();
522         _write_data_count += ev.size();
523
524         _last_ev_time = ev.time();
525 }
526
527
528 XMLNode&
529 SMFSource::get_state ()
530 {
531         XMLNode& root (MidiSource::get_state());
532         char buf[16];
533         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
534         root.add_property ("flags", buf);
535         return root;
536 }
537
538 int
539 SMFSource::set_state (const XMLNode& node)
540 {
541         const XMLProperty* prop;
542
543         if (MidiSource::set_state (node)) {
544                 return -1;
545         }
546
547         if ((prop = node.property (X_("flags"))) != 0) {
548
549                 int ival;
550                 sscanf (prop->value().c_str(), "0x%x", &ival);
551                 _flags = Flag (ival);
552
553         } else {
554
555                 _flags = Flag (0);
556
557         }
558
559         assert(_name.find("/") == string::npos);
560
561         return 0;
562 }
563
564 void
565 SMFSource::mark_for_remove ()
566 {
567         if (!writable()) {
568                 return;
569         }
570         _flags = Flag (_flags | RemoveAtDestroy);
571 }
572
573 void
574 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
575 {
576         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
577         _last_ev_time = 0;
578         fseek(_fd, _header_size, SEEK_SET);
579 }
580
581 void
582 SMFSource::mark_streaming_write_completed ()
583 {
584         MidiSource::mark_streaming_write_completed();
585
586         if (!writable()) {
587                 return;
588         }
589         
590         _model->set_edited(false);
591         flush_header();
592         flush_footer();
593 }
594
595 void
596 SMFSource::mark_take (string id)
597 {
598         if (writable()) {
599                 _take_id = id;
600         }
601 }
602
603 int
604 SMFSource::move_to_trash (const string trash_dir_name)
605 {
606         string newpath;
607
608         if (!writable()) {
609                 return -1;
610         }
611
612         /* don't move the file across filesystems, just
613            stick it in the 'trash_dir_name' directory
614            on whichever filesystem it was already on.
615         */
616
617         newpath = Glib::path_get_dirname (_path);
618         newpath = Glib::path_get_dirname (newpath);
619
620         newpath += '/';
621         newpath += trash_dir_name;
622         newpath += '/';
623         newpath += Glib::path_get_basename (_path);
624
625         if (access (newpath.c_str(), F_OK) == 0) {
626
627                 /* the new path already exists, try versioning */
628                 
629                 char buf[PATH_MAX+1];
630                 int version = 1;
631                 string newpath_v;
632
633                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
634                 newpath_v = buf;
635
636                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
637                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
638                         newpath_v = buf;
639                 }
640                 
641                 if (version == 999) {
642                         PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
643                                           newpath)
644                               << endmsg;
645                 } else {
646                         newpath = newpath_v;
647                 }
648
649         } else {
650
651                 /* it doesn't exist, or we can't read it or something */
652
653         }
654
655         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
656                 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
657                                   _path, newpath, strerror (errno))
658                       << endmsg;
659                 return -1;
660         }
661 #if 0
662         if (::unlink (peakpath.c_str()) != 0) {
663                 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
664                                   peakpath, _path, strerror (errno))
665                       << endmsg;
666                 /* try to back out */
667                 rename (newpath.c_str(), _path.c_str());
668                 return -1;
669         }
670             
671         _path = newpath;
672         peakpath = "";
673 #endif  
674         /* file can not be removed twice, since the operation is not idempotent */
675
676         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
677
678         return 0;
679 }
680
681 bool
682 SMFSource::safe_file_extension(const Glib::ustring& file)
683 {
684         return (file.rfind(".mid") != Glib::ustring::npos);
685 }
686
687 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
688 bool
689 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
690 {
691         string::size_type pos;
692         bool ret = false;
693
694         isnew = false;
695
696         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
697
698         if ((pos = pathstr.find_last_of (':')) == string::npos) {
699                 pathstr = pathstr;
700         } else {
701                 pathstr = pathstr.substr (0, pos);
702         }
703
704         if (pathstr[0] != '/') {
705
706                 /* non-absolute pathname: find pathstr in search path */
707
708                 vector<string> dirs;
709                 int cnt;
710                 string fullpath;
711                 string keeppath;
712
713                 if (_search_path.length() == 0) {
714                         PBD::error << _("FileSource: search path not set") << endmsg;
715                         goto out;
716                 }
717
718                 split (_search_path, dirs, ':');
719
720                 cnt = 0;
721                 
722                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
723
724                         fullpath = *i;
725                         if (fullpath[fullpath.length()-1] != '/') {
726                                 fullpath += '/';
727                         }
728                         fullpath += pathstr;
729                         
730                         if (access (fullpath.c_str(), R_OK) == 0) {
731                                 keeppath = fullpath;
732                                 ++cnt;
733                         } 
734                 }
735
736                 if (cnt > 1) {
737
738                         PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
739                         goto out;
740
741                 } else if (cnt == 0) {
742
743                         if (must_exist) {
744                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
745                                 goto out;
746                         } else {
747                                 isnew = true;
748                         }
749                 }
750                 
751                 _name = pathstr;
752                 _path = keeppath;
753                 ret = true;
754
755         } else {
756                 
757                 /* external files and/or very very old style sessions include full paths */
758                 
759                 _path = pathstr;
760                 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
761                 
762                 if (access (_path.c_str(), R_OK) != 0) {
763
764                         /* file does not exist or we cannot read it */
765
766                         if (must_exist) {
767                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
768                                 goto out;
769                         }
770                         
771                         if (errno != ENOENT) {
772                                 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
773                                 goto out;
774                         }
775                         
776                         /* a new file */
777
778                         isnew = true;
779                         ret = true;
780
781                 } else {
782                         
783                         /* already exists */
784
785                         ret = true;
786                 }
787         }
788         
789   out:
790         return ret;
791 }
792
793 void
794 SMFSource::set_search_path (string p)
795 {
796         _search_path = p;
797 }
798
799
800 void
801 SMFSource::set_allow_remove_if_empty (bool yn)
802 {
803         if (writable()) {
804                 _allow_remove_if_empty = yn;
805         }
806 }
807
808 int
809 SMFSource::set_source_name (string newname, bool destructive)
810 {
811         //Glib::Mutex::Lock lm (_lock); FIXME
812         string oldpath = _path;
813         string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
814
815         if (newpath.empty()) {
816                 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
817                 return -1;
818         }
819
820         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
821                 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
822                 return -1;
823         }
824
825         _name = Glib::path_get_basename (newpath);
826         _path = newpath;
827
828         return 0;//rename_peakfile (peak_path (_path));
829 }
830
831 bool
832 SMFSource::is_empty () const
833 {
834         bool ret = (_track_size > 4);
835
836         //cerr << name() << " IS EMPTY: " << ret << endl;
837
838         return ret;
839 }
840
841
842 void
843 SMFSource::write_chunk_header(const char id[4], uint32_t length)
844 {
845         const uint32_t length_be = GUINT32_TO_BE(length);
846
847         fwrite(id, 1, 4, _fd);
848         fwrite(&length_be, 4, 1, _fd);
849 }
850
851 void
852 SMFSource::write_chunk(const char id[4], uint32_t length, void* data)
853 {
854         write_chunk_header(id, length);
855         
856         fwrite(data, 1, length, _fd);
857 }
858
859 /** Returns the size (in bytes) of the value written. */
860 size_t
861 SMFSource::write_var_len(uint32_t value)
862 {
863         size_t ret = 0;
864
865         uint32_t buffer = value & 0x7F;
866
867         while ( (value >>= 7) ) {
868                 buffer <<= 8;
869                 buffer |= ((value & 0x7F) | 0x80);
870         }
871
872         while (true) {
873                 //printf("Writing var len byte %X\n", (unsigned char)buffer);
874                 ++ret;
875                 fputc(buffer, _fd);
876                 if (buffer & 0x80)
877                         buffer >>= 8;
878                 else
879                         break;
880         }
881
882         return ret;
883 }
884
885 void
886 SMFSource::load_model(bool lock, bool force_reload)
887 {
888         if (_writing)
889                 return;
890
891         if (lock)
892                 Glib::Mutex::Lock lm (_lock);
893
894         if (_model && !force_reload && !_model->empty())
895                 return;
896
897         if (! _model) {
898                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
899                 cerr << _name << " loaded new model " << _model.get() << endl;
900         } else {
901                 cerr << _name << " reloading model " << _model.get()
902                         << " (" << _model->n_notes() << " notes)" <<endl;
903                 _model->clear();
904         }
905
906         _model->start_write();
907
908         fseek(_fd, _header_size, SEEK_SET);
909
910         uint64_t time = 0; /* in SMF ticks */
911         MIDI::Event ev;
912         
913         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
914         
915         // FIXME: assumes tempo never changes after start
916         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
917                         _session.engine().frame_rate(),
918                         _session.tempo_map().meter_at(_timeline_position));
919         
920         uint32_t delta_t = 0;
921         int ret;
922         while ((ret = read_event(&delta_t, &ev.size(), &ev.buffer())) >= 0) {
923                 
924                 time += delta_t;
925                 
926                 if (ret > 0) { // didn't skip (meta) event
927                         // make ev.time absolute time in frames
928                         ev.time() = (double)time * frames_per_beat / (double)_ppqn;
929
930                         _model->append(ev);
931                 }
932
933                 if (ev.size() > scratch_size)
934                         scratch_size = ev.size();
935                 else
936                         ev.size() = scratch_size;
937         }
938         
939         _model->end_write(false);
940         _model->set_edited(false);
941
942         free(ev.buffer());
943 }
944
945
946 void
947 SMFSource::destroy_model()
948 {
949         //cerr << _name << " destroying model " << _model.get() << endl;
950         _model.reset();
951 }
952