Commit of the century, right here.
[ardour.git] / libs / ardour / smf_source.cc
1 /*
2     Copyright (C) 2006 Paul Davis 
3         Written by Dave Robillard, 2006
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <vector>
22
23 #include <sys/time.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <errno.h>
27
28 #include <pbd/mountpoint.h>
29 #include <pbd/pathscanner.h>
30 #include <pbd/stl_delete.h>
31 #include <pbd/strsplit.h>
32
33 #include <glibmm/miscutils.h>
34
35 #include <evoral/SMFReader.hpp>
36 #include <evoral/Control.hpp>
37
38 #include <ardour/smf_source.h>
39 #include <ardour/session.h>
40 #include <ardour/midi_ring_buffer.h>
41 #include <ardour/tempo.h>
42 #include <ardour/audioengine.h>
43 #include <ardour/event_type_map.h>
44
45 #include "i18n.h"
46
47 using namespace ARDOUR;
48
49 string SMFSource::_search_path;
50
51 SMFSource::SMFSource(Session& s, std::string path, Flag flags)
52         : MidiSource(s, region_name_from_path(path, false))
53         , Evoral::SMF()
54         , _flags(flags)
55         , _allow_remove_if_empty(true)
56         , _last_ev_time(0)
57 {
58         /* Constructor used for new internal-to-session files.  File cannot exist. */
59
60         if (init(path, false)) {
61                 throw failed_constructor ();
62         }
63         
64         if (create(path)) {
65                 throw failed_constructor ();
66         }
67
68         assert(_name.find("/") == string::npos);
69 }
70
71 SMFSource::SMFSource(Session& s, const XMLNode& node)
72         : MidiSource(s, node)
73         , _flags(Flag(Writable|CanRename))
74         , _allow_remove_if_empty(true)
75         , _last_ev_time(0)
76 {
77         /* Constructor used for existing internal-to-session files.  File must exist. */
78
79         if (set_state(node)) {
80                 throw failed_constructor ();
81         }
82         
83         if (init(_name, true)) {
84                 throw failed_constructor ();
85         }
86         
87         if (open(_path)) {
88                 throw failed_constructor ();
89         }
90         
91         assert(_name.find("/") == string::npos);
92 }
93
94 SMFSource::~SMFSource ()
95 {
96         if (removable()) {
97                 unlink (_path.c_str());
98         }
99 }
100
101 bool
102 SMFSource::removable () const
103 {
104         return (_flags & Removable) && ((_flags & RemoveAtDestroy) ||
105                         ((_flags & RemovableIfEmpty) && is_empty()));
106 }
107
108 int
109 SMFSource::init (string pathstr, bool must_exist)
110 {
111         bool is_new = false;
112
113         if (!find (pathstr, must_exist, is_new)) {
114                 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
115                 return -1;
116         }
117
118         if (is_new && must_exist) {
119                 return -1;
120         }
121
122         assert(_name.find("/") == string::npos);
123         return 0;
124 }
125
126 /** All stamps in audio frames */
127 nframes_t
128 SMFSource::read_unlocked (MidiRingBuffer<nframes_t>& dst, nframes_t start, nframes_t dur,
129                 nframes_t stamp_offset, nframes_t negative_stamp_offset) const
130 {
131         //cerr << "SMF read_unlocked " << name() << " read "
132         //<< start << ", count=" << dur << ", offset=" << stamp_offset << endl;
133
134         int ret;
135         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
136
137         _read_data_count = 0;
138
139         // Output parameters for read_event (which will allocate scratch in buffer as needed)
140         uint32_t ev_delta_t = 0;
141         uint32_t ev_type    = 0;
142         uint32_t ev_size    = 0;
143         uint8_t* ev_buffer  = 0;
144
145         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
146
147         // FIXME: assumes tempo never changes after start
148         const Tempo& tempo = _session.tempo_map().tempo_at(_timeline_position);
149         
150         const double frames_per_beat = tempo.frames_per_beat(
151                         _session.engine().frame_rate(),
152                         _session.tempo_map().meter_at(_timeline_position));
153         
154         const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
155
156         if (_last_read_end == 0 || start != _last_read_end) {
157                 cerr << "SMFSource::read_unlocked seeking to " << start << endl;
158                 Evoral::SMF::seek_to_start();
159                 while (time < start_ticks) {
160                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
161                         if (ret == -1) { // EOF
162                                 _last_read_end = start + dur;
163                                 return dur;
164                         }
165                         time += ev_delta_t; // accumulate delta time
166                 }
167         }
168         
169         _last_read_end = start + dur;
170
171         while (!Evoral::SMF::eof()) {
172                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
173                 if (ret == -1) { // EOF
174                         break;
175                 }
176                 
177                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
178                 
179                 time += ev_delta_t; // accumulate delta time
180
181                 if (ret == 0) { // meta-event (skipped, just accumulate time)
182                         continue;
183                 }
184
185                 assert(time >= start_ticks);
186                 const nframes_t ev_frame_time = (nframes_t)(
187                                 ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
188
189                 if (ev_frame_time < start + dur) {
190                         dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
191                 } else {
192                         break;
193                 }
194
195                 _read_data_count += ev_size;
196
197                 if (ev_size > scratch_size) {
198                         scratch_size = ev_size;
199                 }
200                 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 cnt)
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<double> 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 + cnt) {
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                 if (_model) {
261                         _model->append(ev);
262                 }
263         }
264
265         if (_model) {
266                 set_default_controls_interpolation();
267         }
268
269         Evoral::SMF::flush();
270         free(buf);
271
272         const nframes_t oldlen = _length;
273         update_length(oldlen, cnt);
274
275         ViewDataRangeReady(_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
276         
277         return cnt;
278 }
279                 
280
281 void
282 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event<double>& ev)
283 {
284         if (ev.size() == 0)  {
285                 cerr << "SMFSource: Warning: skipping empty event" << endl;
286                 return;
287         }
288
289         /*
290         printf("SMFSource: %s - append_event_unlocked time = %lf, size = %u, data = ",
291                         name().c_str(), ev.time(), ev.size()); 
292         for (size_t i=0; i < ev.size(); ++i) {
293                 printf("%X ", ev.buffer()[i]);
294         } printf("\n");
295         */
296         
297         assert(ev.time() >= 0);
298         
299         if (ev.time() < last_event_time()) {
300                 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
301                 return;
302         }
303         
304         uint32_t delta_time = 0;
305         
306         if (unit == Frames) {
307                 // FIXME: assumes tempo never changes after start
308                 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
309                                 _session.engine().frame_rate(),
310                                 _session.tempo_map().meter_at(_timeline_position));
311
312                 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
313         } else {
314                 assert(unit == Beats);
315                 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
316         }
317
318         Evoral::SMF::append_event_delta(delta_time, ev.size(), ev.buffer());
319         _last_ev_time = ev.time();
320
321         _write_data_count += ev.size();
322 }
323
324
325 XMLNode&
326 SMFSource::get_state ()
327 {
328         XMLNode& root (MidiSource::get_state());
329         char buf[16];
330         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
331         root.add_property ("flags", buf);
332         return root;
333 }
334
335 int
336 SMFSource::set_state (const XMLNode& node)
337 {
338         const XMLProperty* prop;
339
340         if (MidiSource::set_state (node)) {
341                 return -1;
342         }
343
344         if ((prop = node.property (X_("flags"))) != 0) {
345                 int ival;
346                 sscanf (prop->value().c_str(), "0x%x", &ival);
347                 _flags = Flag (ival);
348         } else {
349                 _flags = Flag (0);
350         }
351
352         assert(_name.find("/") == string::npos);
353
354         return 0;
355 }
356
357 void
358 SMFSource::mark_for_remove ()
359 {
360         if (!writable()) {
361                 return;
362         }
363         _flags = Flag (_flags | RemoveAtDestroy);
364 }
365
366 void
367 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
368 {
369         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
370         Evoral::SMF::begin_write ();
371         _last_ev_time = 0;
372 }
373
374 void
375 SMFSource::mark_streaming_write_completed ()
376 {
377         MidiSource::mark_streaming_write_completed();
378
379         if (!writable()) {
380                 return;
381         }
382         
383         _model->set_edited(false);
384         Evoral::SMF::end_write ();
385 }
386
387 void
388 SMFSource::mark_take (string id)
389 {
390         if (writable()) {
391                 _take_id = id;
392         }
393 }
394
395 int
396 SMFSource::move_to_trash (const string trash_dir_name)
397 {
398         string newpath;
399
400         if (!writable()) {
401                 return -1;
402         }
403
404         /* don't move the file across filesystems, just
405            stick it in the 'trash_dir_name' directory
406            on whichever filesystem it was already on.
407         */
408
409         newpath = Glib::path_get_dirname (_path);
410         newpath = Glib::path_get_dirname (newpath);
411
412         newpath += '/';
413         newpath += trash_dir_name;
414         newpath += '/';
415         newpath += Glib::path_get_basename (_path);
416
417         if (access (newpath.c_str(), F_OK) == 0) {
418
419                 /* the new path already exists, try versioning */
420                 
421                 char buf[PATH_MAX+1];
422                 int version = 1;
423                 string newpath_v;
424
425                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
426                 newpath_v = buf;
427
428                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
429                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
430                         newpath_v = buf;
431                 }
432                 
433                 if (version == 999) {
434                         PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
435                                           newpath)
436                               << endmsg;
437                 } else {
438                         newpath = newpath_v;
439                 }
440
441         } else {
442
443                 /* it doesn't exist, or we can't read it or something */
444
445         }
446
447         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
448                 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
449                                   _path, newpath, strerror (errno))
450                       << endmsg;
451                 return -1;
452         }
453         
454         /* file can not be removed twice, since the operation is not idempotent */
455
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         string::size_type pos;
472         bool ret = false;
473
474         isnew = false;
475
476         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
477
478         if ((pos = pathstr.find_last_of (':')) == string::npos) {
479                 pathstr = pathstr;
480         } else {
481                 pathstr = pathstr.substr (0, pos);
482         }
483
484         if (pathstr[0] != '/') {
485
486                 /* non-absolute pathname: find pathstr in search path */
487
488                 vector<string> dirs;
489                 int cnt;
490                 string fullpath;
491                 string keeppath;
492
493                 if (_search_path.length() == 0) {
494                         PBD::error << _("FileSource: search path not set") << endmsg;
495                         goto out;
496                 }
497
498                 split (_search_path, dirs, ':');
499
500                 cnt = 0;
501                 
502                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
503
504                         fullpath = *i;
505                         if (fullpath[fullpath.length()-1] != '/') {
506                                 fullpath += '/';
507                         }
508                         fullpath += pathstr;
509                         
510                         if (access (fullpath.c_str(), R_OK) == 0) {
511                                 keeppath = fullpath;
512                                 ++cnt;
513                         } 
514                 }
515
516                 if (cnt > 1) {
517
518                         PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
519                         goto out;
520
521                 } else if (cnt == 0) {
522
523                         if (must_exist) {
524                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
525                                 goto out;
526                         } else {
527                                 isnew = true;
528                         }
529                 }
530                 
531                 _name = pathstr;
532                 _path = keeppath;
533                 ret = true;
534
535         } else {
536                 
537                 /* external files and/or very very old style sessions include full paths */
538                 
539                 _path = pathstr;
540                 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
541                 
542                 if (access (_path.c_str(), R_OK) != 0) {
543
544                         /* file does not exist or we cannot read it */
545
546                         if (must_exist) {
547                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
548                                 goto out;
549                         }
550                         
551                         if (errno != ENOENT) {
552                                 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
553                                 goto out;
554                         }
555                         
556                         /* a new file */
557
558                         isnew = true;
559                         ret = true;
560
561                 } else {
562                         
563                         /* already exists */
564
565                         ret = true;
566                 }
567         }
568         
569   out:
570         return ret;
571 }
572
573 void
574 SMFSource::set_search_path (string p)
575 {
576         _search_path = p;
577 }
578
579
580 void
581 SMFSource::set_allow_remove_if_empty (bool yn)
582 {
583         if (writable()) {
584                 _allow_remove_if_empty = yn;
585         }
586 }
587
588 int
589 SMFSource::set_source_name (string newname, bool destructive)
590 {
591         //Glib::Mutex::Lock lm (_lock); FIXME
592         string oldpath = _path;
593         string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
594
595         if (newpath.empty()) {
596                 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
597                 return -1;
598         }
599
600         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
601                 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
602                 return -1;
603         }
604
605         _name = Glib::path_get_basename (newpath);
606         _path = newpath;
607
608         return 0;
609 }
610
611 void
612 SMFSource::load_model(bool lock, bool force_reload)
613 {
614         if (_writing) {
615                 return;
616         }
617         
618         if (lock) {
619                 Glib::Mutex::Lock lm (_lock);
620         }
621
622         if (_model && !force_reload && !_model->empty()) {
623                 return;
624         }
625
626         if (! _model) {
627                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
628                 cerr << _name << " loaded new model " << _model.get() << endl;
629         } else {
630                 cerr << _name << " reloading model " << _model.get()
631                         << " (" << _model->n_notes() << " notes)" <<endl;
632                 _model->clear();
633         }
634
635         _model->start_write();
636         Evoral::SMF::seek_to_start();
637
638         uint64_t time = 0; /* in SMF ticks */
639         Evoral::Event<double> ev;
640         
641         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
642         
643         // FIXME: assumes tempo never changes after start
644         const Tempo& tempo = _session.tempo_map().tempo_at(_timeline_position);
645         
646         const double frames_per_beat = tempo.frames_per_beat(
647                         _session.engine().frame_rate(),
648                         _session.tempo_map().meter_at(_timeline_position));
649         
650         uint32_t delta_t = 0;
651         uint32_t size    = 0;
652         uint8_t* buf     = NULL;
653         int ret;
654         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
655                 ev.set(buf, size, 0.0);
656                 time += delta_t;
657                 
658                 if (ret > 0) { // didn't skip (meta) event
659                         // make ev.time absolute time in frames
660                         ev.time() = time * frames_per_beat / (double)ppqn();
661                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
662                         _model->append(ev);
663                 }
664
665                 if (ev.size() > scratch_size) {
666                         scratch_size = ev.size();
667                 }
668                 ev.size() = scratch_size; // ensure read_event only allocates if necessary
669         }
670
671         set_default_controls_interpolation();
672         
673         _model->end_write(false);
674         _model->set_edited(false);
675
676         free(buf);
677 }
678
679 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
680
681 void
682 SMFSource::set_default_controls_interpolation()
683 {
684         // set interpolation style to defaults, can be changed by the GUI later
685         Evoral::ControlSet::Controls controls = _model->controls();
686         for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
687                 (*c).second->list()->set_interpolation(
688                         // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
689                         #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
690                         EventTypeMap::instance().interpolation_of((*c).first));
691                         #else
692                         Evoral::ControlList::Discrete);
693                         #endif
694         }
695 }
696
697
698 void
699 SMFSource::destroy_model()
700 {
701         //cerr << _name << " destroying model " << _model.get() << endl;
702         _model.reset();
703 }
704
705 void
706 SMFSource::flush_midi()
707 {
708         Evoral::SMF::end_write();
709 }
710