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