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