7db027124b8c09c9b15ff368960cf4cdee1ed62a
[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                 if (!ret || time > _last_write_end + duration) {
190                         break;
191                 }
192
193                 ret = source.read_prefix(&time, &type, &size);
194                 if (!ret) {
195                         cerr << "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl;
196                         break;
197                 }
198
199                 if (size > buf_capacity) {
200                         buf_capacity = size;
201                         buf = (uint8_t*)realloc(buf, size);
202                 }
203
204                 ret = source.read_contents(size, buf);
205                 if (!ret) {
206                         cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
207                         break;
208                 }
209                 
210                 assert(time >= position);
211                 time -= position;
212                 
213                 ev.set(buf, size, time);
214                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
215                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
216                         cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
217                                         << std::hex << int(ev.buffer()[0]) << endl;
218                         continue;
219                 }
220                 
221                 append_event_unlocked_frames(ev, position);
222         }
223
224         if (_model) {
225                 set_default_controls_interpolation();
226         }
227
228         Evoral::SMF::flush();
229         free(buf);
230
231         ViewDataRangeReady(position + _last_write_end, duration); /* EMIT SIGNAL */
232
233         return duration;
234 }
235                 
236
237 /** Append an event with a timestamp in beats (double) */
238 void
239 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
240 {
241         if (ev.size() == 0)  {
242                 return;
243         }
244
245         /*printf("SMFSource: %s - append_event_unlocked_beats time = %lf, size = %u, data = ",
246                         name().c_str(), ev.time(), ev.size()); 
247         for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
248         
249         assert(ev.time() >= 0);
250         if (ev.time() < _last_ev_time_beats) {
251                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
252                 return;
253         }
254         
255         _length_beats = max(_length_beats, ev.time());
256         
257         const double delta_time_beats   = ev.time() - _last_ev_time_beats;
258         const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
259         
260         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer());
261         _last_ev_time_beats = ev.time();
262
263         _write_data_count += ev.size();
264
265         if (_model) {
266                 _model->append(ev);
267         }
268 }
269
270 /** Append an event with a timestamp in frames (nframes_t) */
271 void
272 SMFSource::append_event_unlocked_frames (const Evoral::Event<nframes_t>& ev, sframes_t position)
273 {
274         if (ev.size() == 0)  {
275                 return;
276         }
277
278         /*printf("SMFSource: %s - append_event_unlocked_frames time = %u, size = %u, data = ",
279                         name().c_str(), ev.time(), ev.size()); 
280         for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
281         
282         if (ev.time() < _last_ev_time_frames) {
283                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
284                 return;
285         }
286         
287         BeatsFramesConverter converter(_session, position);
288         
289         _length_beats = max(_length_beats, converter.from(ev.time()));
290         
291         const sframes_t delta_time_frames = ev.time() - _last_ev_time_frames;
292         const double    delta_time_beats  = converter.from(delta_time_frames);
293         const uint32_t  delta_time_ticks  = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
294
295         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer());
296         _last_ev_time_frames = ev.time();
297
298         _write_data_count += ev.size();
299
300         if (_model) {
301                 const double ev_time_beats = converter.from(ev.time());
302                 const Evoral::Event<double> beat_ev(
303                                 ev.event_type(), ev_time_beats, ev.size(), (uint8_t*)ev.buffer());
304                 _model->append(beat_ev);
305         }
306 }
307
308 XMLNode&
309 SMFSource::get_state ()
310 {
311         return MidiSource::get_state();
312 }
313
314 int
315 SMFSource::set_state (const XMLNode& node)
316 {
317         if (Source::set_state (node)) {
318                 return -1;
319         }
320
321         if (MidiSource::set_state (node)) {
322                 return -1;
323         }
324         
325         if (FileSource::set_state (node)) {
326                 return -1;
327         }
328
329         return 0;
330 }
331
332 void
333 SMFSource::mark_streaming_midi_write_started (NoteMode mode, sframes_t start_frame)
334 {
335         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
336         Evoral::SMF::begin_write ();
337         _last_ev_time_beats = 0.0;
338         _last_ev_time_frames = 0;
339 }
340
341 void
342 SMFSource::mark_streaming_write_completed ()
343 {
344         MidiSource::mark_streaming_write_completed();
345
346         if (!writable()) {
347                 return;
348         }
349         
350         _model->set_edited(false);
351         Evoral::SMF::end_write ();
352 }
353
354 bool
355 SMFSource::safe_midi_file_extension (const Glib::ustring& file)
356 {
357         return (file.rfind(".mid") != Glib::ustring::npos);
358 }
359
360 void
361 SMFSource::load_model (bool lock, bool force_reload)
362 {
363         if (_writing) {
364                 return;
365         }
366         
367         if (lock) {
368                 Glib::Mutex::Lock lm (_lock);
369         }
370
371         if (_model && !force_reload) {
372                 return;
373         }
374
375         if (! _model) {
376                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
377                 //cerr << _name << " loaded new model " << _model.get() << endl;
378         } else {
379                 /*cerr << _name << " reloading model " << _model.get()
380                         << " (" << _model->n_notes() << " notes)" << endl;*/
381                 _model->clear();
382         }
383
384         _model->start_write();
385         Evoral::SMF::seek_to_start();
386
387         uint64_t time = 0; /* in SMF ticks */
388         Evoral::Event<double> ev;
389         
390         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
391         
392         uint32_t delta_t = 0;
393         uint32_t size    = 0;
394         uint8_t* buf     = NULL;
395         int ret;
396         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
397                 time += delta_t;
398                 ev.set(buf, size, time / (double)ppqn());
399
400                 if (ret > 0) { // didn't skip (meta) event
401                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
402                         _model->append(ev);
403                 }
404
405                 if (ev.size() > scratch_size) {
406                         scratch_size = ev.size();
407                 }
408                 ev.size() = scratch_size; // ensure read_event only allocates if necessary
409                 
410                 _length_beats = max(_length_beats, ev.time());
411         }
412
413         set_default_controls_interpolation();
414         
415         _model->end_write(false);
416         _model->set_edited(false);
417
418         _model_iter = _model->begin();
419
420         free(buf);
421 }
422
423 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
424
425 void
426 SMFSource::set_default_controls_interpolation ()
427 {
428         // set interpolation style to defaults, can be changed by the GUI later
429         Evoral::ControlSet::Controls controls = _model->controls();
430         for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
431                 (*c).second->list()->set_interpolation(
432                         // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
433                         #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
434                         EventTypeMap::instance().interpolation_of((*c).first));
435                         #else
436                         Evoral::ControlList::Discrete);
437                         #endif
438         }
439 }
440
441
442 void
443 SMFSource::destroy_model ()
444 {
445         //cerr << _name << " destroying model " << _model.get() << endl;
446         _model.reset();
447 }
448
449 void
450 SMFSource::flush_midi ()
451 {
452         Evoral::SMF::end_write();
453 }
454