2 Copyright (C) 2007 Paul Davis
3 Written by Dave Robillard, 2007
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.
21 #define __STDC_LIMIT_MACROS 1
27 #include <pbd/enumwriter.h>
28 #include <ardour/midi_model.h>
29 #include <ardour/midi_events.h>
30 #include <ardour/midi_source.h>
31 #include <ardour/types.h>
32 #include <ardour/session.h>
35 using namespace ARDOUR;
38 // Read iterator (const_iterator)
40 MidiModel::const_iterator::const_iterator(const MidiModel& model, double t)
42 , _is_end( (t == DBL_MAX) || model.empty())
45 //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl;
52 _note_iter = model.notes().end();
54 for (MidiModel::Notes::const_iterator i = model.notes().begin(); i != model.notes().end(); ++i) {
55 if ((*i)->time() >= t) {
61 MidiControlIterator earliest_control = make_pair(boost::shared_ptr<AutomationList>(),
62 make_pair(DBL_MAX, 0.0));
64 _control_iters.reserve(model.controls().size());
65 for (Automatable::Controls::const_iterator i = model.controls().begin();
66 i != model.controls().end(); ++i) {
68 assert(i->first.type() == MidiCCAutomation);
71 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
73 /*cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
74 << ") has no events past " << t << endl;*/
80 assert(y <= UINT8_MAX);
82 const MidiControlIterator new_iter = make_pair(i->second->list(), make_pair(x, y));
84 //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
85 _control_iters.push_back(new_iter);
87 if (x < earliest_control.second.first) {
88 earliest_control = new_iter;
89 _control_iter = _control_iters.end();
94 if (_note_iter != model.notes().end()) {
95 _event = MidiEvent((*_note_iter)->on_event(), false);
96 _active_notes.push(*_note_iter);
100 if (earliest_control.first && earliest_control.second.first < _event.time())
101 model.control_to_midi_event(_event, earliest_control);
103 _control_iter = _control_iters.end();
105 if (_event.size() == 0) {
106 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
108 _model->read_unlock();
111 printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
116 MidiModel::const_iterator::~const_iterator()
119 _model->read_unlock();
123 const MidiModel::const_iterator&
124 MidiModel::const_iterator::operator++()
127 throw std::logic_error("Attempt to iterate past end of MidiModel");
129 assert(_event.is_note() || _event.is_cc());
131 // Increment past current control event
132 if (_control_iter != _control_iters.end() && _control_iter->first && _event.is_cc()) {
134 const bool ret = _control_iter->first->rt_safe_earliest_event_unlocked(
135 _control_iter->second.first, DBL_MAX, x, y, false);
138 //cerr << "Incremented " << _control_iter->first->parameter().id() << " to " << x << endl;
139 _control_iter->second.first = x;
140 _control_iter->second.second = y;
142 //cerr << "Hit end of " << _control_iter->first->parameter().id() << endl;
143 _control_iter->first.reset();
144 _control_iter->second.first = DBL_MAX;
148 // Now find and point at the earliest event
150 _control_iter = _control_iters.begin();
152 for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
153 i != _control_iters.end(); ++i) {
154 if (i->second.first < _control_iter->second.first) {
159 enum Type { NIL, NOTE_ON, NOTE_OFF, CC };
164 // Next earliest note on
165 if (_note_iter != _model->notes().end()) {
167 t = (*_note_iter)->time();
170 // Use the next earliest note off iff it's earlier than the note on
171 if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
172 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
174 t = _active_notes.top()->end_time();
178 // Use the next earliest controller iff it's earlier than the note event
179 if (_control_iter != _control_iters.end() && _control_iter->second.first != DBL_MAX)
180 if (type == NIL || _control_iter->second.first < t)
183 if (type == NOTE_ON) {
184 //cerr << "********** MIDI Iterator = note on" << endl;
185 _event = MidiEvent((*_note_iter)->on_event(), false);
186 _active_notes.push(*_note_iter);
188 } else if (type == NOTE_OFF) {
189 //cerr << "********** MIDI Iterator = note off" << endl;
190 _event = MidiEvent(_active_notes.top()->off_event(), false);
192 } else if (type == CC) {
193 //cerr << "********** MIDI Iterator = CC" << endl;
194 _model->control_to_midi_event(_event, *_control_iter);
196 //cerr << "********** MIDI Iterator = END" << endl;
198 _model->read_unlock();
202 assert(_is_end || _event.size() > 0);
209 MidiModel::const_iterator::operator==(const const_iterator& other) const
211 if (_is_end || other._is_end)
212 return (_is_end == other._is_end);
214 return (_event == other._event);
218 MidiModel::const_iterator&
219 MidiModel::const_iterator::operator=(const const_iterator& other)
221 if (_locked && _model != other._model)
222 _model->read_unlock();
224 assert( ! other._event.owns_buffer());
226 _model = other._model;
227 _event = other._event;
228 _is_end = other._is_end;
229 _locked = other._locked;
230 _note_iter = other._note_iter;
231 _control_iters = other._control_iters;
232 _control_iter = other._control_iter;
234 assert( ! _event.owns_buffer());
245 MidiModel::MidiModel(Session& s, size_t size)
246 : Automatable(s, "midi model")
248 , _note_mode(Sustained)
251 , _end_iter(*this, DBL_MAX)
252 , _next_read(UINT32_MAX)
253 , _read_iter(*this, DBL_MAX)
255 assert(_end_iter._is_end);
256 assert( ! _end_iter._locked);
260 /** Read events in frame range \a start .. \a start+cnt into \a dst,
261 * adding \a stamp_offset to each event's timestamp.
262 * \return number of events written to \a dst
265 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset) const
267 //cerr << this << " MM::read @ " << start << " * " << nframes << " + " << stamp_offset << endl;
268 //cerr << this << " MM # notes: " << n_notes() << endl;
270 size_t read_events = 0;
272 if (start != _next_read) {
273 _read_iter = const_iterator(*this, (double)start);
274 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
276 //cerr << "Using cached iterator at " << _next_read << endl;
279 if (_read_iter == end()) {
280 //cerr << this << " MM::read: at end @ " << _read_iter->time() << endl;
282 //cerr << this << " MM::read: at " << _read_iter->time() << endl;
285 _next_read = start + nframes;
287 while (_read_iter != end() && _read_iter->time() < start + nframes) {
288 assert(_read_iter->size() > 0);
289 dst.write(_read_iter->time() + stamp_offset, _read_iter->size(), _read_iter->buffer());
290 //cerr << this << " MM::read event @ " << _read_iter->time() << endl;
300 MidiModel::control_to_midi_event(MidiEvent& ev, const MidiControlIterator& iter) const
302 if (iter.first->parameter().type() == MidiCCAutomation) {
304 ev.set_buffer((Byte*)malloc(3), true);
307 assert(iter.first->parameter().id() <= INT8_MAX);
308 assert(iter.second.second <= INT8_MAX);
309 ev.buffer()[0] = MIDI_CMD_CONTROL;
310 ev.buffer()[1] = (Byte)iter.first->parameter().id();
311 ev.buffer()[2] = (Byte)iter.second.second;
312 ev.time() = iter.second.first; // x
321 /** Begin a write of events to the model.
323 * If \a mode is Sustained, complete notes with duration are constructed as note
324 * on/off events are received. Otherwise (Percussive), only note on events are
325 * stored; note off events are discarded entirely and all contained notes will
329 MidiModel::start_write()
331 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
334 _write_notes.clear();
340 /** Finish a write of events to the model.
342 * If \a delete_stuck is true and the current mode is Sustained, note on events
343 * that were never resolved with a corresonding note off will be deleted.
344 * Otherwise they will remain as notes with duration 0.
347 MidiModel::end_write(bool delete_stuck)
352 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
354 if (_note_mode == Sustained && delete_stuck) {
355 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
356 if ((*n)->duration() == 0) {
357 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
365 _write_notes.clear();
371 /** Append \a in_event to model. NOT realtime safe.
373 * Timestamps of events in \a buf are expected to be relative to
374 * the start of this model (t=0) and MUST be monotonically increasing
375 * and MUST be >= the latest event currently in the model.
378 MidiModel::append(const MidiEvent& ev)
382 assert(_notes.empty() || ev.time() >= _notes.back()->time());
386 append_note_on_unlocked(ev.time(), ev.note(), ev.velocity());
387 else if (ev.is_note_off())
388 append_note_off_unlocked(ev.time(), ev.note());
390 append_cc_unlocked(ev.time(), ev.cc_number(), ev.cc_value());
392 printf("MM Unknown event type %X\n", ev.type());
399 MidiModel::append_note_on_unlocked(double time, uint8_t note_num, uint8_t velocity)
401 //cerr << "MidiModel " << this << " note " << (int)note_num << " on @ " << time << endl;
404 _notes.push_back(boost::shared_ptr<Note>(new Note(time, 0, note_num, velocity)));
405 if (_note_mode == Sustained) {
406 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
407 _write_notes.push_back(_notes.size() - 1);
409 //cerr << "MM Percussive: NOT appending active note on" << endl;
415 MidiModel::append_note_off_unlocked(double time, uint8_t note_num)
417 //cerr << "MidiModel " << this << " note " << (int)note_num << " off @ " << time << endl;
420 if (_note_mode == Percussive) {
421 //cerr << "MM Ignoring note off (percussive mode)" << endl;
424 //cerr << "MM Attempting to resolve note off " << (unsigned)(uint8_t)note_num << endl;
427 /* FIXME: make _write_notes fixed size (127 noted) for speed */
429 /* FIXME: note off velocity for that one guy out there who actually has
430 * keys that send it */
432 for (WriteNotes::iterator n = _write_notes.begin(); n != _write_notes.end(); ++n) {
433 Note& note = *_notes[*n].get();
434 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
435 if (note.note() == note_num) {
436 assert(time > note.time());
437 note.set_duration(time - note.time());
438 _write_notes.erase(n);
439 //cerr << "MM resolved note, duration: " << note.duration() << endl;
447 MidiModel::append_cc_unlocked(double time, uint8_t number, uint8_t value)
449 Parameter param(MidiCCAutomation, number);
451 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
452 //cerr << "MidiModel " << this << "(" << control.get() << ") add CC " << (int)number << " = " << (int)value
453 // << " @ " << time << endl;
454 control->list()->fast_simple_add(time, (double)value);
459 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
461 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
462 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
463 _notes.insert(i, note);
468 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
470 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
471 Notes::iterator n = find(_notes.begin(), _notes.end(), note);
472 if (n != _notes.end())
476 /** Slow! for debugging only. */
479 MidiModel::is_sorted() const
482 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
483 if ((*n)->time() < t)
492 /** Start a new command.
494 * This has no side-effects on the model or Session, the returned command
495 * can be held on to for as long as the caller wishes, or discarded without
496 * formality, until apply_command is called and ownership is taken.
498 MidiModel::DeltaCommand*
499 MidiModel::new_delta_command(const string name)
501 DeltaCommand* cmd = new DeltaCommand(*this, name);
508 * Ownership of cmd is taken, it must not be deleted by the caller.
509 * The command will constitute one item on the undo stack.
512 MidiModel::apply_command(Command* cmd)
514 _session.begin_reversible_command(cmd->name());
517 _session.commit_reversible_command(cmd);
526 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
528 //cerr << "MEC: apply" << endl;
530 _removed_notes.remove(note);
531 _added_notes.push_back(note);
536 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
538 //cerr << "MEC: remove" << endl;
540 _added_notes.remove(note);
541 _removed_notes.push_back(note);
546 MidiModel::DeltaCommand::operator()()
548 // This could be made much faster by using a priority_queue for added and
549 // removed notes (or sort here), and doing a single iteration over _model
551 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
552 const bool reset_iter = (_model._read_iter.locked());
553 const double iter_time = _model._read_iter->time();
556 _model._read_iter = _model.end(); // drop read lock
558 assert( ! _model._read_iter.locked());
562 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
563 _model.add_note_unlocked(*i);
565 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
566 _model.remove_note_unlocked(*i);
568 _model.write_unlock();
571 _model._read_iter = const_iterator(_model, iter_time);
573 _model.ContentsChanged(); /* EMIT SIGNAL */
578 MidiModel::DeltaCommand::undo()
580 // This could be made much faster by using a priority_queue for added and
581 // removed notes (or sort here), and doing a single iteration over _model
583 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
584 const bool reset_iter = (_model._read_iter.locked());
585 const double iter_time = _model._read_iter->time();
588 _model._read_iter = _model.end(); // drop read lock
590 assert( ! _model._read_iter.locked());
594 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
595 _model.remove_note_unlocked(*i);
597 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
598 _model.add_note_unlocked(*i);
600 _model.write_unlock();
603 _model._read_iter = const_iterator(_model, iter_time);
605 _model.ContentsChanged(); /* EMIT SIGNAL */
610 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
612 //cerr << "Writing model to " << source->name() << endl;
614 /* This could be done using a temporary MidiRingBuffer and using
615 * MidiModel::read and MidiSource::write, but this is more efficient
616 * and doesn't require any buffer size assumptions (ie it's worth
617 * the code duplication).
619 * This is also different from read in that note off events are written
620 * regardless of the track mode. This is so the user can switch a
621 * recorded track (with note durations from some instrument) to percussive,
622 * save, reload, then switch it back to sustained preserving the original
627 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
628 const MidiEvent& ev = n->on_event();
629 source->append_event_unlocked(ev);
634 LaterNoteEndComparator cmp;
635 ActiveNotes active_notes(cmp);
638 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
640 // Write any pending note offs earlier than this note on
641 while ( ! active_notes.empty() ) {
642 const boost::shared_ptr<const Note> earliest_off = active_notes.top();
643 const MidiEvent& off_ev = earliest_off->off_event();
644 if (off_ev.time() <= (*n)->time()) {
645 source->append_event_unlocked(off_ev);
652 // Write this note on
653 source->append_event_unlocked((*n)->on_event());
654 if ((*n)->duration() > 0)
655 active_notes.push(*n);
658 // Write any trailing note offs
659 while ( ! active_notes.empty() ) {
660 source->append_event_unlocked(active_notes.top()->off_event());
672 MidiModel::get_state()
674 XMLNode *node = new XMLNode("MidiModel");