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