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