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