do not allow smf_source's reads to stomp on cached read_end position in parent class...
[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/SMFReader.hpp"
36 #include "evoral/Control.hpp"
37
38 #include "ardour/audioengine.h"
39 #include "ardour/event_type_map.h"
40 #include "ardour/midi_model.h"
41 #include "ardour/midi_ring_buffer.h"
42 #include "ardour/session.h"
43 #include "ardour/smf_source.h"
44
45 #include "i18n.h"
46
47 using namespace ARDOUR;
48 using namespace Glib;
49
50 /** Constructor used for new internal-to-session files.  File cannot exist. */
51 SMFSource::SMFSource (Session& s, const ustring& path, bool embedded, Source::Flag flags)
52         : Source(s, DataType::MIDI, path, flags)
53         , MidiSource(s, path)
54         , FileSource(s, DataType::MIDI, path, embedded, flags)
55         , Evoral::SMF()
56         , _last_ev_time_beats(0.0)
57         , _last_ev_time_frames(0)
58         , _smf_last_read_end (0)
59 {
60         if (init(_name, false)) {
61                 throw failed_constructor ();
62         }
63         
64         if (create(path)) {
65                 throw failed_constructor ();
66         }
67 }
68
69 /** Constructor used for existing internal-to-session files. */
70 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
71         : Source(s, node)
72         , MidiSource(s, node)
73         , FileSource(s, node, must_exist)
74         , _last_ev_time_beats(0.0)
75         , _last_ev_time_frames(0)
76         , _smf_last_read_end (0)
77 {
78         if (set_state(node)) {
79                 throw failed_constructor ();
80         }
81         
82         if (init(_name, true)) {
83                 throw failed_constructor ();
84         }
85         
86         if (open(_path)) {
87                 throw failed_constructor ();
88         }
89 }
90
91 SMFSource::~SMFSource ()
92 {
93         if (removable()) {
94                 unlink (_path.c_str());
95         }
96 }
97
98 /** All stamps in audio frames */
99 nframes_t
100 SMFSource::read_unlocked (MidiRingBuffer<nframes_t>& destination, sframes_t source_start,
101                 sframes_t start, nframes_t duration,
102                 sframes_t stamp_offset, sframes_t negative_stamp_offset) const
103 {
104         int      ret  = 0;
105         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
106
107         _read_data_count = 0;
108
109         // Output parameters for read_event (which will allocate scratch in buffer as needed)
110         uint32_t ev_delta_t = 0;
111         uint32_t ev_type    = 0;
112         uint32_t ev_size    = 0;
113         uint8_t* ev_buffer  = 0;
114
115         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
116         
117         BeatsFramesConverter converter(_session, source_start);
118
119         const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
120
121         if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
122                 //cerr << "SMFSource::read_unlocked seeking to " << start << endl;
123                 Evoral::SMF::seek_to_start();
124                 while (time < start_ticks) {
125                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
126                         if (ret == -1) { // EOF
127                                 _smf_last_read_end = start + duration;
128                                 return duration;
129                         }
130                         time += ev_delta_t; // accumulate delta time
131                 }
132         }
133         
134         _smf_last_read_end = start + duration;
135
136         while (true) {
137                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
138                 if (ret == -1) { // EOF
139                         break;
140                 }
141                 
142                 time += ev_delta_t; // accumulate delta time
143
144                 if (ret == 0) { // meta-event (skipped, just accumulate time)
145                         continue;
146                 }
147                 
148                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
149
150                 assert(time >= start_ticks);
151                 const sframes_t ev_frame_time = converter.to(time / (double)ppqn()) + stamp_offset;
152
153                 if (ev_frame_time < start + duration) {
154                         destination.write(ev_frame_time - negative_stamp_offset, ev_type, ev_size, ev_buffer);
155                 } else {
156                         break;
157                 }
158
159                 _read_data_count += ev_size;
160
161                 if (ev_size > scratch_size) {
162                         scratch_size = ev_size;
163                 }
164                 ev_size = scratch_size; // ensure read_event only allocates if necessary
165         }
166         
167         return duration;
168 }
169
170 /** All stamps in audio frames */
171 nframes_t
172 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& source, sframes_t position, nframes_t duration)
173 {
174         _write_data_count = 0;
175                 
176         nframes_t         time;
177         Evoral::EventType type;
178         uint32_t          size;
179
180         size_t   buf_capacity = 4;
181         uint8_t* buf          = (uint8_t*)malloc(buf_capacity);
182         
183         if (_model && ! _model->writing()) {
184                 _model->start_write();
185         }
186
187         Evoral::MIDIEvent<nframes_t> ev;
188
189         while (true) {
190                 bool ret = source.peek_time(&time);
191                 if (!ret || time > _last_write_end + duration) {
192                         break;
193                 }
194
195                 ret = source.read_prefix(&time, &type, &size);
196                 if (!ret) {
197                         cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
198                         break;
199                 }
200
201                 if (size > buf_capacity) {
202                         buf_capacity = size;
203                         buf = (uint8_t*)realloc(buf, size);
204                 }
205
206                 ret = source.read_contents(size, buf);
207                 if (!ret) {
208                         cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
209                         break;
210                 }
211                 
212                 assert(time >= position);
213                 time -= position;
214                 
215                 ev.set(buf, size, time);
216                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
217                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
218                         cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
219                                         << std::hex << int(ev.buffer()[0]) << endl;
220                         continue;
221                 }
222                 
223                 append_event_unlocked_frames(ev, position);
224         }
225
226         if (_model) {
227                 set_default_controls_interpolation();
228         }
229
230         Evoral::SMF::flush();
231         free(buf);
232
233         ViewDataRangeReady(position + _last_write_end, duration); /* EMIT SIGNAL */
234
235         return duration;
236 }
237                 
238
239 /** Append an event with a timestamp in beats (double) */
240 void
241 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
242 {
243         if (ev.size() == 0)  {
244                 return;
245         }
246
247         /*printf("SMFSource: %s - append_event_unlocked_beats time = %lf, size = %u, data = ",
248                         name().c_str(), ev.time(), ev.size()); 
249         for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
250         
251         assert(ev.time() >= 0);
252         if (ev.time() < _last_ev_time_beats) {
253                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
254                 return;
255         }
256         
257         _length_beats = max(_length_beats, ev.time());
258         
259         const double delta_time_beats   = ev.time() - _last_ev_time_beats;
260         const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
261         
262         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer());
263         _last_ev_time_beats = ev.time();
264
265         _write_data_count += ev.size();
266
267         if (_model) {
268                 _model->append(ev);
269         }
270 }
271
272 /** Append an event with a timestamp in frames (nframes_t) */
273 void
274 SMFSource::append_event_unlocked_frames (const Evoral::Event<nframes_t>& ev, sframes_t position)
275 {
276         if (ev.size() == 0)  {
277                 return;
278         }
279
280         /*printf("SMFSource: %s - append_event_unlocked_frames time = %u, size = %u, data = ",
281                         name().c_str(), ev.time(), ev.size()); 
282         for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
283         
284         if (ev.time() < _last_ev_time_frames) {
285                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
286                 return;
287         }
288         
289         BeatsFramesConverter converter(_session, position);
290         
291         _length_beats = max(_length_beats, converter.from(ev.time()));
292         
293         const sframes_t delta_time_frames = ev.time() - _last_ev_time_frames;
294         const double    delta_time_beats  = converter.from(delta_time_frames);
295         const uint32_t  delta_time_ticks  = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
296
297         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer());
298         _last_ev_time_frames = ev.time();
299
300         _write_data_count += ev.size();
301
302         if (_model) {
303                 const double ev_time_beats = converter.from(ev.time());
304                 const Evoral::Event<double> beat_ev(
305                                 ev.event_type(), ev_time_beats, ev.size(), (uint8_t*)ev.buffer());
306                 _model->append(beat_ev);
307         }
308 }
309
310 XMLNode&
311 SMFSource::get_state ()
312 {
313         return MidiSource::get_state();
314 }
315
316 int
317 SMFSource::set_state (const XMLNode& node)
318 {
319         if (Source::set_state (node)) {
320                 return -1;
321         }
322
323         if (MidiSource::set_state (node)) {
324                 return -1;
325         }
326         
327         if (FileSource::set_state (node)) {
328                 return -1;
329         }
330
331         return 0;
332 }
333
334 void
335 SMFSource::mark_streaming_midi_write_started (NoteMode mode, sframes_t start_frame)
336 {
337         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
338         Evoral::SMF::begin_write ();
339         _last_ev_time_beats = 0.0;
340         _last_ev_time_frames = 0;
341 }
342
343 void
344 SMFSource::mark_streaming_write_completed ()
345 {
346         MidiSource::mark_streaming_write_completed();
347
348         if (!writable()) {
349                 return;
350         }
351         
352         _model->set_edited(false);
353         Evoral::SMF::end_write ();
354 }
355
356 bool
357 SMFSource::safe_midi_file_extension (const Glib::ustring& file)
358 {
359         return (file.rfind(".mid") != Glib::ustring::npos);
360 }
361
362 void
363 SMFSource::load_model (bool lock, bool force_reload)
364 {
365         if (_writing) {
366                 return;
367         }
368         
369         if (lock) {
370                 Glib::Mutex::Lock lm (_lock);
371         }
372
373         if (_model && !force_reload) {
374                 return;
375         }
376
377         if (! _model) {
378                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
379                 //cerr << _name << " loaded new model " << _model.get() << endl;
380         } else {
381                 /*cerr << _name << " reloading model " << _model.get()
382                         << " (" << _model->n_notes() << " notes)" << endl;*/
383                 _model->clear();
384         }
385
386         _model->start_write();
387         Evoral::SMF::seek_to_start();
388
389         uint64_t time = 0; /* in SMF ticks */
390         Evoral::Event<double> ev;
391         
392         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
393         
394         uint32_t delta_t = 0;
395         uint32_t size    = 0;
396         uint8_t* buf     = NULL;
397         int ret;
398         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
399                 time += delta_t;
400                 ev.set(buf, size, time / (double)ppqn());
401
402                 if (ret > 0) { // didn't skip (meta) event
403                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
404                         _model->append(ev);
405                 }
406
407                 if (ev.size() > scratch_size) {
408                         scratch_size = ev.size();
409                 }
410                 ev.size() = scratch_size; // ensure read_event only allocates if necessary
411                 
412                 _length_beats = max(_length_beats, ev.time());
413         }
414
415         set_default_controls_interpolation();
416         
417         _model->end_write(false);
418         _model->set_edited(false);
419
420         _model_iter = _model->begin();
421
422         free(buf);
423 }
424
425 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
426
427 void
428 SMFSource::set_default_controls_interpolation ()
429 {
430         // set interpolation style to defaults, can be changed by the GUI later
431         Evoral::ControlSet::Controls controls = _model->controls();
432         for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
433                 (*c).second->list()->set_interpolation(
434                         // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
435                         #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
436                         EventTypeMap::instance().interpolation_of((*c).first));
437                         #else
438                         Evoral::ControlList::Discrete);
439                         #endif
440         }
441 }
442
443
444 void
445 SMFSource::destroy_model ()
446 {
447         //cerr << _name << " destroying model " << _model.get() << endl;
448         _model.reset();
449 }
450
451 void
452 SMFSource::flush_midi ()
453 {
454         Evoral::SMF::end_write();
455 }
456