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