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