*** NEW CODING POLICY ***
[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>& dst, sframes_t position,
99                 sframes_t start, nframes_t dur,
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, position);
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 + dur;
126                                 return dur;
127                         }
128                         time += ev_delta_t; // accumulate delta time
129                 }
130         }
131         
132         _last_read_end = start + dur;
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 + dur) {
152                         dst.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 dur;
166 }
167
168 /** All stamps in audio frames */
169 nframes_t
170 SMFSource::write_unlocked (MidiRingBuffer<nframes_t>& src, sframes_t position, nframes_t dur)
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 = src.peek_time(&time);
189                 if (!ret || time > _last_write_end + dur) {
190                         break;
191                 }
192
193                 ret = src.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 = src.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, dur); /* EMIT SIGNAL */
232
233         return dur;
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         assert(ev.time() >= 0);
283         if (ev.time() < _last_ev_time_frames) {
284                 cerr << "SMFSource: Warning: Skipping event with non-monotonic time" << endl;
285                 return;
286         }
287         
288         BeatsFramesConverter converter(_session, position);
289         
290         _length_beats = max(_length_beats, converter.from(ev.time()));
291         
292         const sframes_t delta_time_frames = ev.time() - _last_ev_time_frames;
293         const double    delta_time_beats  = converter.from(delta_time_frames);
294         const uint32_t  delta_time_ticks  = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
295
296         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer());
297         _last_ev_time_frames = ev.time();
298
299         _write_data_count += ev.size();
300
301         if (_model) {
302                 const double ev_time_beats = converter.from(ev.time());
303                 const Evoral::Event<double> beat_ev(
304                                 ev.event_type(), ev_time_beats, ev.size(), (uint8_t*)ev.buffer());
305                 _model->append(beat_ev);
306         }
307 }
308
309 XMLNode&
310 SMFSource::get_state ()
311 {
312         return MidiSource::get_state();
313 }
314
315 int
316 SMFSource::set_state (const XMLNode& node)
317 {
318         if (Source::set_state (node)) {
319                 return -1;
320         }
321
322         if (MidiSource::set_state (node)) {
323                 return -1;
324         }
325         
326         if (FileSource::set_state (node)) {
327                 return -1;
328         }
329
330         return 0;
331 }
332
333 void
334 SMFSource::mark_streaming_midi_write_started (NoteMode mode, sframes_t start_frame)
335 {
336         MidiSource::mark_streaming_midi_write_started (mode, start_frame);
337         Evoral::SMF::begin_write ();
338         _last_ev_time_beats = 0.0;
339         _last_ev_time_frames = 0;
340 }
341
342 void
343 SMFSource::mark_streaming_write_completed ()
344 {
345         MidiSource::mark_streaming_write_completed();
346
347         if (!writable()) {
348                 return;
349         }
350         
351         _model->set_edited(false);
352         Evoral::SMF::end_write ();
353 }
354
355 bool
356 SMFSource::safe_midi_file_extension (const Glib::ustring& file)
357 {
358         return (file.rfind(".mid") != Glib::ustring::npos);
359 }
360
361 void
362 SMFSource::load_model (bool lock, bool force_reload)
363 {
364         if (_writing) {
365                 return;
366         }
367         
368         if (lock) {
369                 Glib::Mutex::Lock lm (_lock);
370         }
371
372         if (_model && !force_reload) {
373                 return;
374         }
375
376         if (! _model) {
377                 _model = boost::shared_ptr<MidiModel>(new MidiModel(this));
378                 cerr << _name << " loaded new model " << _model.get() << endl;
379         } else {
380                 cerr << _name << " reloading model " << _model.get()
381                         << " (" << _model->n_notes() << " notes)" <<endl;
382                 _model->clear();
383         }
384
385         _model->start_write();
386         Evoral::SMF::seek_to_start();
387
388         uint64_t time = 0; /* in SMF ticks */
389         Evoral::Event<double> ev;
390         
391         size_t scratch_size = 0; // keep track of scratch and minimize reallocs
392         
393         uint32_t delta_t = 0;
394         uint32_t size    = 0;
395         uint8_t* buf     = NULL;
396         int ret;
397         while ((ret = read_event(&delta_t, &size, &buf)) >= 0) {
398                 time += delta_t;
399                 ev.set(buf, size, time / (double)ppqn());
400                 
401                 if (ret > 0) { // didn't skip (meta) event
402                         ev.set_event_type(EventTypeMap::instance().midi_event_type(buf[0]));
403                         _model->append(ev);
404                 }
405
406                 if (ev.size() > scratch_size) {
407                         scratch_size = ev.size();
408                 }
409                 ev.size() = scratch_size; // ensure read_event only allocates if necessary
410                 
411                 _length_beats = max(_length_beats, ev.time());
412         }
413
414         set_default_controls_interpolation();
415         
416         _model->end_write(false);
417         _model->set_edited(false);
418
419         _model_iter = _model->begin();
420
421         free(buf);
422 }
423
424 #define LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY 0
425
426 void
427 SMFSource::set_default_controls_interpolation ()
428 {
429         // set interpolation style to defaults, can be changed by the GUI later
430         Evoral::ControlSet::Controls controls = _model->controls();
431         for (Evoral::ControlSet::Controls::iterator c = controls.begin(); c != controls.end(); ++c) {
432                 (*c).second->list()->set_interpolation(
433                         // to be enabled when ControlList::rt_safe_earliest_event_linear_unlocked works properly
434                         #if LINEAR_INTERPOLATION_MODE_WORKS_PROPERLY
435                         EventTypeMap::instance().interpolation_of((*c).first));
436                         #else
437                         Evoral::ControlList::Discrete);
438                         #endif
439         }
440 }
441
442
443 void
444 SMFSource::destroy_model ()
445 {
446         //cerr << _name << " destroying model " << _model.get() << endl;
447         _model.reset();
448 }
449
450 void
451 SMFSource::flush_midi ()
452 {
453         Evoral::SMF::end_write();
454 }
455