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