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