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