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