f134ff53351be085c73cc790eb35fec230fc21bc
[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, 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         if (create(path)) {
70                 throw failed_constructor ();
71         }
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
97 SMFSource::~SMFSource ()
98 {
99         if (removable()) {
100                 unlink (_path.c_str());
101         }
102 }
103
104 /** All stamps in audio frames */
105 framecnt_t
106 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination, framepos_t const source_start,
107                           framepos_t start, framecnt_t duration,
108                           MidiStateTracker* tracker) const
109 {
110         int      ret  = 0;
111         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
112
113         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
114
115         _read_data_count = 0;
116
117         // Output parameters for read_event (which will allocate scratch in buffer as needed)
118         uint32_t ev_delta_t = 0;
119         uint32_t ev_type    = 0;
120         uint32_t ev_size    = 0;
121         uint8_t* ev_buffer  = 0;
122
123         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
124
125         BeatsFramesConverter converter(_session.tempo_map(), source_start);
126
127         const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
128         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
129
130         if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
131                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
132                 Evoral::SMF::seek_to_start();
133                 while (time < start_ticks) {
134                         gint ignored;
135
136                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
137                         if (ret == -1) { // EOF
138                                 _smf_last_read_end = start + duration;
139                                 return duration;
140                         }
141                         time += ev_delta_t; // accumulate delta time
142                 }
143         } else {
144                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
145                 time = _smf_last_read_time;
146         }
147
148         _smf_last_read_end = start + duration;
149
150         while (true) {
151                 gint ignored; /* XXX don't ignore note id's ??*/
152
153                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
154                 if (ret == -1) { // EOF
155                         break;
156                 }
157
158                 time += ev_delta_t; // accumulate delta time
159                 _smf_last_read_time = time;
160
161                 if (ret == 0) { // meta-event (skipped, just accumulate time)
162                         continue;
163                 }
164
165                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
166
167                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
168                                                                   ev_delta_t, time, ev_buffer[0], ev_type));
169
170                 assert(time >= start_ticks);
171
172                 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
173                    is in session frames.
174                 */
175                 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
176
177                 if (ev_frame_time < start + duration) {
178                         destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
179
180                         if (tracker) {
181                                 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
182                                         tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
183                                 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
184                                         tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
185                                 }
186                         }
187                 } else {
188                         break;
189                 }
190
191                 _read_data_count += ev_size;
192
193                 if (ev_size > scratch_size) {
194                         scratch_size = ev_size;
195                 }
196                 ev_size = scratch_size; // ensure read_event only allocates if necessary
197         }
198
199         return duration;
200 }
201
202 /** Write data to this source from a MidiRingBuffer.
203  *  @param source Buffer to read from.
204  *  @param position This source's start position in session frames.
205  */
206 framecnt_t
207 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source, framepos_t position, framecnt_t duration)
208 {
209         _write_data_count = 0;
210
211         framepos_t        time;
212         Evoral::EventType type;
213         uint32_t          size;
214
215         size_t   buf_capacity = 4;
216         uint8_t* buf          = (uint8_t*)malloc(buf_capacity);
217
218         if (_model && ! _model->writing()) {
219                 _model->start_write();
220         }
221
222         Evoral::MIDIEvent<framepos_t> ev;
223
224         while (true) {
225                 bool ret = source.peek_time(&time);
226                 if (!ret || time > _last_write_end + duration) {
227                         break;
228                 }
229
230                 ret = source.read_prefix(&time, &type, &size);
231                 if (!ret) {
232                         cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
233                         break;
234                 }
235
236                 if (size > buf_capacity) {
237                         buf_capacity = size;
238                         buf = (uint8_t*)realloc(buf, size);
239                 }
240
241                 ret = source.read_contents(size, buf);
242                 if (!ret) {
243                         cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
244                         break;
245                 }
246
247                 /* convert from session time to time relative to the source start */
248                 assert(time >= position);
249                 time -= position;
250
251                 ev.set(buf, size, time);
252                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
253                 ev.set_id (Evoral::next_event_id());
254
255                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
256                         /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
257                                         << std::hex << int(ev.buffer()[0]) << endl;*/
258                         continue;
259                 }
260
261                 append_event_unlocked_frames(ev, position);
262         }
263
264         Evoral::SMF::flush();
265         free(buf);
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 (framepos_t) */
315 void
316 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_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         XMLNode& node = MidiSource::get_state();
367         node.add_property (X_("origin"), _origin);
368         return node;
369 }
370
371 int
372 SMFSource::set_state (const XMLNode& node, int version)
373 {
374         if (Source::set_state (node, version)) {
375                 return -1;
376         }
377
378         if (MidiSource::set_state (node, version)) {
379                 return -1;
380         }
381
382         if (FileSource::set_state (node, version)) {
383                 return -1;
384         }
385
386         return 0;
387 }
388
389 void
390 SMFSource::mark_streaming_midi_write_started (NoteMode mode, framepos_t start_frame)
391 {
392         Glib::Mutex::Lock lm (_lock);
393         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
394         Evoral::SMF::begin_write ();
395         _last_ev_time_beats = 0.0;
396         _last_ev_time_frames = 0;
397 }
398
399 void
400 SMFSource::mark_streaming_write_completed ()
401 {
402         Glib::Mutex::Lock lm (_lock);
403         MidiSource::mark_streaming_write_completed();
404
405         if (!writable()) {
406                 return;
407         }
408
409         if (_model) {
410                 _model->set_edited(false);
411         }
412         
413         Evoral::SMF::end_write ();
414
415         /* data in the file now, not removable */
416
417         mark_nonremovable (); 
418 }
419
420 bool
421 SMFSource::safe_midi_file_extension (const string& file)
422 {
423         return (file.rfind(".mid") != string::npos);
424 }
425
426 void
427 SMFSource::load_model (bool lock, bool force_reload)
428 {
429         if (_writing) {
430                 return;
431         }
432
433         boost::shared_ptr<Glib::Mutex::Lock> lm;
434         if (lock)
435                 lm = boost::shared_ptr<Glib::Mutex::Lock>(new Glib::Mutex::Lock(_lock));
436
437         if (_model && !force_reload) {
438                 return;
439         }
440
441         if (!_model) {
442                 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
443         } else {
444                 _model->clear();
445         }
446
447         _model->start_write();
448         Evoral::SMF::seek_to_start();
449
450         uint64_t time = 0; /* in SMF ticks */
451         Evoral::Event<double> ev;
452
453         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
454
455         uint32_t delta_t = 0;
456         uint32_t size    = 0;
457         uint8_t* buf     = NULL;
458         int ret;
459         gint event_id;
460         bool have_event_id = false;
461
462         while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
463
464                 time += delta_t;
465                 
466                 if (ret == 0) {
467
468                         /* meta-event : did we get an event ID ?
469                          */
470
471                         if (event_id >= 0) {
472                                 have_event_id = true;
473                         }
474
475                         continue;
476                 } 
477                         
478                 if (ret > 0) { 
479
480                         /* not a meta-event */
481
482                         ev.set (buf, size, time / (double)ppqn());
483                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
484
485                         if (!have_event_id) {
486                                 event_id = Evoral::next_event_id();   
487                         }
488 #ifndef NDEBUG
489                         std::string ss;
490                         
491                         for (uint32_t xx = 0; xx < size; ++xx) {
492                                 char b[8];
493                                 snprintf (b, sizeof (b), "0x%x ", buf[xx]);
494                                 ss += b;
495                         }
496
497                         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
498                                                                           delta_t, time, size, ss , ev.event_type(), name()));
499 #endif
500                         
501                         _model->append (ev, event_id);
502
503                         if (ev.size() > scratch_size) {
504                                 scratch_size = ev.size();
505                         }
506                         
507                         ev.size() = scratch_size; // ensure read_event only allocates if necessary
508                         
509                         _length_beats = max(_length_beats, ev.time());
510                 }
511
512                 /* event ID's must immediately precede the event they are for
513                  */
514                    
515                 have_event_id = false;
516         }
517
518         _model->end_write(false);
519         _model->set_edited(false);
520
521         _model_iter = _model->begin();
522
523         free(buf);
524 }
525
526 void
527 SMFSource::destroy_model ()
528 {
529         //cerr << _name << " destroying model " << _model.get() << endl;
530         _model.reset();
531 }
532
533 void
534 SMFSource::flush_midi ()
535 {
536         if (!writable()) {
537                 return;
538         }
539
540         Evoral::SMF::end_write();
541         /* data in the file means its no longer removable */
542         mark_nonremovable (); 
543 }
544
545 void
546 SMFSource::set_path (const string& p)
547 {
548         FileSource::set_path (p);
549         SMF::set_path (_path);
550 }