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