2 Copyright (C) 2006 Paul Davis
3 Written by Dave Robillard, 2006
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.
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.
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.
28 #include "pbd/mountpoint.h"
29 #include "pbd/pathscanner.h"
30 #include "pbd/stl_delete.h"
31 #include "pbd/strsplit.h"
33 #include <glibmm/miscutils.h>
35 #include "evoral/Control.hpp"
37 #include "ardour/audioengine.h"
38 #include "ardour/event_type_map.h"
39 #include "ardour/midi_model.h"
40 #include "ardour/midi_ring_buffer.h"
41 #include "ardour/midi_state_tracker.h"
42 #include "ardour/session.h"
43 #include "ardour/smf_source.h"
44 #include "ardour/debug.h"
48 using namespace ARDOUR
;
52 /** Constructor used for new internal-to-session files. File cannot exist. */
53 SMFSource::SMFSource (Session
& s
, const ustring
& path
, Source::Flag flags
)
54 : Source(s
, DataType::MIDI
, path
, flags
)
56 , FileSource(s
, DataType::MIDI
, path
, flags
)
58 , _last_ev_time_beats(0.0)
59 , _last_ev_time_frames(0)
60 , _smf_last_read_end (0)
61 , _smf_last_read_time (0)
63 if (init(_path
, false)) {
64 throw failed_constructor ();
68 throw failed_constructor ();
71 load_model(true, true); // FIXME
74 /** Constructor used for existing internal-to-session files. */
75 SMFSource::SMFSource (Session
& s
, const XMLNode
& node
, bool must_exist
)
78 , FileSource(s
, node
, must_exist
)
79 , _last_ev_time_beats(0.0)
80 , _last_ev_time_frames(0)
81 , _smf_last_read_end (0)
82 , _smf_last_read_time (0)
84 if (set_state(node
, Stateful::loading_state_version
)) {
85 throw failed_constructor ();
88 if (init(_path
, true)) {
89 throw failed_constructor ();
93 throw failed_constructor ();
96 load_model(true, true); // FIXME
99 SMFSource::~SMFSource ()
102 unlink (_path
.c_str());
106 /** All stamps in audio frames */
108 SMFSource::read_unlocked (Evoral::EventSink
<nframes_t
>& destination
, sframes_t source_start
,
109 sframes_t start
, nframes_t duration
,
110 sframes_t stamp_offset
, sframes_t negative_stamp_offset
,
111 MidiStateTracker
* tracker
) const
114 uint64_t time
= 0; // in SMF ticks, 1 tick per _ppqn
116 DEBUG_TRACE (DEBUG::MidiSourceIO
, string_compose ("SMF read_unlocked: start %1 duration %2\n", start
, duration
));
118 _read_data_count
= 0;
120 // Output parameters for read_event (which will allocate scratch in buffer as needed)
121 uint32_t ev_delta_t
= 0;
122 uint32_t ev_type
= 0;
123 uint32_t ev_size
= 0;
124 uint8_t* ev_buffer
= 0;
126 size_t scratch_size
= 0; // keep track of scratch to minimize reallocs
128 BeatsFramesConverter
converter(_session
.tempo_map(), source_start
);
130 const uint64_t start_ticks
= (uint64_t)(converter
.from(start
) * ppqn());
131 DEBUG_TRACE (DEBUG::MidiSourceIO
, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks
));
133 if (_smf_last_read_end
== 0 || start
!= _smf_last_read_end
) {
134 DEBUG_TRACE (DEBUG::MidiSourceIO
, string_compose ("SMF read_unlocked: seek to %1\n", start
));
135 Evoral::SMF::seek_to_start();
136 while (time
< start_ticks
) {
139 ret
= read_event(&ev_delta_t
, &ev_size
, &ev_buffer
, &ignored
);
140 if (ret
== -1) { // EOF
141 _smf_last_read_end
= start
+ duration
;
144 time
+= ev_delta_t
; // accumulate delta time
147 DEBUG_TRACE (DEBUG::MidiSourceIO
, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time
));
148 time
= _smf_last_read_time
;
151 _smf_last_read_end
= start
+ duration
;
154 gint ignored
; /* XXX don't ignore note id's ??*/
156 ret
= read_event(&ev_delta_t
, &ev_size
, &ev_buffer
, &ignored
);
157 if (ret
== -1) { // EOF
161 time
+= ev_delta_t
; // accumulate delta time
162 _smf_last_read_time
= time
;
164 if (ret
== 0) { // meta-event (skipped, just accumulate time)
168 ev_type
= EventTypeMap::instance().midi_event_type(ev_buffer
[0]);
170 DEBUG_TRACE (DEBUG::MidiSourceIO
, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
171 ev_delta_t
, time
, ev_buffer
[0], ev_type
));
173 assert(time
>= start_ticks
);
174 const sframes_t ev_frame_time
= converter
.to(time
/ (double)ppqn()) + stamp_offset
;
177 cerr
<< " frames = " << ev_frame_time
178 << " w/offset = " << ev_frame_time
- negative_stamp_offset
182 if (ev_frame_time
< start
+ duration
) {
183 destination
.write(ev_frame_time
- negative_stamp_offset
, ev_type
, ev_size
, ev_buffer
);
186 if (ev_buffer
[0] & MIDI_CMD_NOTE_ON
) {
187 tracker
->add (ev_buffer
[1], ev_buffer
[0] & 0xf);
188 } else if (ev_buffer
[0] & MIDI_CMD_NOTE_OFF
) {
189 tracker
->remove (ev_buffer
[1], ev_buffer
[0] & 0xf);
196 _read_data_count
+= ev_size
;
198 if (ev_size
> scratch_size
) {
199 scratch_size
= ev_size
;
201 ev_size
= scratch_size
; // ensure read_event only allocates if necessary
207 /** All stamps in audio frames */
209 SMFSource::write_unlocked (MidiRingBuffer
<nframes_t
>& source
, sframes_t position
, nframes_t duration
)
211 _write_data_count
= 0;
214 Evoral::EventType type
;
217 size_t buf_capacity
= 4;
218 uint8_t* buf
= (uint8_t*)malloc(buf_capacity
);
220 if (_model
&& ! _model
->writing()) {
221 _model
->start_write();
224 Evoral::MIDIEvent
<nframes_t
> ev
;
227 bool ret
= source
.peek_time(&time
);
228 if (!ret
|| time
> _last_write_end
+ duration
) {
232 ret
= source
.read_prefix(&time
, &type
, &size
);
234 cerr
<< "ERROR: Unable to read event prefix, corrupt MIDI ring buffer" << endl
;
238 if (size
> buf_capacity
) {
240 buf
= (uint8_t*)realloc(buf
, size
);
243 ret
= source
.read_contents(size
, buf
);
245 cerr
<< "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl
;
249 assert(time
>= position
);
252 ev
.set(buf
, size
, time
);
253 ev
.set_event_type(EventTypeMap::instance().midi_event_type(ev
.buffer()[0]));
254 ev
.set_id (Evoral::next_event_id());
256 if (!(ev
.is_channel_event() || ev
.is_smf_meta_event() || ev
.is_sysex())) {
257 /*cerr << "SMFSource: WARNING: caller tried to write non SMF-Event of type "
258 << std::hex << int(ev.buffer()[0]) << endl;*/
262 append_event_unlocked_frames(ev
, position
);
265 Evoral::SMF::flush();
268 ViewDataRangeReady(position
+ _last_write_end
, duration
); /* EMIT SIGNAL */
274 /** Append an event with a timestamp in beats (double) */
276 SMFSource::append_event_unlocked_beats (const Evoral::Event
<double>& ev
)
279 if (ev
.size() == 0) {
283 /* printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
284 name().c_str(), ev.id(), ev.time(), ev.size());
285 for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
287 assert(ev
.time() >= 0);
288 if (ev
.time() < _last_ev_time_beats
) {
289 cerr
<< "SMFSource: Warning: Skipping event with non-monotonic time" << endl
;
293 Evoral::event_id_t event_id
;
296 event_id
= Evoral::next_event_id();
302 _model
->append (ev
, event_id
);
305 _length_beats
= max(_length_beats
, ev
.time());
307 const double delta_time_beats
= ev
.time() - _last_ev_time_beats
;
308 const uint32_t delta_time_ticks
= (uint32_t)lrint(delta_time_beats
* (double)ppqn());
310 Evoral::SMF::append_event_delta(delta_time_ticks
, ev
.size(), ev
.buffer(), event_id
);
311 _last_ev_time_beats
= ev
.time();
313 _write_data_count
+= ev
.size();
317 /** Append an event with a timestamp in frames (nframes_t) */
319 SMFSource::append_event_unlocked_frames (const Evoral::Event
<nframes_t
>& ev
, sframes_t position
)
322 if (ev
.size() == 0) {
326 /* printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
327 name().c_str(), ev.id(), ev.time(), ev.size());
328 for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
330 if (ev
.time() < _last_ev_time_frames
) {
331 cerr
<< "SMFSource: Warning: Skipping event with non-monotonic time" << endl
;
335 BeatsFramesConverter
converter(_session
.tempo_map(), position
);
336 const double ev_time_beats
= converter
.from(ev
.time());
337 Evoral::event_id_t event_id
;
340 event_id
= Evoral::next_event_id();
346 const Evoral::Event
<double> beat_ev (ev
.event_type(),
349 (uint8_t*)ev
.buffer());
350 _model
->append (beat_ev
, event_id
);
353 _length_beats
= max(_length_beats
, ev_time_beats
);
355 const sframes_t delta_time_frames
= ev
.time() - _last_ev_time_frames
;
356 const double delta_time_beats
= converter
.from(delta_time_frames
);
357 const uint32_t delta_time_ticks
= (uint32_t)(lrint(delta_time_beats
* (double)ppqn()));
359 Evoral::SMF::append_event_delta(delta_time_ticks
, ev
.size(), ev
.buffer(), event_id
);
360 _last_ev_time_frames
= ev
.time();
362 _write_data_count
+= ev
.size();
367 SMFSource::get_state ()
369 return MidiSource::get_state();
373 SMFSource::set_state (const XMLNode
& node
, int version
)
375 if (Source::set_state (node
, version
)) {
379 if (MidiSource::set_state (node
, version
)) {
383 if (FileSource::set_state (node
, version
)) {
391 SMFSource::mark_streaming_midi_write_started (NoteMode mode
, sframes_t start_frame
)
393 Glib::Mutex::Lock
lm (_lock
);
394 MidiSource::mark_streaming_midi_write_started (mode
, start_frame
);
395 Evoral::SMF::begin_write ();
396 _last_ev_time_beats
= 0.0;
397 _last_ev_time_frames
= 0;
401 SMFSource::mark_streaming_write_completed ()
403 Glib::Mutex::Lock
lm (_lock
);
404 MidiSource::mark_streaming_write_completed();
411 _model
->set_edited(false);
414 Evoral::SMF::end_write ();
416 /* data in the file now, not removable */
418 mark_nonremovable ();
422 SMFSource::safe_midi_file_extension (const Glib::ustring
& file
)
424 return (file
.rfind(".mid") != Glib::ustring::npos
);
428 SMFSource::load_model (bool lock
, bool force_reload
)
434 boost::shared_ptr
<Glib::Mutex::Lock
> lm
;
436 lm
= boost::shared_ptr
<Glib::Mutex::Lock
>(new Glib::Mutex::Lock(_lock
));
438 if (_model
&& !force_reload
) {
443 _model
= boost::shared_ptr
<MidiModel
>(new MidiModel(this));
444 //cerr << _name << " loaded new model " << _model.get() << endl;
446 /*cerr << _name << " reloading model " << _model.get()
447 << " (" << _model->n_notes() << " notes)" << endl;*/
451 _model
->start_write();
452 Evoral::SMF::seek_to_start();
454 uint64_t time
= 0; /* in SMF ticks */
455 Evoral::Event
<double> ev
;
457 size_t scratch_size
= 0; // keep track of scratch and minimize reallocs
459 uint32_t delta_t
= 0;
464 bool have_event_id
= false;
466 while ((ret
= read_event (&delta_t
, &size
, &buf
, &event_id
)) >= 0) {
472 /* meta-event : did we get an event ID ?
476 have_event_id
= true;
484 /* not a meta-event */
486 ev
.set (buf
, size
, time
/ (double)ppqn());
487 ev
.set_event_type(EventTypeMap::instance().midi_event_type(buf
[0]));
489 if (!have_event_id
) {
490 event_id
= Evoral::next_event_id();
495 for (uint32_t xx
= 0; xx
< size
; ++xx
) {
497 snprintf (b
, sizeof (b
), "0x%x ", buf
[xx
]);
501 DEBUG_TRACE (DEBUG::MidiSourceIO
, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
502 delta_t
, time
, size
, ss
, ev
.event_type(), name()));
505 _model
->append (ev
, event_id
);
507 if (ev
.size() > scratch_size
) {
508 scratch_size
= ev
.size();
511 ev
.size() = scratch_size
; // ensure read_event only allocates if necessary
513 _length_beats
= max(_length_beats
, ev
.time());
516 /* event ID's must immediately precede the event they are for
519 have_event_id
= false;
522 _model
->end_write(false);
523 _model
->set_edited(false);
525 _model_iter
= _model
->begin();
531 SMFSource::destroy_model ()
533 //cerr << _name << " destroying model " << _model.get() << endl;
538 SMFSource::flush_midi ()
544 Evoral::SMF::end_write();
545 /* data in the file means its no longer removable */
546 mark_nonremovable ();
550 SMFSource::set_path (const string
& p
)
552 FileSource::set_path (p
);
553 SMF::set_path (_path
);