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