prepare for upcoming Jadeo.app -> Xjadeo.app rename on OSX.
[ardour.git] / libs / ardour / smf_source.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3     Author: David Robillard
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 #include <regex.h>
28
29 #include "pbd/pathscanner.h"
30 #include "pbd/stl_delete.h"
31 #include "pbd/strsplit.h"
32
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
35
36 #include "evoral/Control.hpp"
37 #include "evoral/evoral/SMF.hpp"
38
39 #include "ardour/event_type_map.h"
40 #include "ardour/midi_model.h"
41 #include "ardour/midi_ring_buffer.h"
42 #include "ardour/midi_state_tracker.h"
43 #include "ardour/session.h"
44 #include "ardour/smf_source.h"
45 #include "ardour/debug.h"
46
47 #include "i18n.h"
48
49 using namespace ARDOUR;
50 using namespace Glib;
51 using namespace PBD;
52 using namespace Evoral;
53
54 /** Constructor used for new internal-to-session files.  File cannot exist. */
55 SMFSource::SMFSource (Session& s, const string& path, Source::Flag flags)
56         : Source(s, DataType::MIDI, path, flags)
57         , MidiSource(s, path, flags)
58         , FileSource(s, DataType::MIDI, path, string(), flags)
59         , Evoral::SMF()
60         , _last_ev_time_beats(0.0)
61         , _last_ev_time_frames(0)
62         , _smf_last_read_end (0)
63         , _smf_last_read_time (0)
64 {
65         /* note that origin remains empty */
66
67         if (init (_path, false)) {
68                 throw failed_constructor ();
69         }
70  
71         assert (!Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
72         existence_check ();
73
74         /* file is not opened until write */
75
76         if (flags & Writable) {
77                 return;
78         }
79
80         if (open (_path)) {
81                 throw failed_constructor ();
82         }
83
84         _open = true;
85 }
86
87 /** Constructor used for external-to-session files.  File must exist. */
88 SMFSource::SMFSource (Session& s, const string& path)
89         : Source(s, DataType::MIDI, path, Source::Flag (0))
90         , MidiSource(s, path, Source::Flag (0))
91         , FileSource(s, DataType::MIDI, path, string(), Source::Flag (0))
92         , Evoral::SMF()
93         , _last_ev_time_beats(0.0)
94         , _last_ev_time_frames(0)
95         , _smf_last_read_end (0)
96         , _smf_last_read_time (0)
97 {
98         /* note that origin remains empty */
99
100         if (init (_path, false)) {
101                 throw failed_constructor ();
102         }
103  
104         assert (Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
105         existence_check ();
106
107         /* file is not opened until write */
108
109         if (_flags & Writable) {
110                 return;
111         }
112
113         if (open (_path)) {
114                 throw failed_constructor ();
115         }
116
117         _open = true;
118 }
119
120 /** Constructor used for existing internal-to-session files. */
121 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
122         : Source(s, node)
123         , MidiSource(s, node)
124         , FileSource(s, node, must_exist)
125         , _last_ev_time_beats(0.0)
126         , _last_ev_time_frames(0)
127         , _smf_last_read_end (0)
128         , _smf_last_read_time (0)
129 {
130         if (set_state(node, Stateful::loading_state_version)) {
131                 throw failed_constructor ();
132         }
133
134         if (init (_path, true)) {
135                 throw failed_constructor ();
136         }
137
138         assert (Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
139         existence_check ();
140
141         if (open(_path)) {
142                 throw failed_constructor ();
143         }
144
145         _open = true;
146 }
147
148 SMFSource::~SMFSource ()
149 {
150         if (removable()) {
151                 unlink (_path.c_str());
152         }
153 }
154
155 int
156 SMFSource::open_for_write ()
157 {
158         if (create (_path)) {
159                 return -1;
160         }
161         _open = true;
162         return 0;
163 }
164
165 /** All stamps in audio frames */
166 framecnt_t
167 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination,
168                           framepos_t const               source_start,
169                           framepos_t                     start,
170                           framecnt_t                     duration,
171                           MidiStateTracker*              tracker) const
172 {
173         int      ret  = 0;
174         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
175
176         if (writable() && !_open) {
177                 /* nothing to read since nothing has ben written */
178                 return duration;
179         }
180
181         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
182
183         // Output parameters for read_event (which will allocate scratch in buffer as needed)
184         uint32_t ev_delta_t = 0;
185         uint32_t ev_type    = 0;
186         uint32_t ev_size    = 0;
187         uint8_t* ev_buffer  = 0;
188
189         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
190
191         BeatsFramesConverter converter(_session.tempo_map(), source_start);
192
193         const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
194         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
195
196         if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
197                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
198                 Evoral::SMF::seek_to_start();
199                 while (time < start_ticks) {
200                         gint ignored;
201
202                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
203                         if (ret == -1) { // EOF
204                                 _smf_last_read_end = start + duration;
205                                 return duration;
206                         }
207                         time += ev_delta_t; // accumulate delta time
208                 }
209         } else {
210                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
211                 time = _smf_last_read_time;
212         }
213
214         _smf_last_read_end = start + duration;
215
216         while (true) {
217                 gint ignored; /* XXX don't ignore note id's ??*/
218
219                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
220                 if (ret == -1) { // EOF
221                         break;
222                 }
223
224                 time += ev_delta_t; // accumulate delta time
225                 _smf_last_read_time = time;
226
227                 if (ret == 0) { // meta-event (skipped, just accumulate time)
228                         continue;
229                 }
230
231                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
232
233                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
234                                                                   ev_delta_t, time, ev_buffer[0], ev_type));
235
236                 assert(time >= start_ticks);
237
238                 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
239                    is in session frames.
240                 */
241                 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
242
243                 if (ev_frame_time < start + duration) {
244                         destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
245
246                         if (tracker) {
247                                 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
248                                         tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
249                                 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
250                                         tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
251                                 }
252                         }
253                 } else {
254                         break;
255                 }
256
257                 if (ev_size > scratch_size) {
258                         scratch_size = ev_size;
259                 }
260                 ev_size = scratch_size; // ensure read_event only allocates if necessary
261         }
262
263         return duration;
264 }
265
266 framecnt_t
267 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source,
268                            framepos_t                  position,
269                            framecnt_t                  cnt)
270 {
271         if (!_writing) {
272                 mark_streaming_write_started ();
273         }
274
275         framepos_t        time;
276         Evoral::EventType type;
277         uint32_t          size;
278
279         size_t   buf_capacity = 4;
280         uint8_t* buf          = (uint8_t*)malloc(buf_capacity);
281
282         if (_model && !_model->writing()) {
283                 _model->start_write();
284         }
285
286         Evoral::MIDIEvent<framepos_t> ev;
287         while (true) {
288                 /* Get the event time, in frames since session start but ignoring looping. */
289                 bool ret;
290                 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
291                         /* Ring is empty, no more events. */
292                         break;
293                 }
294
295                 if ((cnt != max_framecnt) &&
296                     (time > position + _capture_length + cnt)) {
297                         /* The diskstream doesn't want us to write everything, and this
298                            event is past the end of this block, so we're done for now. */
299                         break;
300                 }
301
302                 /* Read the time, type, and size of the event. */
303                 if (!(ret = source.read_prefix (&time, &type, &size))) {
304                         error << _("Unable to read event prefix, corrupt MIDI ring") << endmsg;
305                         break;
306                 }
307
308                 /* Enlarge body buffer if necessary now that we know the size. */
309                 if (size > buf_capacity) {
310                         buf_capacity = size;
311                         buf = (uint8_t*)realloc(buf, size);
312                 }
313
314                 /* Read the event body into buffer. */
315                 ret = source.read_contents(size, buf);
316                 if (!ret) {
317                         error << _("Event has time and size but no body, corrupt MIDI ring") << endmsg;
318                         break;
319                 }
320
321                 /* Convert event time from absolute to source relative. */
322                 if (time < position) {
323                         error << _("Event time is before MIDI source position") << endmsg;
324                         break;
325                 }
326                 time -= position;
327                         
328                 ev.set(buf, size, time);
329                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
330                 ev.set_id(Evoral::next_event_id());
331
332                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
333                         continue;
334                 }
335
336                 append_event_unlocked_frames(ev, position);
337         }
338
339         Evoral::SMF::flush ();
340         free (buf);
341
342         return cnt;
343 }
344
345 /** Append an event with a timestamp in beats (double) */
346 void
347 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
348 {
349         if (!_writing || ev.size() == 0)  {
350                 return;
351         }
352
353         /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
354                name().c_str(), ev.id(), ev.time(), ev.size());
355                for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
356
357         if (ev.time() < _last_ev_time_beats) {
358                 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
359                         << endmsg;
360                 return;
361         }
362
363         Evoral::event_id_t event_id;
364
365         if (ev.id() < 0) {
366                 event_id  = Evoral::next_event_id();
367         } else {
368                 event_id = ev.id();
369         }
370
371         if (_model) {
372                 _model->append (ev, event_id);
373         }
374
375         _length_beats = max(_length_beats, ev.time());
376
377         const double delta_time_beats   = ev.time() - _last_ev_time_beats;
378         const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
379
380         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
381         _last_ev_time_beats = ev.time();
382 }
383
384 /** Append an event with a timestamp in frames (framepos_t) */
385 void
386 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
387 {
388         if (!_writing || ev.size() == 0)  {
389                 return;
390         }
391
392         // printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
393         // name().c_str(), ev.id(), ev.time(), ev.size());
394         // for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");
395
396         if (ev.time() < _last_ev_time_frames) {
397                 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
398                         << endmsg;
399                 return;
400         }
401
402         BeatsFramesConverter converter(_session.tempo_map(), position);
403         const double ev_time_beats = converter.from(ev.time());
404         Evoral::event_id_t event_id;
405
406         if (ev.id() < 0) {
407                 event_id  = Evoral::next_event_id();
408         } else {
409                 event_id = ev.id();
410         }
411
412         if (_model) {
413                 const Evoral::Event<double> beat_ev (ev.event_type(),
414                                                      ev_time_beats,
415                                                      ev.size(),
416                                                      const_cast<uint8_t*>(ev.buffer()));
417                 _model->append (beat_ev, event_id);
418         }
419
420         _length_beats = max(_length_beats, ev_time_beats);
421
422         const Evoral::MusicalTime last_time_beats  = converter.from (_last_ev_time_frames);
423         const Evoral::MusicalTime delta_time_beats = ev_time_beats - last_time_beats;
424         const uint32_t            delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
425
426         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
427         _last_ev_time_frames = ev.time();
428 }
429
430 XMLNode&
431 SMFSource::get_state ()
432 {
433         XMLNode& node = MidiSource::get_state();
434         node.add_property (X_("origin"), _origin);
435         return node;
436 }
437
438 int
439 SMFSource::set_state (const XMLNode& node, int version)
440 {
441         if (Source::set_state (node, version)) {
442                 return -1;
443         }
444
445         if (MidiSource::set_state (node, version)) {
446                 return -1;
447         }
448
449         if (FileSource::set_state (node, version)) {
450                 return -1;
451         }
452
453         return 0;
454 }
455
456 void
457 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
458 {
459         /* CALLER MUST HOLD LOCK */
460
461         if (!_open && open_for_write()) {
462                 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
463                 /* XXX should probably throw or return something */
464                 return;
465         }
466
467         MidiSource::mark_streaming_midi_write_started (mode);
468         Evoral::SMF::begin_write ();
469         _last_ev_time_beats = 0.0;
470         _last_ev_time_frames = 0;
471 }
472
473 void
474 SMFSource::mark_streaming_write_completed ()
475 {
476         mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
477 }
478
479 void
480 SMFSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption stuck_notes_option, Evoral::MusicalTime when)
481 {
482         Glib::Threads::Mutex::Lock lm (_lock);
483         MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
484
485         if (!writable()) {
486                 warning << string_compose ("attempt to write to unwritable SMF file %1", _path) << endmsg;
487                 return;
488         }
489
490         if (_model) {
491                 _model->set_edited(false);
492         }
493
494         Evoral::SMF::end_write ();
495
496         /* data in the file now, not removable */
497
498         mark_nonremovable ();
499 }
500
501 bool
502 SMFSource::valid_midi_file (const string& file)
503 {
504         if (safe_midi_file_extension (file) ) {
505                 return (SMF::test (file) );
506         }
507         return false;
508 }
509
510 bool
511 SMFSource::safe_midi_file_extension (const string& file)
512 {
513         static regex_t compiled_pattern;
514         static bool compile = true;
515         const int nmatches = 2;
516         regmatch_t matches[nmatches];
517         
518         if (Glib::file_test (file, Glib::FILE_TEST_EXISTS)) {
519                 if (!Glib::file_test (file, Glib::FILE_TEST_IS_REGULAR)) {
520                         /* exists but is not a regular file */
521                         return false;
522                 }
523         }
524
525         if (compile && regcomp (&compiled_pattern, "\\.[mM][iI][dD][iI]?$", REG_EXTENDED)) {
526                 return false;
527         } else {
528                 compile = false;
529         }
530         
531         if (regexec (&compiled_pattern, file.c_str(), nmatches, matches, 0)) {
532                 return false;
533         }
534
535         return true;
536 }
537
538 static bool compare_eventlist (
539                 const std::pair< Evoral::Event<double>*, gint >& a,
540                 const std::pair< Evoral::Event<double>*, gint >& b) {
541         return ( a.first->time() < b.first->time() );
542 }
543
544 void
545 SMFSource::load_model (bool lock, bool force_reload)
546 {
547         if (_writing) {
548                 return;
549         }
550
551         boost::shared_ptr<Glib::Threads::Mutex::Lock> lm;
552         if (lock)
553                 lm = boost::shared_ptr<Glib::Threads::Mutex::Lock>(new Glib::Threads::Mutex::Lock(_lock));
554
555         if (_model && !force_reload) {
556                 return;
557         }
558
559         if (!_model) {
560                 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
561         } else {
562                 _model->clear();
563         }
564
565         if (writable() && !_open) {
566                 return;
567         }
568
569         _model->start_write();
570         Evoral::SMF::seek_to_start();
571
572         uint64_t time = 0; /* in SMF ticks */
573         Evoral::Event<double> ev;
574
575         uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
576
577         uint32_t delta_t = 0;
578         uint32_t size    = 0;
579         uint8_t* buf     = NULL;
580         int ret;
581         gint event_id;
582         bool have_event_id;
583
584         // TODO simplify event allocation
585         std::list< std::pair< Evoral::Event<double>*, gint > > eventlist;
586
587         for (unsigned i = 1; i <= num_tracks(); ++i) {
588                 if (seek_to_track(i)) continue;
589
590                 time = 0;
591                 have_event_id = false;
592
593                 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
594
595                         time += delta_t;
596
597                         if (ret == 0) {
598                                 /* meta-event : did we get an event ID ?  */
599                                 if (event_id >= 0) {
600                                         have_event_id = true;
601                                 }
602                                 continue;
603                         }
604
605                         if (ret > 0) {
606                                 /* not a meta-event */
607
608                                 if (!have_event_id) {
609                                         event_id = Evoral::next_event_id();
610                                 }
611                                 uint32_t event_type = EventTypeMap::instance().midi_event_type(buf[0]);
612                                 double   event_time = time / (double) ppqn();
613 #ifndef NDEBUG
614                                 std::string ss;
615
616                                 for (uint32_t xx = 0; xx < size; ++xx) {
617                                         char b[8];
618                                         snprintf (b, sizeof (b), "0x%x ", buf[xx]);
619                                         ss += b;
620                                 }
621
622                                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
623                                                         delta_t, time, size, ss , event_type, name()));
624 #endif
625
626                                 eventlist.push_back(make_pair (
627                                                         new Evoral::Event<double> (
628                                                                 event_type, event_time,
629                                                                 size, buf, true)
630                                                         , event_id));
631
632                                 // Set size to max capacity to minimize allocs in read_event
633                                 scratch_size = std::max(size, scratch_size);
634                                 size = scratch_size;
635
636                                 _length_beats = max(_length_beats, event_time);
637                         }
638
639                         /* event ID's must immediately precede the event they are for */
640                         have_event_id = false;
641                 }
642         }
643
644         eventlist.sort(compare_eventlist);
645
646         std::list< std::pair< Evoral::Event<double>*, gint > >::iterator it;
647         for (it=eventlist.begin(); it!=eventlist.end(); ++it) {
648                 _model->append (*it->first, it->second);
649                 delete it->first;
650         }
651
652         _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
653         _model->set_edited (false);
654
655         _model_iter = _model->begin();
656
657         free(buf);
658 }
659
660 void
661 SMFSource::destroy_model ()
662 {
663         //cerr << _name << " destroying model " << _model.get() << endl;
664         _model.reset();
665 }
666
667 void
668 SMFSource::flush_midi ()
669 {
670         if (!writable() || (writable() && !_open)) {
671                 return;
672         }
673
674         Evoral::SMF::end_write ();
675         /* data in the file means its no longer removable */
676         mark_nonremovable ();
677 }
678
679 void
680 SMFSource::set_path (const string& p)
681 {
682         FileSource::set_path (p);
683         SMF::set_path (_path);
684 }
685
686 /** Ensure that this source has some file on disk, even if it's just a SMF header */
687 void
688 SMFSource::ensure_disk_file ()
689 {
690         if (_model) {
691                 /* We have a model, so write it to disk; see MidiSource::session_saved
692                    for an explanation of what we are doing here.
693                 */
694                 boost::shared_ptr<MidiModel> mm = _model;
695                 _model.reset ();
696                 mm->sync_to_source ();
697                 _model = mm;
698         } else {
699                 /* No model; if it's not already open, it's an empty source, so create
700                    and open it for writing.
701                 */
702                 if (!_open) {
703                         open_for_write ();
704                 }
705
706                 /* Flush, which will definitely put something on disk */
707                 flush_midi ();
708         }
709 }
710
711 void
712 SMFSource::prevent_deletion ()
713 {
714         /* Unlike the audio case, the MIDI file remains mutable (because we can
715            edit MIDI data)
716         */
717   
718         _flags = Flag (_flags & ~(Removable|RemovableIfEmpty|RemoveAtDestroy));
719 }
720