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