Fix stub LV2 persist implementation.
[ardour.git] / libs / ardour / smf_source.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3         Written by Dave Robillard, 2006
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)
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         if (create(path)) {
70                 throw failed_constructor ();
71         }
72
73         load_model(true, true); // FIXME
74 }
75
76 /** Constructor used for existing internal-to-session files. */
77 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
78         : Source(s, node)
79         , MidiSource(s, node)
80         , FileSource(s, node, must_exist)
81         , _last_ev_time_beats(0.0)
82         , _last_ev_time_frames(0)
83         , _smf_last_read_end (0)
84         , _smf_last_read_time (0)
85 {
86         if (set_state(node, Stateful::loading_state_version)) {
87                 throw failed_constructor ();
88         }
89
90         if (init(_path, true)) {
91                 throw failed_constructor ();
92         }
93
94         if (open(_path)) {
95                 throw failed_constructor ();
96         }
97
98         load_model(true, true); // FIXME
99 }
100
101 SMFSource::~SMFSource ()
102 {
103         if (removable()) {
104                 unlink (_path.c_str());
105         }
106 }
107
108 /** All stamps in audio frames */
109 nframes_t
110 SMFSource::read_unlocked (Evoral::EventSink<nframes_t>& destination, framepos_t const source_start,
111                           framepos_t start, nframes_t duration,
112                           MidiStateTracker* tracker) const
113 {
114         int      ret  = 0;
115         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
116
117         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
118
119         _read_data_count = 0;
120
121         // Output parameters for read_event (which will allocate scratch in buffer as needed)
122         uint32_t ev_delta_t = 0;
123         uint32_t ev_type    = 0;
124         uint32_t ev_size    = 0;
125         uint8_t* ev_buffer  = 0;
126
127         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
128
129         BeatsFramesConverter converter(_session.tempo_map(), source_start);
130
131         const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
132         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
133
134         if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
135                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
136                 Evoral::SMF::seek_to_start();
137                 while (time < start_ticks) {
138                         gint ignored;
139
140                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
141                         if (ret == -1) { // EOF
142                                 _smf_last_read_end = start + duration;
143                                 return duration;
144                         }
145                         time += ev_delta_t; // accumulate delta time
146                 }
147         } else {
148                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
149                 time = _smf_last_read_time;
150         }
151
152         _smf_last_read_end = start + duration;
153
154         while (true) {
155                 gint ignored; /* XXX don't ignore note id's ??*/
156
157                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
158                 if (ret == -1) { // EOF
159                         break;
160                 }
161
162                 time += ev_delta_t; // accumulate delta time
163                 _smf_last_read_time = time;
164
165                 if (ret == 0) { // meta-event (skipped, just accumulate time)
166                         continue;
167                 }
168
169                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
170
171                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
172                                                                   ev_delta_t, time, ev_buffer[0], ev_type));
173
174                 assert(time >= start_ticks);
175
176                 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
177                    is in session frames.
178                 */
179                 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
180
181                 if (ev_frame_time < start + duration) {
182                         destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
183
184                         if (tracker) {
185                                 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
186                                         tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
187                                 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
188                                         tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
189                                 }
190                         }
191                 } else {
192                         break;
193                 }
194
195                 _read_data_count += ev_size;
196
197                 if (ev_size > scratch_size) {
198                         scratch_size = ev_size;
199                 }
200                 ev_size = scratch_size; // ensure read_event only allocates if necessary
201         }
202
203         return duration;
204 }
205
206 /** Write data to this source from a MidiRingBuffer.
207  *  @param source Buffer to read from.
208  *  @param position This source's start position in session frames.
209  */
210 nframes_t
211 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& source, framepos_t position, nframes_t duration)
212 {
213         _write_data_count = 0;
214
215         nframes_t         time;
216         Evoral::EventType type;
217         uint32_t          size;
218
219         size_t   buf_capacity = 4;
220         uint8_t* buf          = (uint8_t*)malloc(buf_capacity);
221
222         if (_model && ! _model->writing()) {
223                 _model->start_write();
224         }
225
226         Evoral::MIDIEvent<nframes_t> ev;
227
228         while (true) {
229                 bool ret = source.peek_time(&time);
230                 if (!ret || time > _last_write_end + duration) {
231                         break;
232                 }
233
234                 ret = source.read_prefix(&time, &type, &size);
235                 if (!ret) {
236                         cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
237                         break;
238                 }
239
240                 if (size > buf_capacity) {
241                         buf_capacity = size;
242                         buf = (uint8_t*)realloc(buf, size);
243                 }
244
245                 ret = source.read_contents(size, buf);
246                 if (!ret) {
247                         cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
248                         break;
249                 }
250
251                 /* convert from session time to time relative to the source start */
252                 assert(time >= position);
253                 time -= position;
254
255                 ev.set(buf, size, time);
256                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
257                 ev.set_id (Evoral::next_event_id());
258
259                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
260                         /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
261                                         << std::hex << int(ev.buffer()[0]) << endl;*/
262                         continue;
263                 }
264
265                 append_event_unlocked_frames(ev, position);
266         }
267
268         Evoral::SMF::flush();
269         free(buf);
270
271         return duration;
272 }
273
274
275 /** Append an event with a timestamp in beats (double) */
276 void
277 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
278 {
279         assert(_writing);
280         if (ev.size() == 0)  {
281                 return;
282         }
283         
284         /* printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
285                name().c_str(), ev.id(), ev.time(), ev.size());
286            for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
287
288         assert(ev.time() >= 0);
289         if (ev.time() < _last_ev_time_beats) {
290                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
291                 return;
292         }
293
294         Evoral::event_id_t event_id;
295
296         if (ev.id() < 0) {
297                 event_id  = Evoral::next_event_id();
298         } else {
299                 event_id = ev.id();
300         }
301
302         if (_model) {
303                 _model->append (ev, event_id);
304         }
305
306         _length_beats = max(_length_beats, ev.time());
307
308         const double delta_time_beats   = ev.time() - _last_ev_time_beats;
309         const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
310
311         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
312         _last_ev_time_beats = ev.time();
313
314         _write_data_count += ev.size();
315
316 }
317
318 /** Append an event with a timestamp in frames (nframes_t) */
319 void
320 SMFSource::append_event_unlocked_frames (const Evoral::Event<nframes_t>& ev, framepos_t position)
321 {
322         assert(_writing);
323         if (ev.size() == 0)  {
324                 return;
325         }
326
327         /* printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
328                name().c_str(), ev.id(), ev.time(), ev.size());
329            for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
330
331         if (ev.time() < _last_ev_time_frames) {
332                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
333                 return;
334         }
335         
336         BeatsFramesConverter converter(_session.tempo_map(), position);
337         const double ev_time_beats = converter.from(ev.time());
338         Evoral::event_id_t event_id;
339
340         if (ev.id() < 0) {
341                 event_id  = Evoral::next_event_id();
342         } else {
343                 event_id = ev.id();
344         }
345
346         if (_model) {
347                 const Evoral::Event<double> beat_ev (ev.event_type(), 
348                                                      ev_time_beats, 
349                                                      ev.size(), 
350                                                      (uint8_t*)ev.buffer());
351                 _model->append (beat_ev, event_id);
352         } 
353
354         _length_beats = max(_length_beats, ev_time_beats);
355
356         const framepos_t delta_time_frames = ev.time() - _last_ev_time_frames;
357         const double    delta_time_beats  = converter.from(delta_time_frames);
358         const uint32_t  delta_time_ticks  = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
359
360         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
361         _last_ev_time_frames = ev.time();
362
363         _write_data_count += ev.size();
364
365 }
366
367 XMLNode&
368 SMFSource::get_state ()
369 {
370         XMLNode& node = MidiSource::get_state();
371         node.add_property (X_("origin"), _origin);
372         return node;
373 }
374
375 int
376 SMFSource::set_state (const XMLNode& node, int version)
377 {
378         if (Source::set_state (node, version)) {
379                 return -1;
380         }
381
382         if (MidiSource::set_state (node, version)) {
383                 return -1;
384         }
385
386         if (FileSource::set_state (node, version)) {
387                 return -1;
388         }
389
390         return 0;
391 }
392
393 void
394 SMFSource::mark_streaming_midi_write_started (NoteMode mode, framepos_t start_frame)
395 {
396         Glib::Mutex::Lock lm (_lock);
397         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
398         Evoral::SMF::begin_write ();
399         _last_ev_time_beats = 0.0;
400         _last_ev_time_frames = 0;
401 }
402
403 void
404 SMFSource::mark_streaming_write_completed ()
405 {
406         Glib::Mutex::Lock lm (_lock);
407         MidiSource::mark_streaming_write_completed();
408
409         if (!writable()) {
410                 return;
411         }
412
413         if (_model) {
414                 _model->set_edited(false);
415         }
416         
417         Evoral::SMF::end_write ();
418
419         /* data in the file now, not removable */
420
421         mark_nonremovable (); 
422 }
423
424 bool
425 SMFSource::safe_midi_file_extension (const string& file)
426 {
427         return (file.rfind(".mid") != string::npos);
428 }
429
430 void
431 SMFSource::load_model (bool lock, bool force_reload)
432 {
433         if (_writing) {
434                 return;
435         }
436
437         boost::shared_ptr<Glib::Mutex::Lock> lm;
438         if (lock)
439                 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
440
441         if (_model && !force_reload) {
442                 return;
443         }
444
445         if (! _model) {
446                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
447         } else {
448                 _model->clear();
449         }
450
451         _model->start_write();
452         Evoral::SMF::seek_to_start();
453
454         uint64_t time = 0; /* in SMF ticks */
455         Evoral::Event<double> ev;
456
457         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
458
459         uint32_t delta_t = 0;
460         uint32_t size    = 0;
461         uint8_t* buf     = NULL;
462         int ret;
463         gint event_id;
464         bool have_event_id = false;
465
466         while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
467
468                 time += delta_t;
469                 
470                 if (ret == 0) {
471
472                         /* meta-event : did we get an event ID ?
473                          */
474
475                         if (event_id >= 0) {
476                                 have_event_id = true;
477                         }
478
479                         continue;
480                 } 
481                         
482                 if (ret > 0) { 
483
484                         /* not a meta-event */
485
486                         ev.set (buf, size, time / (double)ppqn());
487                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
488
489                         if (!have_event_id) {
490                                 event_id = Evoral::next_event_id();   
491                         }
492 #ifndef NDEBUG
493                         std::string ss;
494                         
495                         for (uint32_t xx = 0; xx < size; ++xx) {
496                                 char b[8];
497                                 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
498                                 ss += b;
499                         }
500
501                         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
502                                                                           delta_t, time, size, ss , ev.event_type(), name()));
503 #endif
504                         
505                         _model->append (ev, event_id);
506
507                         if (ev.size() > scratch_size) {
508                                 scratch_size = ev.size();
509                         }
510                         
511                         ev.size() = scratch_size; // ensure read_event only allocates if necessary
512                         
513                         _length_beats = max(_length_beats, ev.time());
514                 }
515
516                 /* event ID's must immediately precede the event they are for
517                  */
518                    
519                 have_event_id = false;
520         }
521
522         _model->end_write(false);
523         _model->set_edited(false);
524
525         _model_iter = _model->begin();
526
527         free(buf);
528 }
529
530 void
531 SMFSource::destroy_model ()
532 {
533         //cerr << _name << " destroying model " << _model.get() << endl;
534         _model.reset();
535 }
536
537 void
538 SMFSource::flush_midi ()
539 {
540         if (!writable()) {
541                 return;
542         }
543
544         Evoral::SMF::end_write();
545         /* data in the file means its no longer removable */
546         mark_nonremovable (); 
547 }
548
549 void
550 SMFSource::set_path (const string& p)
551 {
552         FileSource::set_path (p);
553         SMF::set_path (_path);
554 }