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