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