Move midi_util.h.
[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 <evoral/SMFReader.hpp>
36
37 #include <ardour/smf_source.h>
38 #include <ardour/session.h>
39 #include <ardour/midi_ring_buffer.h>
40 #include <ardour/tempo.h>
41 #include <ardour/audioengine.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         , SMF ()
58         , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
59         , _allow_remove_if_empty(true)
60 {
61         /* constructor used for new internal-to-session files. file cannot exist */
62
63         if (init (path, false)) {
64                 throw failed_constructor ();
65         }
66         
67         if (open(path)) {
68                 throw failed_constructor ();
69         }
70
71         assert(_name.find("/") == string::npos);
72 }
73
74 SMFSource::SMFSource (Session& s, const XMLNode& node)
75         : MidiSource (s, node)
76         , _flags (Flag (Writable|CanRename))
77         , _allow_remove_if_empty(true)
78 {
79         /* constructor used for existing internal-to-session files. file must exist */
80
81         if (set_state (node)) {
82                 throw failed_constructor ();
83         }
84         
85         if (init (_name, true)) {
86                 throw failed_constructor ();
87         }
88         
89         if (open(_path)) {
90                 throw failed_constructor ();
91         }
92         
93         assert(_name.find("/") == string::npos);
94 }
95
96 SMFSource::~SMFSource ()
97 {
98         if (removable()) {
99                 unlink (_path.c_str());
100         }
101 }
102
103 bool
104 SMFSource::removable () const
105 {
106         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || 
107                                       ((_flags & RemovableIfEmpty) && is_empty()));
108 }
109
110 int
111 SMFSource::init (string pathstr, bool must_exist)
112 {
113         bool is_new = false;
114
115         if (!find (pathstr, must_exist, is_new)) {
116                 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
117                 return -1;
118         }
119
120         if (is_new && must_exist) {
121                 return -1;
122         }
123
124         assert(_name.find("/") == string::npos);
125         return 0;
126 }
127
128 /** All stamps in audio frames */
129 nframes_t
130 SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
131 {
132         //cerr << "SMF read_unlocked " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
133
134         // 64 bits ought to be enough for anybody
135         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
136
137         _read_data_count = 0;
138
139         // Output parameters for read_event (which will allocate scratch in buffer as needed)
140         uint32_t ev_delta_t = 0;
141         uint32_t ev_type = 0;
142         uint32_t ev_size = 0;
143         uint8_t* ev_buffer = 0;
144
145         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
146
147         // FIXME: don't seek to start and search every read (brutal!)
148         SMF::seek_to_start();
149         
150         // FIXME: assumes tempo never changes after start
151         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
152                         _session.engine().frame_rate(),
153                         _session.tempo_map().meter_at(_timeline_position));
154         
155         const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
156
157         while (!SMF::eof()) {
158                 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
159                 if (ret == -1) { // EOF
160                         //cerr << "SMF - EOF\n";
161                         break;
162                 }
163                 
164                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
165                 
166                 time += ev_delta_t; // accumulate delta time
167
168                 if (ret == 0) { // meta-event (skipped, just accumulate time)
169                         //cerr << "SMF - META\n";
170                         continue;
171                 }
172
173                 if (time >= start_ticks) {
174                         const nframes_t ev_frame_time = (nframes_t)(
175                                         ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
176
177                         if (ev_frame_time <= start + cnt)
178                                 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
179                         else
180                                 break;
181                 }
182
183                 _read_data_count += ev_size;
184
185                 if (ev_size > scratch_size)
186                         scratch_size = ev_size;
187                 else
188                         ev_size = scratch_size; // minimize realloc in read_event
189         }
190         
191         return cnt;
192 }
193
194 /** All stamps in audio frames */
195 nframes_t
196 SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
197 {
198         _write_data_count = 0;
199                 
200         EventTime time;
201         EventType type;
202         uint32_t  size;
203
204         size_t buf_capacity = 4;
205         uint8_t* buf = (uint8_t*)malloc(buf_capacity);
206         
207         if (_model && ! _model->writing())
208                 _model->start_write();
209
210         Evoral::MIDIEvent ev(0, 0.0, 4, NULL, true);
211
212         while (true) {
213                 bool ret = src.peek_time(&time);
214                 if (!ret || time - _timeline_position > _length + cnt)
215                         break;
216
217                 ret = src.read_prefix(&time, &type, &size);
218                 if (!ret)
219                         break;
220
221                 if (size > buf_capacity) {
222                         buf_capacity = size;
223                         buf = (uint8_t*)realloc(buf, size);
224                 }
225
226                 ret = src.read_contents(size, buf);
227                 if (!ret) {
228                         cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
229                         break;
230                 }
231                 
232                 assert(time >= _timeline_position);
233                 time -= _timeline_position;
234                 
235                 ev.set(buf, size, time);
236                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
237                 if (! (ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex()) ) {
238                         //cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type " << std::hex << int(ev.buffer()[0]) << endl;
239                         continue;
240                 }
241                 
242                 append_event_unlocked(Frames, ev);
243
244                 if (_model)
245                         _model->append(ev);
246         }
247
248         SMF::flush();
249         free(buf);
250
251         const nframes_t oldlen = _length;
252         update_length(oldlen, cnt);
253
254         ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
255         
256         return cnt;
257 }
258                 
259
260 void
261 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event& ev)
262 {
263         if (ev.size() == 0)
264                 return;
265
266         /*printf("SMFSource: %s - append_event_unlocked chan = %u, time = %lf, size = %u, data = ",
267                         name().c_str(), (unsigned)ev.channel(), ev.time(), ev.size()); 
268         for (size_t i=0; i < ev.size(); ++i) {
269                 printf("%X ", ev.buffer()[i]);
270         }
271         printf("\n");*/
272         
273         assert(ev.time() >= 0);
274         
275         if (ev.time() < last_event_time()) {
276                 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
277                 return;
278         }
279         
280         uint32_t delta_time = 0;
281         
282         if (unit == Frames) {
283                 // FIXME: assumes tempo never changes after start
284                 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
285                                 _session.engine().frame_rate(),
286                                 _session.tempo_map().meter_at(_timeline_position));
287
288                 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
289         } else {
290                 assert(unit == Beats);
291                 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
292         }
293
294         SMF::append_event_unlocked(delta_time, ev);
295
296         _write_data_count += ev.size();
297 }
298
299
300 XMLNode&
301 SMFSource::get_state ()
302 {
303         XMLNode& root (MidiSource::get_state());
304         char buf[16];
305         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
306         root.add_property ("flags", buf);
307         return root;
308 }
309
310 int
311 SMFSource::set_state (const XMLNode& node)
312 {
313         const XMLProperty* prop;
314
315         if (MidiSource::set_state (node)) {
316                 return -1;
317         }
318
319         if ((prop = node.property (X_("flags"))) != 0) {
320
321                 int ival;
322                 sscanf (prop->value().c_str(), "0x%x", &ival);
323                 _flags = Flag (ival);
324
325         } else {
326
327                 _flags = Flag (0);
328
329         }
330
331         assert(_name.find("/") == string::npos);
332
333         return 0;
334 }
335
336 void
337 SMFSource::mark_for_remove ()
338 {
339         if (!writable()) {
340                 return;
341         }
342         _flags = Flag (_flags | RemoveAtDestroy);
343 }
344
345 void
346 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
347 {
348         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
349         SMF::begin_write (start_frame);
350 }
351
352 void
353 SMFSource::mark_streaming_write_completed ()
354 {
355         MidiSource::mark_streaming_write_completed();
356
357         if (!writable()) {
358                 return;
359         }
360         
361         _model->set_edited(false);
362         SMF::end_write ();
363 }
364
365 void
366 SMFSource::mark_take (string id)
367 {
368         if (writable()) {
369                 _take_id = id;
370         }
371 }
372
373 int
374 SMFSource::move_to_trash (const string trash_dir_name)
375 {
376         string newpath;
377
378         if (!writable()) {
379                 return -1;
380         }
381
382         /* don't move the file across filesystems, just
383            stick it in the 'trash_dir_name' directory
384            on whichever filesystem it was already on.
385         */
386
387         newpath = Glib::path_get_dirname (_path);
388         newpath = Glib::path_get_dirname (newpath);
389
390         newpath += '/';
391         newpath += trash_dir_name;
392         newpath += '/';
393         newpath += Glib::path_get_basename (_path);
394
395         if (access (newpath.c_str(), F_OK) == 0) {
396
397                 /* the new path already exists, try versioning */
398                 
399                 char buf[PATH_MAX+1];
400                 int version = 1;
401                 string newpath_v;
402
403                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
404                 newpath_v = buf;
405
406                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
407                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
408                         newpath_v = buf;
409                 }
410                 
411                 if (version == 999) {
412                         PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
413                                           newpath)
414                               << endmsg;
415                 } else {
416                         newpath = newpath_v;
417                 }
418
419         } else {
420
421                 /* it doesn't exist, or we can't read it or something */
422
423         }
424
425         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
426                 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
427                                   _path, newpath, strerror (errno))
428                       << endmsg;
429                 return -1;
430         }
431 #if 0
432         if (::unlink (peakpath.c_str()) != 0) {
433                 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
434                                   peakpath, _path, strerror (errno))
435                       << endmsg;
436                 /* try to back out */
437                 rename (newpath.c_str(), _path.c_str());
438                 return -1;
439         }
440             
441         _path = newpath;
442         peakpath = "";
443 #endif  
444         /* file can not be removed twice, since the operation is not idempotent */
445
446         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
447
448         return 0;
449 }
450
451 bool
452 SMFSource::safe_file_extension(const Glib::ustring& file)
453 {
454         return (file.rfind(".mid") != Glib::ustring::npos);
455 }
456
457 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
458 bool
459 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
460 {
461         string::size_type pos;
462         bool ret = false;
463
464         isnew = false;
465
466         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
467
468         if ((pos = pathstr.find_last_of (':')) == string::npos) {
469                 pathstr = pathstr;
470         } else {
471                 pathstr = pathstr.substr (0, pos);
472         }
473
474         if (pathstr[0] != '/') {
475
476                 /* non-absolute pathname: find pathstr in search path */
477
478                 vector<string> dirs;
479                 int cnt;
480                 string fullpath;
481                 string keeppath;
482
483                 if (_search_path.length() == 0) {
484                         PBD::error << _("FileSource: search path not set") << endmsg;
485                         goto out;
486                 }
487
488                 split (_search_path, dirs, ':');
489
490                 cnt = 0;
491                 
492                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
493
494                         fullpath = *i;
495                         if (fullpath[fullpath.length()-1] != '/') {
496                                 fullpath += '/';
497                         }
498                         fullpath += pathstr;
499                         
500                         if (access (fullpath.c_str(), R_OK) == 0) {
501                                 keeppath = fullpath;
502                                 ++cnt;
503                         } 
504                 }
505
506                 if (cnt > 1) {
507
508                         PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
509                         goto out;
510
511                 } else if (cnt == 0) {
512
513                         if (must_exist) {
514                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
515                                 goto out;
516                         } else {
517                                 isnew = true;
518                         }
519                 }
520                 
521                 _name = pathstr;
522                 _path = keeppath;
523                 ret = true;
524
525         } else {
526                 
527                 /* external files and/or very very old style sessions include full paths */
528                 
529                 _path = pathstr;
530                 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
531                 
532                 if (access (_path.c_str(), R_OK) != 0) {
533
534                         /* file does not exist or we cannot read it */
535
536                         if (must_exist) {
537                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
538                                 goto out;
539                         }
540                         
541                         if (errno != ENOENT) {
542                                 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
543                                 goto out;
544                         }
545                         
546                         /* a new file */
547
548                         isnew = true;
549                         ret = true;
550
551                 } else {
552                         
553                         /* already exists */
554
555                         ret = true;
556                 }
557         }
558         
559   out:
560         return ret;
561 }
562
563 void
564 SMFSource::set_search_path (string p)
565 {
566         _search_path = p;
567 }
568
569
570 void
571 SMFSource::set_allow_remove_if_empty (bool yn)
572 {
573         if (writable()) {
574                 _allow_remove_if_empty = yn;
575         }
576 }
577
578 int
579 SMFSource::set_source_name (string newname, bool destructive)
580 {
581         //Glib::Mutex::Lock lm (_lock); FIXME
582         string oldpath = _path;
583         string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
584
585         if (newpath.empty()) {
586                 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
587                 return -1;
588         }
589
590         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
591                 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
592                 return -1;
593         }
594
595         _name = Glib::path_get_basename (newpath);
596         _path = newpath;
597
598         return 0;//rename_peakfile (peak_path (_path));
599 }
600
601 void
602 SMFSource::load_model(bool lock, bool force_reload)
603 {
604         if (_writing)
605                 return;
606
607         if (lock)
608                 Glib::Mutex::Lock lm (_lock);
609
610         if (_model && !force_reload && !_model->empty())
611                 return;
612
613         if (! _model) {
614                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
615                 cerr << _name << " loaded new model " << _model.get() << endl;
616         } else {
617                 cerr << _name << " reloading model " << _model.get()
618                         << " (" << _model->n_notes() << " notes)" <<endl;
619                 _model->clear();
620         }
621
622         _model->start_write();
623         SMF::seek_to_start();
624
625         uint64_t time = 0; /* in SMF ticks */
626         Evoral::Event ev;
627         
628         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
629         
630         // FIXME: assumes tempo never changes after start
631         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
632                         _session.engine().frame_rate(),
633                         _session.tempo_map().meter_at(_timeline_position));
634         
635         uint32_t delta_t = 0;
636         uint32_t size    = 0;
637         uint8_t* buf     = NULL;
638         int ret;
639         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
640                 
641                 ev.set(buf, size, 0.0);
642                 time += delta_t;
643                 
644                 if (ret > 0) { // didn't skip (meta) event
645                         // make ev.time absolute time in frames
646                         ev.time() = time * frames_per_beat / (EventTime)ppqn();
647                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
648                         _model->append(ev);
649                 }
650
651                 if (ev.size() > scratch_size)
652                         scratch_size = ev.size();
653                 else
654                         ev.size() = scratch_size;
655         }
656         
657         _model->end_write(false);
658         _model->set_edited(false);
659
660         free(buf);
661 }
662
663
664 void
665 SMFSource::destroy_model()
666 {
667         //cerr << _name << " destroying model " << _model.get() << endl;
668         _model.reset();
669 }
670
671 void
672 SMFSource::flush_midi()
673 {
674         SMF::end_write();
675 }
676