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