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