Trim include dependency graph, especially for io.h and session.h.
[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                 return;
271
272         /*printf("SMFSource: %s - append_event_unlocked chan = %u, time = %lf, size = %u, data = ",
273                         name().c_str(), (unsigned)ev.channel(), 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         assert(ev.time() >= 0);
280         
281         if (ev.time() < last_event_time()) {
282                 cerr << "SMFSource: Warning: Skipping event with ev.time() < last.time()" << endl;
283                 return;
284         }
285         
286         uint32_t delta_time = 0;
287         
288         if (unit == Frames) {
289                 // FIXME: assumes tempo never changes after start
290                 const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
291                                 _session.engine().frame_rate(),
292                                 _session.tempo_map().meter_at(_timeline_position));
293
294                 delta_time = (uint32_t)((ev.time() - last_event_time()) / frames_per_beat * ppqn());
295         } else {
296                 assert(unit == Beats);
297                 delta_time = (uint32_t)((ev.time() - last_event_time()) * ppqn());
298         }
299
300         SMF::append_event_unlocked(delta_time, ev);
301
302         _write_data_count += ev.size();
303 }
304
305
306 XMLNode&
307 SMFSource::get_state ()
308 {
309         XMLNode& root (MidiSource::get_state());
310         char buf[16];
311         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
312         root.add_property ("flags", buf);
313         return root;
314 }
315
316 int
317 SMFSource::set_state (const XMLNode& node)
318 {
319         const XMLProperty* prop;
320
321         if (MidiSource::set_state (node)) {
322                 return -1;
323         }
324
325         if ((prop = node.property (X_("flags"))) != 0) {
326
327                 int ival;
328                 sscanf (prop->value().c_str(), "0x%x", &ival);
329                 _flags = Flag (ival);
330
331         } else {
332
333                 _flags = Flag (0);
334
335         }
336
337         assert(_name.find("/") == string::npos);
338
339         return 0;
340 }
341
342 void
343 SMFSource::mark_for_remove ()
344 {
345         if (!writable()) {
346                 return;
347         }
348         _flags = Flag (_flags | RemoveAtDestroy);
349 }
350
351 void
352 SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
353 {
354         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
355         SMF::begin_write (start_frame);
356 }
357
358 void
359 SMFSource::mark_streaming_write_completed ()
360 {
361         MidiSource::mark_streaming_write_completed();
362
363         if (!writable()) {
364                 return;
365         }
366         
367         _model->set_edited(false);
368         SMF::end_write ();
369 }
370
371 void
372 SMFSource::mark_take (string id)
373 {
374         if (writable()) {
375                 _take_id = id;
376         }
377 }
378
379 int
380 SMFSource::move_to_trash (const string trash_dir_name)
381 {
382         string newpath;
383
384         if (!writable()) {
385                 return -1;
386         }
387
388         /* don't move the file across filesystems, just
389            stick it in the 'trash_dir_name' directory
390            on whichever filesystem it was already on.
391         */
392
393         newpath = Glib::path_get_dirname (_path);
394         newpath = Glib::path_get_dirname (newpath);
395
396         newpath += '/';
397         newpath += trash_dir_name;
398         newpath += '/';
399         newpath += Glib::path_get_basename (_path);
400
401         if (access (newpath.c_str(), F_OK) == 0) {
402
403                 /* the new path already exists, try versioning */
404                 
405                 char buf[PATH_MAX+1];
406                 int version = 1;
407                 string newpath_v;
408
409                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
410                 newpath_v = buf;
411
412                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
413                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
414                         newpath_v = buf;
415                 }
416                 
417                 if (version == 999) {
418                         PBD::error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
419                                           newpath)
420                               << endmsg;
421                 } else {
422                         newpath = newpath_v;
423                 }
424
425         } else {
426
427                 /* it doesn't exist, or we can't read it or something */
428
429         }
430
431         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
432                 PBD::error << string_compose (_("cannot rename midi file source from %1 to %2 (%3)"),
433                                   _path, newpath, strerror (errno))
434                       << endmsg;
435                 return -1;
436         }
437 #if 0
438         if (::unlink (peakpath.c_str()) != 0) {
439                 PBD::error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
440                                   peakpath, _path, strerror (errno))
441                       << endmsg;
442                 /* try to back out */
443                 rename (newpath.c_str(), _path.c_str());
444                 return -1;
445         }
446             
447         _path = newpath;
448         peakpath = "";
449 #endif  
450         /* file can not be removed twice, since the operation is not idempotent */
451
452         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
453
454         return 0;
455 }
456
457 bool
458 SMFSource::safe_file_extension(const Glib::ustring& file)
459 {
460         return (file.rfind(".mid") != Glib::ustring::npos);
461 }
462
463 // FIXME: Merge this with audiofilesource somehow (make a generic filesource?)
464 bool
465 SMFSource::find (string pathstr, bool must_exist, bool& isnew)
466 {
467         string::size_type pos;
468         bool ret = false;
469
470         isnew = false;
471
472         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
473
474         if ((pos = pathstr.find_last_of (':')) == string::npos) {
475                 pathstr = pathstr;
476         } else {
477                 pathstr = pathstr.substr (0, pos);
478         }
479
480         if (pathstr[0] != '/') {
481
482                 /* non-absolute pathname: find pathstr in search path */
483
484                 vector<string> dirs;
485                 int cnt;
486                 string fullpath;
487                 string keeppath;
488
489                 if (_search_path.length() == 0) {
490                         PBD::error << _("FileSource: search path not set") << endmsg;
491                         goto out;
492                 }
493
494                 split (_search_path, dirs, ':');
495
496                 cnt = 0;
497                 
498                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
499
500                         fullpath = *i;
501                         if (fullpath[fullpath.length()-1] != '/') {
502                                 fullpath += '/';
503                         }
504                         fullpath += pathstr;
505                         
506                         if (access (fullpath.c_str(), R_OK) == 0) {
507                                 keeppath = fullpath;
508                                 ++cnt;
509                         } 
510                 }
511
512                 if (cnt > 1) {
513
514                         PBD::error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, _search_path) << endmsg;
515                         goto out;
516
517                 } else if (cnt == 0) {
518
519                         if (must_exist) {
520                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, _search_path) << endmsg;
521                                 goto out;
522                         } else {
523                                 isnew = true;
524                         }
525                 }
526                 
527                 _name = pathstr;
528                 _path = keeppath;
529                 ret = true;
530
531         } else {
532                 
533                 /* external files and/or very very old style sessions include full paths */
534                 
535                 _path = pathstr;
536                 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
537                 
538                 if (access (_path.c_str(), R_OK) != 0) {
539
540                         /* file does not exist or we cannot read it */
541
542                         if (must_exist) {
543                                 PBD::error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
544                                 goto out;
545                         }
546                         
547                         if (errno != ENOENT) {
548                                 PBD::error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
549                                 goto out;
550                         }
551                         
552                         /* a new file */
553
554                         isnew = true;
555                         ret = true;
556
557                 } else {
558                         
559                         /* already exists */
560
561                         ret = true;
562                 }
563         }
564         
565   out:
566         return ret;
567 }
568
569 void
570 SMFSource::set_search_path (string p)
571 {
572         _search_path = p;
573 }
574
575
576 void
577 SMFSource::set_allow_remove_if_empty (bool yn)
578 {
579         if (writable()) {
580                 _allow_remove_if_empty = yn;
581         }
582 }
583
584 int
585 SMFSource::set_source_name (string newname, bool destructive)
586 {
587         //Glib::Mutex::Lock lm (_lock); FIXME
588         string oldpath = _path;
589         string newpath = Session::change_midi_path_by_name (oldpath, _name, newname, destructive);
590
591         if (newpath.empty()) {
592                 PBD::error << string_compose (_("programming error: %1"), "cannot generate a changed midi path") << endmsg;
593                 return -1;
594         }
595
596         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
597                 PBD::error << string_compose (_("cannot rename midi file for %1 to %2"), _name, newpath) << endmsg;
598                 return -1;
599         }
600
601         _name = Glib::path_get_basename (newpath);
602         _path = newpath;
603
604         return 0;//rename_peakfile (peak_path (_path));
605 }
606
607 void
608 SMFSource::load_model(bool lock, bool force_reload)
609 {
610         if (_writing) {
611                 return;
612         }
613         
614
615         if (lock) {
616                 Glib::Mutex::Lock lm (_lock);
617         }
618
619         if (_model && !force_reload && !_model->empty()) {
620                 return;
621         }
622
623         if (! _model) {
624                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
625                 cerr << _name << " loaded new model " << _model.get() << endl;
626         } else {
627                 cerr << _name << " reloading model " << _model.get()
628                         << " (" << _model->n_notes() << " notes)" <<endl;
629                 _model->clear();
630         }
631
632         _model->start_write();
633         SMF::seek_to_start();
634
635         uint64_t time = 0; /* in SMF ticks */
636         Evoral::Event ev;
637         
638         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
639         
640         // FIXME: assumes tempo never changes after start
641         const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
642                         _session.engine().frame_rate(),
643                         _session.tempo_map().meter_at(_timeline_position));
644         
645         uint32_t delta_t = 0;
646         uint32_t size    = 0;
647         uint8_t* buf     = NULL;
648         int ret;
649         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
650                 
651                 ev.set(buf, size, 0.0);
652                 time += delta_t;
653                 
654                 if (ret > 0) { // didn't skip (meta) event
655                         // make ev.time absolute time in frames
656                         ev.time() = time * frames_per_beat / (Evoral::EventTime)ppqn();
657                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
658                         _model->append(ev);
659                 }
660
661                 if (ev.size() > scratch_size) {
662                         scratch_size = ev.size();
663                 } else {
664                         ev.size() = scratch_size;
665                 }
666         }
667
668         make_sure_controls_have_the_right_interpolation();
669         
670         _model->end_write(false);
671         _model->set_edited(false);
672
673         free(buf);
674 }
675
676 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
677
678 void
679 SMFSource::make_sure_controls_have_the_right_interpolation()
680 {
681         // set interpolation style to defaults, can be changed by the GUI later
682         Evoral::ControlSet::Controls controls = _model->controls();
683         for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
684                 (*c).second->list()->set_interpolation(
685                         // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
686                         #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
687                         EventTypeMap::instance().interpolation_of((*c).first));
688                         #else
689                         Evoral::ControlList::Discrete);
690                         #endif
691         }
692 }
693
694
695 void
696 SMFSource::destroy_model()
697 {
698         //cerr << _name << " destroying model " << _model.get() << endl;
699         _model.reset();
700 }
701
702 void
703 SMFSource::flush_midi()
704 {
705         SMF::end_write();
706 }
707