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