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