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