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