main fix: when transport stops, clear per-region per-playlist note trackers even...
[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
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/Control.hpp"
36
37 #include "ardour/audioengine.h"
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                 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, framepos_t const source_start,
117                           framepos_t start, framecnt_t duration,
118                           MidiStateTracker* tracker) const
119 {
120         int      ret  = 0;
121         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
122
123         if (writable() && !_open) {
124                 /* nothing to read since nothing has ben written */
125                 return duration;
126         }
127
128         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
129
130         // Output parameters for read_event (which will allocate scratch in buffer as needed)
131         uint32_t ev_delta_t = 0;
132         uint32_t ev_type    = 0;
133         uint32_t ev_size    = 0;
134         uint8_t* ev_buffer  = 0;
135
136         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
137
138         BeatsFramesConverter converter(_session.tempo_map(), source_start);
139
140         const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
141         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
142
143         if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
144                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
145                 Evoral::SMF::seek_to_start();
146                 while (time < start_ticks) {
147                         gint ignored;
148
149                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
150                         if (ret == -1) { // EOF
151                                 _smf_last_read_end = start + duration;
152                                 return duration;
153                         }
154                         time += ev_delta_t; // accumulate delta time
155                 }
156         } else {
157                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
158                 time = _smf_last_read_time;
159         }
160
161         _smf_last_read_end = start + duration;
162
163         while (true) {
164                 gint ignored; /* XXX don't ignore note id's ??*/
165
166                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
167                 if (ret == -1) { // EOF
168                         break;
169                 }
170
171                 time += ev_delta_t; // accumulate delta time
172                 _smf_last_read_time = time;
173
174                 if (ret == 0) { // meta-event (skipped, just accumulate time)
175                         continue;
176                 }
177
178                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
179
180                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
181                                                                   ev_delta_t, time, ev_buffer[0], ev_type));
182
183                 assert(time >= start_ticks);
184
185                 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
186                    is in session frames.
187                 */
188                 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
189
190                 if (ev_frame_time < start + duration) {
191                         destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
192
193                         if (tracker) {
194                                 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
195                                         tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
196                                 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
197                                         tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
198                                 }
199                         }
200                 } else {
201                         break;
202                 }
203
204                 if (ev_size > scratch_size) {
205                         scratch_size = ev_size;
206                 }
207                 ev_size = scratch_size; // ensure read_event only allocates if necessary
208         }
209
210         return duration;
211 }
212
213 /** Write data to this source from a MidiRingBuffer.
214  *  @param source Buffer to read from.
215  *  @param position This source's start position in session frames.
216  */
217 framecnt_t
218 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source, framepos_t position, framecnt_t duration)
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
237         // cerr << "SMFSource::write unlocked, begins writing from src buffer with _last_write_end = " << _last_write_end << " dur = " << duration << endl;
238
239         while (true) {
240                 bool ret;
241
242                 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
243                         /* no more events to consider */
244                         break;
245                 }
246
247                 if ((duration != max_framecnt) && (time > (_last_write_end + duration))) {
248                         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("SMFSource::write_unlocked: dropping event @ %1 because it is later than %2 + %3\n",
249                                                                     time, _last_write_end, duration));
250                         break;
251                 }
252
253                 if (!(ret = source.read_prefix (&time, &type, &size))) {
254                         error << _("Unable to read event prefix, corrupt MIDI ring buffer") << endmsg;
255                         break;
256                 }
257
258                 if (size > buf_capacity) {
259                         buf_capacity = size;
260                         buf = (uint8_t*)realloc(buf, size);
261                 }
262
263                 ret = source.read_contents(size, buf);
264                 if (!ret) {
265                         error << _("Read time/size but not buffer, corrupt MIDI ring buffer") << endmsg;
266                         break;
267                 }
268
269                 /* convert from session time to time relative to the source start */
270                 assert(time >= position);
271                 time -= position;
272
273                 ev.set(buf, size, time);
274                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
275                 ev.set_id (Evoral::next_event_id());
276
277                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
278                         /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
279                                         << std::hex << int(ev.buffer()[0]) << endl;*/
280                         continue;
281                 }
282
283                 append_event_unlocked_frames(ev, position);
284         }
285
286         Evoral::SMF::flush();
287         free (buf);
288
289         return duration;
290 }
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         assert(_writing);
298         if (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         assert(ev.time() >= 0);
307         if (ev.time() < _last_ev_time_beats) {
308                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
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         assert(_writing);
338         if (ev.size() == 0)  {
339                 cerr << "SMFSource: asked to append zero-size event\n";
340                 return;
341         }
342
343         /* printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
344                name().c_str(), ev.id(), ev.time(), ev.size());
345            for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
346
347         if (ev.time() < _last_ev_time_frames) {
348                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
349                 return;
350         }
351
352         BeatsFramesConverter converter(_session.tempo_map(), position);
353         const double ev_time_beats = converter.from(ev.time());
354         Evoral::event_id_t event_id;
355
356         if (ev.id() < 0) {
357                 event_id  = Evoral::next_event_id();
358         } else {
359                 event_id = ev.id();
360         }
361
362         if (_model) {
363                 const Evoral::Event<double> beat_ev (ev.event_type(),
364                                                      ev_time_beats,
365                                                      ev.size(),
366                                                      (uint8_t*)ev.buffer());
367                 _model->append (beat_ev, event_id);
368         }
369
370         _length_beats = max(_length_beats, ev_time_beats);
371
372         const Evoral::MusicalTime last_time_beats  = converter.from (_last_ev_time_frames);
373         const Evoral::MusicalTime delta_time_beats = ev_time_beats - last_time_beats;
374         const uint32_t            delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
375
376         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
377         _last_ev_time_frames = ev.time();
378 }
379
380 XMLNode&
381 SMFSource::get_state ()
382 {
383         XMLNode& node = MidiSource::get_state();
384         node.add_property (X_("origin"), _origin);
385         return node;
386 }
387
388 int
389 SMFSource::set_state (const XMLNode& node, int version)
390 {
391         if (Source::set_state (node, version)) {
392                 return -1;
393         }
394
395         if (MidiSource::set_state (node, version)) {
396                 return -1;
397         }
398
399         if (FileSource::set_state (node, version)) {
400                 return -1;
401         }
402
403         return 0;
404 }
405
406 void
407 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
408 {
409         /* CALLER MUST HOLD LOCK */
410
411         if (!_open && open_for_write()) {
412                 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
413                 /* XXX should probably throw or return something */
414                 return;
415         }
416
417         MidiSource::mark_streaming_midi_write_started (mode);
418         Evoral::SMF::begin_write ();
419         _last_ev_time_beats = 0.0;
420         _last_ev_time_frames = 0;
421 }
422
423 void
424 SMFSource::mark_streaming_write_completed ()
425 {
426         mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
427 }
428
429 void
430 SMFSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption stuck_notes_option, Evoral::MusicalTime when)
431 {
432         Glib::Mutex::Lock lm (_lock);
433         MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
434
435         if (!writable()) {
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         return (file.rfind(".mid") != string::npos) || (file.rfind (".MID") != string::npos);
454 }
455
456 void
457 SMFSource::load_model (bool lock, bool force_reload)
458 {
459         if (_writing) {
460                 return;
461         }
462
463         boost::shared_ptr<Glib::Mutex::Lock> lm;
464         if (lock)
465                 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
466
467         if (_model && !force_reload) {
468                 return;
469         }
470
471         if (!_model) {
472                 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
473         } else {
474                 _model->clear();
475         }
476
477         if (writable() && !_open) {
478                 return;
479         }
480
481         _model->start_write();
482         Evoral::SMF::seek_to_start();
483
484         uint64_t time = 0; /* in SMF ticks */
485         Evoral::Event<double> ev;
486
487         uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
488
489         uint32_t delta_t = 0;
490         uint32_t size    = 0;
491         uint8_t* buf     = NULL;
492         int ret;
493         gint event_id;
494         bool have_event_id = false;
495
496         while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
497
498                 time += delta_t;
499
500                 if (ret == 0) {
501
502                         /* meta-event : did we get an event ID ?
503                          */
504
505                         if (event_id >= 0) {
506                                 have_event_id = true;
507                         }
508
509                         continue;
510                 }
511
512                 if (ret > 0) {
513
514                         /* not a meta-event */
515
516                         ev.set (buf, size, time / (double)ppqn());
517                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
518
519                         if (!have_event_id) {
520                                 event_id = Evoral::next_event_id();
521                         }
522 #ifndef NDEBUG
523                         std::string ss;
524
525                         for (uint32_t xx = 0; xx < size; ++xx) {
526                                 char b[8];
527                                 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
528                                 ss += b;
529                         }
530
531                         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
532                                                                           delta_t, time, size, ss , ev.event_type(), name()));
533 #endif
534
535                         _model->append (ev, event_id);
536
537                         // Set size to max capacity to minimize allocs in read_event
538                         scratch_size = std::max(size, scratch_size);
539                         size = scratch_size;
540
541                         _length_beats = max(_length_beats, ev.time());
542                 }
543
544                 /* event ID's must immediately precede the event they are for
545                  */
546
547                 have_event_id = false;
548         }
549
550         _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
551         _model->set_edited (false);
552
553         _model_iter = _model->begin();
554
555         free(buf);
556 }
557
558 void
559 SMFSource::destroy_model ()
560 {
561         //cerr << _name << " destroying model " << _model.get() << endl;
562         _model.reset();
563 }
564
565 void
566 SMFSource::flush_midi ()
567 {
568         if (!writable() || (writable() && !_open)) {
569                 return;
570         }
571
572         Evoral::SMF::end_write ();
573         /* data in the file means its no longer removable */
574         mark_nonremovable ();
575 }
576
577 void
578 SMFSource::set_path (const string& p)
579 {
580         FileSource::set_path (p);
581         SMF::set_path (_path);
582 }
583
584 /** Ensure that this source has some file on disk, even if it's just a SMF header */
585 void
586 SMFSource::ensure_disk_file ()
587 {
588         if (_model) {
589                 /* We have a model, so write it to disk; see MidiSource::session_saved
590                    for an explanation of what we are doing here.
591                 */
592                 boost::shared_ptr<MidiModel> mm = _model;
593                 _model.reset ();
594                 mm->sync_to_source ();
595                 _model = mm;
596         } else {
597                 /* No model; if it's not already open, it's an empty source, so create
598                    and open it for writing.
599                 */
600                 if (!_open) {
601                         open_for_write ();
602                 }
603
604                 /* Flush, which will definitely put something on disk */
605                 flush_midi ();
606         }
607 }
608