da6b3cad6f4043882fd07a42e1422a3b0c908d99
[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/pathscanner.h"
29 #include "pbd/stl_delete.h"
30 #include "pbd/strsplit.h"
31
32 #include <glibmm/miscutils.h>
33
34 #include "evoral/Control.hpp"
35
36 #include "ardour/event_type_map.h"
37 #include "ardour/midi_model.h"
38 #include "ardour/midi_ring_buffer.h"
39 #include "ardour/midi_state_tracker.h"
40 #include "ardour/session.h"
41 #include "ardour/smf_source.h"
42 #include "ardour/debug.h"
43
44 #include "i18n.h"
45
46 using namespace ARDOUR;
47 using namespace Glib;
48 using namespace PBD;
49
50 /** Constructor used for new internal-to-session files.  File cannot exist. */
51 SMFSource::SMFSource (Session& s, const string& path, Source::Flag flags)
52         : Source(s, DataType::MIDI, path, flags)
53         , MidiSource(s, path, flags)
54         , FileSource(s, DataType::MIDI, path, string(), flags)
55         , Evoral::SMF()
56         , _last_ev_time_beats(0.0)
57         , _last_ev_time_frames(0)
58         , _smf_last_read_end (0)
59         , _smf_last_read_time (0)
60 {
61         /* note that origin remains empty */
62
63         if (init(_path, false)) {
64                 throw failed_constructor ();
65         }
66
67         /* file is not opened until write */
68 }
69
70 /** Constructor used for existing internal-to-session files. */
71 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
72         : Source(s, node)
73         , MidiSource(s, node)
74         , FileSource(s, node, must_exist)
75         , _last_ev_time_beats(0.0)
76         , _last_ev_time_frames(0)
77         , _smf_last_read_end (0)
78         , _smf_last_read_time (0)
79 {
80         if (set_state(node, Stateful::loading_state_version)) {
81                 throw failed_constructor ();
82         }
83
84         if (init(_path, true)) {
85                 throw failed_constructor ();
86         }
87
88         if (open(_path)) {
89                 throw failed_constructor ();
90         }
91
92         _open = true;
93 }
94
95 SMFSource::~SMFSource ()
96 {
97         if (removable()) {
98                 unlink (_path.c_str());
99         }
100 }
101
102 int
103 SMFSource::open_for_write ()
104 {
105         if (create (_path)) {
106                 return -1;
107         }
108         _open = true;
109         return 0;
110 }
111
112 /** All stamps in audio frames */
113 framecnt_t
114 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination, framepos_t const source_start,
115                           framepos_t start, framecnt_t duration,
116                           MidiStateTracker* tracker) const
117 {
118         int      ret  = 0;
119         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
120
121         if (writable() && !_open) {
122                 /* nothing to read since nothing has ben written */
123                 return duration;
124         }
125
126         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
127
128         // Output parameters for read_event (which will allocate scratch in buffer as needed)
129         uint32_t ev_delta_t = 0;
130         uint32_t ev_type    = 0;
131         uint32_t ev_size    = 0;
132         uint8_t* ev_buffer  = 0;
133
134         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
135
136         BeatsFramesConverter converter(_session.tempo_map(), source_start);
137
138         const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
139         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
140
141         if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
142                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
143                 Evoral::SMF::seek_to_start();
144                 while (time < start_ticks) {
145                         gint ignored;
146
147                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
148                         if (ret == -1) { // EOF
149                                 _smf_last_read_end = start + duration;
150                                 return duration;
151                         }
152                         time += ev_delta_t; // accumulate delta time
153                 }
154         } else {
155                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
156                 time = _smf_last_read_time;
157         }
158
159         _smf_last_read_end = start + duration;
160
161         while (true) {
162                 gint ignored; /* XXX don't ignore note id's ??*/
163
164                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
165                 if (ret == -1) { // EOF
166                         break;
167                 }
168
169                 time += ev_delta_t; // accumulate delta time
170                 _smf_last_read_time = time;
171
172                 if (ret == 0) { // meta-event (skipped, just accumulate time)
173                         continue;
174                 }
175
176                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
177
178                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
179                                                                   ev_delta_t, time, ev_buffer[0], ev_type));
180
181                 assert(time >= start_ticks);
182
183                 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
184                    is in session frames.
185                 */
186                 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
187
188                 if (ev_frame_time < start + duration) {
189                         destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
190
191                         if (tracker) {
192                                 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
193                                         tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
194                                 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
195                                         tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
196                                 }
197                         }
198                 } else {
199                         break;
200                 }
201
202                 if (ev_size > scratch_size) {
203                         scratch_size = ev_size;
204                 }
205                 ev_size = scratch_size; // ensure read_event only allocates if necessary
206         }
207
208         return duration;
209 }
210
211 /** Write data to this source from a MidiRingBuffer.
212  *  @param source Buffer to read from.
213  *  @param position This source's start position in session frames.
214  */
215 framecnt_t
216 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source, framepos_t position, framecnt_t duration)
217 {
218         if (!_writing) {
219                 mark_streaming_write_started ();
220         }
221
222         framepos_t        time;
223         Evoral::EventType type;
224         uint32_t          size;
225
226         size_t   buf_capacity = 4;
227         uint8_t* buf          = (uint8_t*)malloc(buf_capacity);
228
229         if (_model && ! _model->writing()) {
230                 _model->start_write();
231         }
232
233         Evoral::MIDIEvent<framepos_t> ev;
234
235         // cerr << "SMFSource::write unlocked, begins writing from src buffer with _last_write_end = " << _last_write_end << " dur = " << duration << endl;
236
237         while (true) {
238                 bool ret;
239
240                 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
241                         /* no more events to consider */
242                         break;
243                 }
244
245                 if ((duration != max_framecnt) && (time > (_last_write_end + duration))) {
246                         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("SMFSource::write_unlocked: dropping event @ %1 because it is later than %2 + %3\n",
247                                                                     time, _last_write_end, duration));
248                         break;
249                 }
250
251                 if (!(ret = source.read_prefix (&time, &type, &size))) {
252                         error << _("Unable to read event prefix, corrupt MIDI ring buffer") << endmsg;
253                         break;
254                 }
255
256                 if (size > buf_capacity) {
257                         buf_capacity = size;
258                         buf = (uint8_t*)realloc(buf, size);
259                 }
260
261                 ret = source.read_contents(size, buf);
262                 if (!ret) {
263                         error << _("Read time/size but not buffer, corrupt MIDI ring buffer") << endmsg;
264                         break;
265                 }
266
267                 /* convert from session time to time relative to the source start */
268                 assert(time >= position);
269                 time -= position;
270
271                 ev.set(buf, size, time);
272                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
273                 ev.set_id (Evoral::next_event_id());
274
275                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
276                         /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
277                                         << std::hex << int(ev.buffer()[0]) << endl;*/
278                         continue;
279                 }
280
281                 append_event_unlocked_frames(ev, position);
282         }
283
284         Evoral::SMF::flush();
285         free (buf);
286
287         return duration;
288 }
289
290
291 /** Append an event with a timestamp in beats (double) */
292 void
293 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
294 {
295         assert(_writing);
296         if (ev.size() == 0)  {
297                 return;
298         }
299
300         /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
301                name().c_str(), ev.id(), ev.time(), ev.size());
302                for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
303
304         assert(ev.time() >= 0);
305         if (ev.time() < _last_ev_time_beats) {
306                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
307                 return;
308         }
309
310         Evoral::event_id_t event_id;
311
312         if (ev.id() < 0) {
313                 event_id  = Evoral::next_event_id();
314         } else {
315                 event_id = ev.id();
316         }
317
318         if (_model) {
319                 _model->append (ev, event_id);
320         }
321
322         _length_beats = max(_length_beats, ev.time());
323
324         const double delta_time_beats   = ev.time() - _last_ev_time_beats;
325         const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
326
327         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
328         _last_ev_time_beats = ev.time();
329 }
330
331 /** Append an event with a timestamp in frames (framepos_t) */
332 void
333 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
334 {
335         assert(_writing);
336         if (ev.size() == 0)  {
337                 cerr << "SMFSource: asked to append zero-size event\n";
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                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
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                                                      (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::Mutex::Lock lm (_lock);
431         MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
432
433         if (!writable()) {
434                 return;
435         }
436
437         if (_model) {
438                 _model->set_edited(false);
439         }
440
441         Evoral::SMF::end_write ();
442
443         /* data in the file now, not removable */
444
445         mark_nonremovable ();
446 }
447
448 bool
449 SMFSource::safe_midi_file_extension (const string& file)
450 {
451         return (file.rfind(".mid") != string::npos) || (file.rfind (".MID") != string::npos);
452 }
453
454 void
455 SMFSource::load_model (bool lock, bool force_reload)
456 {
457         if (_writing) {
458                 return;
459         }
460
461         boost::shared_ptr<Glib::Mutex::Lock> lm;
462         if (lock)
463                 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
464
465         if (_model && !force_reload) {
466                 return;
467         }
468
469         if (!_model) {
470                 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
471         } else {
472                 _model->clear();
473         }
474
475         if (writable() && !_open) {
476                 return;
477         }
478
479         _model->start_write();
480         Evoral::SMF::seek_to_start();
481
482         uint64_t time = 0; /* in SMF ticks */
483         Evoral::Event<double> ev;
484
485         uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
486
487         uint32_t delta_t = 0;
488         uint32_t size    = 0;
489         uint8_t* buf     = NULL;
490         int ret;
491         gint event_id;
492         bool have_event_id = false;
493
494         while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
495
496                 time += delta_t;
497
498                 if (ret == 0) {
499
500                         /* meta-event : did we get an event ID ?
501                          */
502
503                         if (event_id >= 0) {
504                                 have_event_id = true;
505                         }
506
507                         continue;
508                 }
509
510                 if (ret > 0) {
511
512                         /* not a meta-event */
513
514                         ev.set (buf, size, time / (double)ppqn());
515                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
516
517                         if (!have_event_id) {
518                                 event_id = Evoral::next_event_id();
519                         }
520 #ifndef NDEBUG
521                         std::string ss;
522
523                         for (uint32_t xx = 0; xx < size; ++xx) {
524                                 char b[8];
525                                 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
526                                 ss += b;
527                         }
528
529                         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
530                                                                           delta_t, time, size, ss , ev.event_type(), name()));
531 #endif
532
533                         _model->append (ev, event_id);
534
535                         // Set size to max capacity to minimize allocs in read_event
536                         scratch_size = std::max(size, scratch_size);
537                         size = scratch_size;
538
539                         _length_beats = max(_length_beats, ev.time());
540                 }
541
542                 /* event ID's must immediately precede the event they are for
543                  */
544
545                 have_event_id = false;
546         }
547
548         _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
549         _model->set_edited (false);
550
551         _model_iter = _model->begin();
552
553         free(buf);
554 }
555
556 void
557 SMFSource::destroy_model ()
558 {
559         //cerr << _name << " destroying model " << _model.get() << endl;
560         _model.reset();
561 }
562
563 void
564 SMFSource::flush_midi ()
565 {
566         if (!writable() || (writable() && !_open)) {
567                 return;
568         }
569
570         Evoral::SMF::end_write ();
571         /* data in the file means its no longer removable */
572         mark_nonremovable ();
573 }
574
575 void
576 SMFSource::set_path (const string& p)
577 {
578         FileSource::set_path (p);
579         SMF::set_path (_path);
580 }
581
582 /** Ensure that this source has some file on disk, even if it's just a SMF header */
583 void
584 SMFSource::ensure_disk_file ()
585 {
586         if (_model) {
587                 /* We have a model, so write it to disk; see MidiSource::session_saved
588                    for an explanation of what we are doing here.
589                 */
590                 boost::shared_ptr<MidiModel> mm = _model;
591                 _model.reset ();
592                 mm->sync_to_source ();
593                 _model = mm;
594         } else {
595                 /* No model; if it's not already open, it's an empty source, so create
596                    and open it for writing.
597                 */
598                 if (!_open) {
599                         open_for_write ();
600                 }
601
602                 /* Flush, which will definitely put something on disk */
603                 flush_midi ();
604         }
605 }
606