Clean up.
[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 cnt,
129                 nframes_t stamp_offset, nframes_t negative_stamp_offset) const
130 {
131         //cerr << "SMF read_unlocked " << name() << " read "
132         //<< start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
133
134         // 64 bits ought to be enough for anybody
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: don't seek to start and search every read (brutal!)
148         Evoral::SMF::seek_to_start();
149         
150         // FIXME: assumes tempo never changes after start
151         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
152                         _session.engine().frame_rate(),
153                         _session.tempo_map().meter_at(_timeline_position));
154         
155         const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
156
157         while (!Evoral::SMF::eof()) {
158                 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
159                 if (ret == -1) { // EOF
160                         //cerr << "SMF - EOF\n";
161                         break;
162                 }
163                 
164                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
165                 
166                 time += ev_delta_t; // accumulate delta time
167
168                 if (ret == 0) { // meta-event (skipped, just accumulate time)
169                         //cerr << "SMF - META\n";
170                         continue;
171                 }
172
173                 if (time >= start_ticks) {
174                         const nframes_t ev_frame_time = (nframes_t)(
175                                         ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
176
177                         if (ev_frame_time <= start + cnt) {
178                                 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
179                         } else {
180                                 break;
181                         }
182                 }
183
184                 _read_data_count += ev_size;
185
186                 if (ev_size > scratch_size) {
187                         scratch_size = ev_size;
188                 } else {
189                         ev_size = scratch_size; // minimize realloc in read_event
190                 }
191         }
192         
193         return cnt;
194 }
195
196 /** All stamps in audio frames */
197 nframes_t
198 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& src, nframes_t cnt)
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<double> 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 + cnt) {
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                 if (_model) {
251                         _model->append(ev);
252                 }
253         }
254
255         if (_model) {
256                 set_default_controls_interpolation();
257         }
258
259         Evoral::SMF::flush();
260         free(buf);
261
262         const nframes_t oldlen = _length;
263         update_length(oldlen, cnt);
264
265         ViewDataRangeReady(_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
266         
267         return cnt;
268 }
269                 
270
271 void
272 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event<double>& ev)
273 {
274         if (ev.size() == 0)  {
275                 cerr << "SMFSource: Warning: skipping empty event" << endl;
276                 return;
277         }
278
279         /*
280         printf("SMFSource: %s - append_event_unlocked time = %lf, size = %u, data = ",
281                         name().c_str(), ev.time(), ev.size()); 
282         for (size_t i=0; i < ev.size(); ++i) {
283                 printf("%X ", ev.buffer()[i]);
284         } printf("\n");
285         */
286         
287         assert(ev.time() >= 0);
288         
289         if (ev.time() < last_event_time()) {
290                 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
291                 return;
292         }
293         
294         uint32_t delta_time = 0;
295         
296         if (unit == Frames) {
297                 // FIXME: assumes tempo never changes after start
298                 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
299                                 _session.engine().frame_rate(),
300                                 _session.tempo_map().meter_at(_timeline_position));
301
302                 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
303         } else {
304                 assert(unit == Beats);
305                 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
306         }
307
308         Evoral::SMF::append_event_delta(delta_time, ev.size(), ev.buffer());
309         _last_ev_time = ev.time();
310
311         _write_data_count += ev.size();
312 }
313
314
315 XMLNode&
316 SMFSource::get_state ()
317 {
318         XMLNode& root (MidiSource::get_state());
319         char buf[16];
320         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
321         root.add_property ("flags", buf);
322         return root;
323 }
324
325 int
326 SMFSource::set_state (const XMLNode& node)
327 {
328         const XMLProperty* prop;
329
330         if (MidiSource::set_state (node)) {
331                 return -1;
332         }
333
334         if ((prop = node.property (X_("flags"))) != 0) {
335                 int ival;
336                 sscanf (prop->value().c_str(), "0x%x", &ival);
337                 _flags = Flag (ival);
338         } else {
339                 _flags = Flag (0);
340         }
341
342         assert(_name.find("/") == string::npos);
343
344         return 0;
345 }
346
347 void
348 SMFSource::mark_for_remove ()
349 {
350         if (!writable()) {
351                 return;
352         }
353         _flags = Flag (_flags | RemoveAtDestroy);
354 }
355
356 void
357 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
358 {
359         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
360         Evoral::SMF::begin_write ();
361         _last_ev_time = 0;
362 }
363
364 void
365 SMFSource::mark_streaming_write_completed ()
366 {
367         MidiSource::mark_streaming_write_completed();
368
369         if (!writable()) {
370                 return;
371         }
372         
373         _model->set_edited(false);
374         Evoral::SMF::end_write ();
375 }
376
377 void
378 SMFSource::mark_take (string id)
379 {
380         if (writable()) {
381                 _take_id = id;
382         }
383 }
384
385 int
386 SMFSource::move_to_trash (const string trash_dir_name)
387 {
388         string newpath;
389
390         if (!writable()) {
391                 return -1;
392         }
393
394         /* don't move the file across filesystems, just
395            stick it in the 'trash_dir_name' directory
396            on whichever filesystem it was already on.
397         */
398
399         newpath = Glib::path_get_dirname (_path);
400         newpath = Glib::path_get_dirname (newpath);
401
402         newpath += '/';
403         newpath += trash_dir_name;
404         newpath += '/';
405         newpath += Glib::path_get_basename (_path);
406
407         if (access (newpath.c_str(), F_OK) == 0) {
408
409                 /* the new path already exists, try versioning */
410                 
411                 char buf[PATH_MAX+1];
412                 int version = 1;
413                 string newpath_v;
414
415                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
416                 newpath_v = buf;
417
418                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
419                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
420                         newpath_v = buf;
421                 }
422                 
423                 if (version == 999) {
424                         PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
425                                           newpath)
426                               << endmsg;
427                 } else {
428                         newpath = newpath_v;
429                 }
430
431         } else {
432
433                 /* it doesn't exist, or we can't read it or something */
434
435         }
436
437         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
438                 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
439                                   _path, newpath, strerror (errno))
440                       << endmsg;
441                 return -1;
442         }
443         
444         /* file can not be removed twice, since the operation is not idempotent */
445
446         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
447
448         return 0;
449 }
450
451 bool
452 SMFSource::safe_file_extension(const Glib::ustring& file)
453 {
454         return (file.rfind(".mid") != Glib::ustring::npos);
455 }
456
457 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
458 bool
459 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
460 {
461         string::size_type pos;
462         bool ret = false;
463
464         isnew = false;
465
466         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
467
468         if ((pos = pathstr.find_last_of (':')) == string::npos) {
469                 pathstr = pathstr;
470         } else {
471                 pathstr = pathstr.substr (0, pos);
472         }
473
474         if (pathstr[0] != '/') {
475
476                 /* non-absolute pathname: find pathstr in search path */
477
478                 vector<string> dirs;
479                 int cnt;
480                 string fullpath;
481                 string keeppath;
482
483                 if (_search_path.length() == 0) {
484                         PBD::error << _("FileSource: search path not set") << endmsg;
485                         goto out;
486                 }
487
488                 split (_search_path, dirs, ':');
489
490                 cnt = 0;
491                 
492                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
493
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 && !_model->empty()) {
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         // FIXME: assumes tempo never changes after start
634         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
635                         _session.engine().frame_rate(),
636                         _session.tempo_map().meter_at(_timeline_position));
637         
638         uint32_t delta_t = 0;
639         uint32_t size    = 0;
640         uint8_t* buf     = NULL;
641         int ret;
642         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
643                 
644                 ev.set(buf, size, 0.0);
645                 time += delta_t;
646                 
647                 if (ret > 0) { // didn't skip (meta) event
648                         // make ev.time absolute time in frames
649                         ev.time() = time * frames_per_beat / (double)ppqn();
650                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
651                         _model->append(ev);
652                 }
653
654                 if (ev.size() > scratch_size) {
655                         scratch_size = ev.size();
656                 } else {
657                         ev.size() = scratch_size;
658                 }
659         }
660
661         set_default_controls_interpolation();
662         
663         _model->end_write(false);
664         _model->set_edited(false);
665
666         free(buf);
667 }
668
669 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
670
671 void
672 SMFSource::set_default_controls_interpolation()
673 {
674         // set interpolation style to defaults, can be changed by the GUI later
675         Evoral::ControlSet::Controls controls = _model->controls();
676         for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
677                 (*c).second->list()->set_interpolation(
678                         // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
679                         #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
680                         EventTypeMap::instance().interpolation_of((*c).first));
681                         #else
682                         Evoral::ControlList::Discrete);
683                         #endif
684         }
685 }
686
687
688 void
689 SMFSource::destroy_model()
690 {
691         //cerr << _name << " destroying model " << _model.get() << endl;
692         _model.reset();
693 }
694
695 void
696 SMFSource::flush_midi()
697 {
698         Evoral::SMF::end_write();
699 }
700