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