Tidy.
[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<double> ()
54         , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
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<double>& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
129 {
130         //cerr << "SMF read_unlocked " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
131
132         // 64 bits ought to be enough for anybody
133         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
134
135         _read_data_count = 0;
136
137         // Output parameters for read_event (which will allocate scratch in buffer as needed)
138         uint32_t ev_delta_t = 0;
139         uint32_t ev_type = 0;
140         uint32_t ev_size = 0;
141         uint8_t* ev_buffer = 0;
142
143         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
144
145         // FIXME: don't seek to start and search every read (brutal!)
146         Evoral::SMF<double>::seek_to_start();
147         
148         // FIXME: assumes tempo never changes after start
149         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
150                         _session.engine().frame_rate(),
151                         _session.tempo_map().meter_at(_timeline_position));
152         
153         const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * ppqn());
154
155         while (!Evoral::SMF<double>::eof()) {
156                 int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
157                 if (ret == -1) { // EOF
158                         //cerr << "SMF - EOF\n";
159                         break;
160                 }
161                 
162                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
163                 
164                 time += ev_delta_t; // accumulate delta time
165
166                 if (ret == 0) { // meta-event (skipped, just accumulate time)
167                         //cerr << "SMF - META\n";
168                         continue;
169                 }
170
171                 if (time >= start_ticks) {
172                         const nframes_t ev_frame_time = (nframes_t)(
173                                         ((time / (double)ppqn()) * frames_per_beat)) + stamp_offset;
174
175                         if (ev_frame_time <= start + cnt)
176                                 dst.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
177                         else
178                                 break;
179                 }
180
181                 _read_data_count += ev_size;
182
183                 if (ev_size > scratch_size)
184                         scratch_size = ev_size;
185                 else
186                         ev_size = scratch_size; // minimize realloc in read_event
187         }
188         
189         return cnt;
190 }
191
192 /** All stamps in audio frames */
193 nframes_t
194 SMFSource::write_unlocked (MidiRingBuffer<double>& src, nframes_t cnt)
195 {
196         _write_data_count = 0;
197                 
198         double            time;
199         Evoral::EventType type;
200         uint32_t          size;
201
202         size_t buf_capacity = 4;
203         uint8_t* buf = (uint8_t*)malloc(buf_capacity);
204         
205         if (_model && ! _model->writing())
206                 _model->start_write();
207
208         Evoral::MIDIEvent<double> ev(0, 0.0, 4, NULL, true);
209
210         while (true) {
211                 bool ret = src.peek_time(&time);
212                 if (!ret || time - _timeline_position > _length + cnt)
213                         break;
214
215                 ret = src.read_prefix(&time, &type, &size);
216                 if (!ret)
217                         break;
218
219                 if (size > buf_capacity) {
220                         buf_capacity = size;
221                         buf = (uint8_t*)realloc(buf, size);
222                 }
223
224                 ret = src.read_contents(size, buf);
225                 if (!ret) {
226                         cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
227                         break;
228                 }
229                 
230                 assert(time >= _timeline_position);
231                 time -= _timeline_position;
232                 
233                 ev.set(buf, size, time);
234                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
235                 if (! (ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex()) ) {
236                         cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type " << std::hex << int(ev.buffer()[0]) << endl;
237                         continue;
238                 }
239                 
240                 append_event_unlocked(Frames, ev);
241
242                 if (_model) {
243                         _model->append(ev);
244                 }
245         }
246
247         if (_model) {
248                 set_default_controls_interpolation();
249         }
250
251         Evoral::SMF<double>::flush();
252         free(buf);
253
254         const nframes_t oldlen = _length;
255         update_length(oldlen, cnt);
256
257         ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
258         
259         return cnt;
260 }
261                 
262
263 void
264 SMFSource::append_event_unlocked(EventTimeUnit unit, const Evoral::Event<double>& ev)
265 {
266         if (ev.size() == 0)  {
267                 cerr << "SMFSource: Warning: skipping empty event" << endl;
268                 return;
269         }
270
271         /*
272         printf("SMFSource: %s - append_event_unlocked time = %lf, size = %u, data = ",
273                         name().c_str(), ev.time(), ev.size()); 
274         for (size_t i=0; i < ev.size(); ++i) {
275                 printf("%X ", ev.buffer()[i]);
276         }
277         printf("\n");
278         */
279         
280         assert(ev.time() >= 0);
281         
282         if (ev.time() < last_event_time()) {
283                 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
284                 return;
285         }
286         
287         uint32_t delta_time = 0;
288         
289         if (unit == Frames) {
290                 // FIXME: assumes tempo never changes after start
291                 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
292                                 _session.engine().frame_rate(),
293                                 _session.tempo_map().meter_at(_timeline_position));
294
295                 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
296         } else {
297                 assert(unit == Beats);
298                 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
299         }
300
301         Evoral::SMF<double>::append_event_delta(delta_time, ev.size(), ev.buffer());
302         _last_ev_time = ev.time();
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         Evoral::SMF<double>::begin_write ();
358         _last_ev_time = 0;
359 }
360
361 void
362 SMFSource::mark_streaming_write_completed ()
363 {
364         MidiSource::mark_streaming_write_completed();
365
366         if (!writable()) {
367                 return;
368         }
369         
370         _model->set_edited(false);
371         Evoral::SMF<double>::end_write ();
372 }
373
374 void
375 SMFSource::mark_take (string id)
376 {
377         if (writable()) {
378                 _take_id = id;
379         }
380 }
381
382 int
383 SMFSource::move_to_trash (const string trash_dir_name)
384 {
385         string newpath;
386
387         if (!writable()) {
388                 return -1;
389         }
390
391         /* don't move the file across filesystems, just
392            stick it in the 'trash_dir_name' directory
393            on whichever filesystem it was already on.
394         */
395
396         newpath = Glib::path_get_dirname (_path);
397         newpath = Glib::path_get_dirname (newpath);
398
399         newpath += '/';
400         newpath += trash_dir_name;
401         newpath += '/';
402         newpath += Glib::path_get_basename (_path);
403
404         if (access (newpath.c_str(), F_OK) == 0) {
405
406                 /* the new path already exists, try versioning */
407                 
408                 char buf[PATH_MAX+1];
409                 int version = 1;
410                 string newpath_v;
411
412                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
413                 newpath_v = buf;
414
415                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
416                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
417                         newpath_v = buf;
418                 }
419                 
420                 if (version == 999) {
421                         PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
422                                           newpath)
423                               << endmsg;
424                 } else {
425                         newpath = newpath_v;
426                 }
427
428         } else {
429
430                 /* it doesn't exist, or we can't read it or something */
431
432         }
433
434         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
435                 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
436                                   _path, newpath, strerror (errno))
437                       << endmsg;
438                 return -1;
439         }
440 #if 0
441         if (::unlink (peakpath.c_str()) != 0) {
442                 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
443                                   peakpath, _path, strerror (errno))
444                       << endmsg;
445                 /* try to back out */
446                 rename (newpath.c_str(), _path.c_str());
447                 return -1;
448         }
449             
450         _path = newpath;
451         peakpath = "";
452 #endif  
453         /* file can not be removed twice, since the operation is not idempotent */
454
455         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
456
457         return 0;
458 }
459
460 bool
461 SMFSource::safe_file_extension(const Glib::ustring& file)
462 {
463         return (file.rfind(".mid") != Glib::ustring::npos);
464 }
465
466 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
467 bool
468 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
469 {
470         string::size_type pos;
471         bool ret = false;
472
473         isnew = false;
474
475         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
476
477         if ((pos = pathstr.find_last_of (':')) == string::npos) {
478                 pathstr = pathstr;
479         } else {
480                 pathstr = pathstr.substr (0, pos);
481         }
482
483         if (pathstr[0] != '/') {
484
485                 /* non-absolute pathname: find pathstr in search path */
486
487                 vector<string> dirs;
488                 int cnt;
489                 string fullpath;
490                 string keeppath;
491
492                 if (_search_path.length() == 0) {
493                         PBD::error << _("FileSource: search path not set") << endmsg;
494                         goto out;
495                 }
496
497                 split (_search_path, dirs, ':');
498
499                 cnt = 0;
500                 
501                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
502
503                         fullpath = *i;
504                         if (fullpath[fullpath.length()-1] != '/') {
505                                 fullpath += '/';
506                         }
507                         fullpath += pathstr;
508                         
509                         if (access (fullpath.c_str(), R_OK) == 0) {
510                                 keeppath = fullpath;
511                                 ++cnt;
512                         } 
513                 }
514
515                 if (cnt > 1) {
516
517                         PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
518                         goto out;
519
520                 } else if (cnt == 0) {
521
522                         if (must_exist) {
523                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
524                                 goto out;
525                         } else {
526                                 isnew = true;
527                         }
528                 }
529                 
530                 _name = pathstr;
531                 _path = keeppath;
532                 ret = true;
533
534         } else {
535                 
536                 /* external files and/or very very old style sessions include full paths */
537                 
538                 _path = pathstr;
539                 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
540                 
541                 if (access (_path.c_str(), R_OK) != 0) {
542
543                         /* file does not exist or we cannot read it */
544
545                         if (must_exist) {
546                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
547                                 goto out;
548                         }
549                         
550                         if (errno != ENOENT) {
551                                 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
552                                 goto out;
553                         }
554                         
555                         /* a new file */
556
557                         isnew = true;
558                         ret = true;
559
560                 } else {
561                         
562                         /* already exists */
563
564                         ret = true;
565                 }
566         }
567         
568   out:
569         return ret;
570 }
571
572 void
573 SMFSource::set_search_path (string p)
574 {
575         _search_path = p;
576 }
577
578
579 void
580 SMFSource::set_allow_remove_if_empty (bool yn)
581 {
582         if (writable()) {
583                 _allow_remove_if_empty = yn;
584         }
585 }
586
587 int
588 SMFSource::set_source_name (string newname, bool destructive)
589 {
590         //Glib::Mutex::Lock lm (_lock); FIXME
591         string oldpath = _path;
592         string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
593
594         if (newpath.empty()) {
595                 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
596                 return -1;
597         }
598
599         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
600                 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
601                 return -1;
602         }
603
604         _name = Glib::path_get_basename (newpath);
605         _path = newpath;
606
607         return 0;//rename_peakfile (peak_path (_path));
608 }
609
610 void
611 SMFSource::load_model(bool lock, bool force_reload)
612 {
613         if (_writing) {
614                 return;
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         Evoral::SMF<double>::seek_to_start();
636
637         uint64_t time = 0; /* in SMF ticks */
638         Evoral::Event<double> 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 / (double)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         set_default_controls_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::set_default_controls_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         Evoral::SMF<double>::end_write();
708 }
709