Fix most absurd function name I've seen in a while.
[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         , Evoral::SMF<double> ()
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<double>& 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         Evoral::SMF<double>::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 (!Evoral::SMF<double>::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<double>& src, nframes_t cnt)
198 {
199         _write_data_count = 0;
200                 
201         double            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<double> 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                 set_default_controls_interpolation();
252         }
253
254         Evoral::SMF<double>::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<double>& ev)
268 {
269         if (ev.size() == 0)  {
270                 cerr << "SMFSource: Warning: skipping empty event" << endl;
271                 return;
272         }
273
274         /*
275         printf("SMFSource: %s - append_event_unlocked time = %lf, size = %u, data = ",
276                         name().c_str(), ev.time(), ev.size()); 
277         for (size_t i=0; i < ev.size(); ++i) {
278                 printf("%X ", ev.buffer()[i]);
279         }
280         printf("\n");
281         */
282         
283         assert(ev.time() >= 0);
284         
285         if (ev.time() < last_event_time()) {
286                 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
287                 return;
288         }
289         
290         uint32_t delta_time = 0;
291         
292         if (unit == Frames) {
293                 // FIXME: assumes tempo never changes after start
294                 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
295                                 _session.engine().frame_rate(),
296                                 _session.tempo_map().meter_at(_timeline_position));
297
298                 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
299         } else {
300                 assert(unit == Beats);
301                 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
302         }
303
304         Evoral::SMF<double>::append_event_delta(delta_time, ev);
305
306         _write_data_count += ev.size();
307 }
308
309
310 XMLNode&
311 SMFSource::get_state ()
312 {
313         XMLNode& root (MidiSource::get_state());
314         char buf[16];
315         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
316         root.add_property ("flags", buf);
317         return root;
318 }
319
320 int
321 SMFSource::set_state (const XMLNode& node)
322 {
323         const XMLProperty* prop;
324
325         if (MidiSource::set_state (node)) {
326                 return -1;
327         }
328
329         if ((prop = node.property (X_("flags"))) != 0) {
330
331                 int ival;
332                 sscanf (prop->value().c_str(), "0x%x", &ival);
333                 _flags = Flag (ival);
334
335         } else {
336
337                 _flags = Flag (0);
338
339         }
340
341         assert(_name.find("/") == string::npos);
342
343         return 0;
344 }
345
346 void
347 SMFSource::mark_for_remove ()
348 {
349         if (!writable()) {
350                 return;
351         }
352         _flags = Flag (_flags | RemoveAtDestroy);
353 }
354
355 void
356 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
357 {
358         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
359         Evoral::SMF<double>::begin_write ();
360 }
361
362 void
363 SMFSource::mark_streaming_write_completed ()
364 {
365         MidiSource::mark_streaming_write_completed();
366
367         if (!writable()) {
368                 return;
369         }
370         
371         _model->set_edited(false);
372         Evoral::SMF<double>::end_write ();
373 }
374
375 void
376 SMFSource::mark_take (string id)
377 {
378         if (writable()) {
379                 _take_id = id;
380         }
381 }
382
383 int
384 SMFSource::move_to_trash (const string trash_dir_name)
385 {
386         string newpath;
387
388         if (!writable()) {
389                 return -1;
390         }
391
392         /* don't move the file across filesystems, just
393            stick it in the 'trash_dir_name' directory
394            on whichever filesystem it was already on.
395         */
396
397         newpath = Glib::path_get_dirname (_path);
398         newpath = Glib::path_get_dirname (newpath);
399
400         newpath += '/';
401         newpath += trash_dir_name;
402         newpath += '/';
403         newpath += Glib::path_get_basename (_path);
404
405         if (access (newpath.c_str(), F_OK) == 0) {
406
407                 /* the new path already exists, try versioning */
408                 
409                 char buf[PATH_MAX+1];
410                 int version = 1;
411                 string newpath_v;
412
413                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
414                 newpath_v = buf;
415
416                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
417                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
418                         newpath_v = buf;
419                 }
420                 
421                 if (version == 999) {
422                         PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
423                                           newpath)
424                               << endmsg;
425                 } else {
426                         newpath = newpath_v;
427                 }
428
429         } else {
430
431                 /* it doesn't exist, or we can't read it or something */
432
433         }
434
435         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
436                 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
437                                   _path, newpath, strerror (errno))
438                       << endmsg;
439                 return -1;
440         }
441 #if 0
442         if (::unlink (peakpath.c_str()) != 0) {
443                 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
444                                   peakpath, _path, strerror (errno))
445                       << endmsg;
446                 /* try to back out */
447                 rename (newpath.c_str(), _path.c_str());
448                 return -1;
449         }
450             
451         _path = newpath;
452         peakpath = "";
453 #endif  
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;//rename_peakfile (peak_path (_path));
609 }
610
611 void
612 SMFSource::load_model(bool lock, bool force_reload)
613 {
614         if (_writing) {
615                 return;
616         }
617         
618
619         if (lock) {
620                 Glib::Mutex::Lock lm (_lock);
621         }
622
623         if (_model && !force_reload && !_model->empty()) {
624                 return;
625         }
626
627         if (! _model) {
628                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
629                 cerr << _name << " loaded new model " << _model.get() << endl;
630         } else {
631                 cerr << _name << " reloading model " << _model.get()
632                         << " (" << _model->n_notes() << " notes)" <<endl;
633                 _model->clear();
634         }
635
636         _model->start_write();
637         Evoral::SMF<double>::seek_to_start();
638
639         uint64_t time = 0; /* in SMF ticks */
640         Evoral::Event<double> ev;
641         
642         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
643         
644         // FIXME: assumes tempo never changes after start
645         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
646                         _session.engine().frame_rate(),
647                         _session.tempo_map().meter_at(_timeline_position));
648         
649         uint32_t delta_t = 0;
650         uint32_t size    = 0;
651         uint8_t* buf     = NULL;
652         int ret;
653         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
654                 
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                 } else {
668                         ev.size() = scratch_size;
669                 }
670         }
671
672         set_default_controls_interpolation();
673         
674         _model->end_write(false);
675         _model->set_edited(false);
676
677         free(buf);
678 }
679
680 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
681
682 void
683 SMFSource::set_default_controls_interpolation()
684 {
685         // set interpolation style to defaults, can be changed by the GUI later
686         Evoral::ControlSet::Controls controls = _model->controls();
687         for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
688                 (*c).second->list()->set_interpolation(
689                         // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
690                         #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
691                         EventTypeMap::instance().interpolation_of((*c).first));
692                         #else
693                         Evoral::ControlList::Discrete);
694                         #endif
695         }
696 }
697
698
699 void
700 SMFSource::destroy_model()
701 {
702         //cerr << _name << " destroying model " << _model.get() << endl;
703         _model.reset();
704 }
705
706 void
707 SMFSource::flush_midi()
708 {
709         Evoral::SMF<double>::end_write();
710 }
711