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