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