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