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