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);
99 if (earliest_control.first && earliest_control.second.first < _event.time())
100 model.control_to_midi_event(_event, earliest_control);
102 _control_iter = _control_iters.end();
104 if (_event.size() == 0) {
105 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
107 _model->read_unlock();
110 // printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
115 MidiModel::const_iterator::~const_iterator()
118 _model->read_unlock();
122 const MidiModel::const_iterator&
123 MidiModel::const_iterator::operator++()
126 throw std::logic_error("Attempt to iterate past end of MidiModel");
128 assert(_event.is_note() || _event.is_cc());
130 // Increment past current control event
131 if (_control_iter->first && _event.is_cc()) {
133 const bool ret = _control_iter->first->rt_safe_earliest_event_unlocked(
134 _control_iter->second.first, DBL_MAX, x, y, false);
137 //cerr << "Incremented " << _control_iter->first->parameter().id() << " to " << x << endl;
138 _control_iter->second.first = x;
139 _control_iter->second.second = y;
141 //cerr << "Hit end of " << _control_iter->first->parameter().id() << endl;
142 _control_iter->first.reset();
143 _control_iter->second.first = DBL_MAX;
147 // Now find and point at the earliest event
149 _control_iter = _control_iters.begin();
151 for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
152 i != _control_iters.end(); ++i) {
153 if (i->second.first < _control_iter->second.first) {
158 enum Type { NIL, NOTE, CC };
161 if (_note_iter != _model->notes().end())
164 if (_control_iter != _control_iters.end() && _control_iter->second.first != DBL_MAX)
165 if (_note_iter == _model->notes().end() || _control_iter->second.first < _note_iter->time())
169 //cerr << "MIDI Iterator = note" << endl;
170 _event = MidiEvent(_note_iter->on_event(), false);
172 } else if (type == CC) {
173 //cerr << "MIDI Iterator = CC" << endl;
174 _model->control_to_midi_event(_event, *_control_iter);
176 //cerr << "MIDI Iterator = NIL" << endl;
178 _model->read_unlock();
187 MidiModel::const_iterator::operator==(const const_iterator& other) const
195 return (_event == other._event);
201 MidiModel::MidiModel(Session& s, size_t size)
202 : Automatable(s, "midi model")
204 , _note_mode(Sustained)
207 //, _active_notes(LaterNoteEndComparator())
208 , _end_iter(*this, DBL_MAX)
209 , _next_read(UINT32_MAX)
210 , _read_iter(*this, DBL_MAX)
215 /** Read events in frame range \a start .. \a start+cnt into \a dst,
216 * adding \a stamp_offset to each event's timestamp.
217 * \return number of events written to \a dst
220 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset) const
222 size_t read_events = 0;
224 if (start != _next_read) {
225 _read_iter = const_iterator(*this, (double)start);
226 // cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
228 // cerr << "Using cached iterator at " << _next_read << endl;
231 _next_read = start + nframes;
233 while (_read_iter != end() && _read_iter->time() < start + nframes) {
234 dst.write(_read_iter->time() + stamp_offset, _read_iter->size(), _read_iter->buffer());
240 /* FIXME: cache last lookup value to avoid O(n) search every time */
242 if (_note_mode == Sustained) {
244 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
246 while ( ! _active_notes.empty() ) {
247 const Note* const earliest_off = _active_notes.top();
248 const MidiEvent& off_ev = earliest_off->off_event();
249 if (off_ev.time() < start + nframes && off_ev.time() <= n->time()) {
250 dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
258 if (n->time() >= start + nframes)
262 if (n->time() >= start) {
263 const MidiEvent& on_ev = n->on_event();
264 dst.write(on_ev.time() + stamp_offset, on_ev.size(), on_ev.buffer());
265 _active_notes.push(&(*n));
271 // Write any trailing note offs
272 while ( ! _active_notes.empty() ) {
273 const Note* const earliest_off = _active_notes.top();
274 const MidiEvent& off_ev = earliest_off->off_event();
275 if (off_ev.time() < start + nframes) {
276 dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
286 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
288 if (n->time() >= start) {
289 if (n->time() < start + nframes) {
290 const MidiEvent& ev = n->on_event();
291 dst.write(ev.time() + stamp_offset, ev.size(), ev.buffer());
305 MidiModel::control_to_midi_event(MidiEvent& ev, const MidiControlIterator& iter) const
307 if (iter.first->parameter().type() == MidiCCAutomation) {
309 ev.set_buffer((Byte*)malloc(3), true);
312 assert(iter.first->parameter().id() <= INT8_MAX);
313 assert(iter.second.second <= INT8_MAX);
314 ev.buffer()[0] = MIDI_CMD_CONTROL;
315 ev.buffer()[1] = (Byte)iter.first->parameter().id();
316 ev.buffer()[2] = (Byte)iter.second.second;
317 ev.time() = iter.second.first; // x
326 /** Return the earliest MIDI event in the given range.
328 * \return true if \a output has been set to the earliest event in the given range.
332 MidiModel::earliest_note_event(MidiEvent& output, nframes_t start, nframes_t nframes) const
334 /* FIXME: cache last lookup value to avoid O(n) search every time */
336 const Note* const earliest_on = NULL;
337 const Note* const earliest_off = NULL;
338 const MidiEvent* const earliest_cc = NULL;
342 if (_note_mode == Sustained) {
344 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
346 if ( ! _active_notes.empty() ) {
347 const Note* const earliest_off = _active_notes.top();
348 const MidiEvent& off_ev = earliest_off->off_event();
349 if (off_ev.time() < start + nframes && off_ev.time() <= n->time()) {
351 //dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
357 if (n->time() >= start + nframes)
361 if (n->time() >= start) {
362 earliest_on = &n->on_event();
363 //dst.write(on_ev.time() + stamp_offset, on_ev.size(), on_ev.buffer());
364 _active_notes.push(&(*n));
370 // Write any trailing note offs
371 while ( ! _active_notes.empty() ) {
372 const Note* const earliest_off = _active_notes.top();
373 const MidiEvent& off_ev = earliest_off->off_event();
374 if (off_ev.time() < start + nframes) {
375 dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
385 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
387 if (n->time() >= start) {
388 if (n->time() < start + nframes) {
389 const MidiEvent& ev = n->on_event();
390 dst.write(ev.time() + stamp_offset, ev.size(), ev.buffer());
403 /** Begin a write of events to the model.
405 * If \a mode is Sustained, complete notes with duration are constructed as note
406 * on/off events are received. Otherwise (Percussive), only note on events are
407 * stored; note off events are discarded entirely and all contained notes will
411 MidiModel::start_write()
413 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
416 _write_notes.clear();
422 /** Finish a write of events to the model.
424 * If \a delete_stuck is true and the current mode is Sustained, note on events
425 * that were never resolved with a corresonding note off will be deleted.
426 * Otherwise they will remain as notes with duration 0.
429 MidiModel::end_write(bool delete_stuck)
434 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
436 if (_note_mode == Sustained && delete_stuck) {
437 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
438 if (n->duration() == 0) {
439 cerr << "WARNING: Stuck note lost: " << n->note() << endl;
447 _write_notes.clear();
453 /** Append contents of \a buf to model. NOT realtime safe.
455 * Timestamps of events in \a buf are expected to be relative to
456 * the start of this model (t=0) and MUST be monotonically increasing
457 * and MUST be >= the latest event currently in the model.
459 * Events in buf are deep copied.
462 MidiModel::append(const MidiBuffer& buf)
468 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
469 assert(_notes.empty() || (*i).time() >= _notes.back().time());
477 /** Append \a in_event to model. NOT realtime safe.
479 * Timestamps of events in \a buf are expected to be relative to
480 * the start of this model (t=0) and MUST be monotonically increasing
481 * and MUST be >= the latest event currently in the model.
484 MidiModel::append(const MidiEvent& ev)
488 assert(_notes.empty() || ev.time() >= _notes.back().time());
492 append_note_on_unlocked(ev.time(), ev.note(), ev.velocity());
493 else if (ev.is_note_off())
494 append_note_off_unlocked(ev.time(), ev.note());
496 append_cc_unlocked(ev.time(), ev.cc_number(), ev.cc_value());
498 printf("MM Unknown event type %X\n", ev.type());
505 MidiModel::append_note_on_unlocked(double time, uint8_t note_num, uint8_t velocity)
507 //cerr << "MidiModel " << this << " note " << (int)note_num << " on @ " << time << endl;
510 _notes.push_back(Note(time, 0, note_num, velocity));
511 if (_note_mode == Sustained) {
512 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
513 _write_notes.push_back(_notes.size() - 1);
515 //cerr << "MM Percussive: NOT appending active note on" << endl;
521 MidiModel::append_note_off_unlocked(double time, uint8_t note_num)
523 //cerr << "MidiModel " << this << " note " << (int)note_num << " off @ " << time << endl;
526 if (_note_mode == Percussive) {
527 //cerr << "MM Ignoring note off (percussive mode)" << endl;
530 //cerr << "MM Attempting to resolve note off " << (unsigned)(uint8_t)note_num << endl;
533 /* FIXME: make _write_notes fixed size (127 noted) for speed */
535 /* FIXME: note off velocity for that one guy out there who actually has
536 * keys that send it */
538 for (WriteNotes::iterator n = _write_notes.begin(); n != _write_notes.end(); ++n) {
539 Note& note = _notes[*n];
540 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
541 if (note.note() == note_num) {
542 assert(time > note.time());
543 note.set_duration(time - note.time());
544 _write_notes.erase(n);
545 //cerr << "MM resolved note, duration: " << note.duration() << endl;
553 MidiModel::append_cc_unlocked(double time, uint8_t number, uint8_t value)
555 Parameter param(MidiCCAutomation, number);
557 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
558 //cerr << "MidiModel " << this << "(" << control.get() << ") add CC " << (int)number << " = " << (int)value
559 // << " @ " << time << endl;
560 control->list()->fast_simple_add(time, (double)value);
565 MidiModel::add_note_unlocked(const Note& note)
567 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
568 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
569 _notes.insert(i, note);
574 MidiModel::remove_note_unlocked(const Note& note)
576 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
577 Notes::iterator n = find(_notes.begin(), _notes.end(), note);
578 if (n != _notes.end())
582 /** Slow! for debugging only. */
585 MidiModel::is_sorted() const
588 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
598 /** Start a new command.
600 * This has no side-effects on the model or Session, the returned command
601 * can be held on to for as long as the caller wishes, or discarded without
602 * formality, until apply_command is called and ownership is taken.
604 MidiModel::DeltaCommand*
605 MidiModel::new_delta_command(const string name)
607 DeltaCommand* cmd = new DeltaCommand(*this, name);
614 * Ownership of cmd is taken, it must not be deleted by the caller.
615 * The command will constitute one item on the undo stack.
618 MidiModel::apply_command(Command* cmd)
620 _session.begin_reversible_command(cmd->name());
623 _session.commit_reversible_command(cmd);
632 MidiModel::DeltaCommand::add(const Note& note)
634 //cerr << "MEC: apply" << endl;
636 _removed_notes.remove(note);
637 _added_notes.push_back(note);
642 MidiModel::DeltaCommand::remove(const Note& note)
644 //cerr << "MEC: remove" << endl;
646 _added_notes.remove(note);
647 _removed_notes.push_back(note);
652 MidiModel::DeltaCommand::operator()()
654 // This could be made much faster by using a priority_queue for added and
655 // removed notes (or sort here), and doing a single iteration over _model
659 for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
660 _model.add_note_unlocked(*i);
662 for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
663 _model.remove_note_unlocked(*i);
665 _model.write_unlock();
667 _model.ContentsChanged(); /* EMIT SIGNAL */
672 MidiModel::DeltaCommand::undo()
674 // This could be made much faster by using a priority_queue for added and
675 // removed notes (or sort here), and doing a single iteration over _model
679 for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
680 _model.remove_note_unlocked(*i);
682 for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
683 _model.add_note_unlocked(*i);
685 _model.write_unlock();
687 _model.ContentsChanged(); /* EMIT SIGNAL */
692 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
694 //cerr << "Writing model to " << source->name() << endl;
696 /* This could be done using a temporary MidiRingBuffer and using
697 * MidiModel::read and MidiSource::write, but this is more efficient
698 * and doesn't require any buffer size assumptions (ie it's worth
699 * the code duplication).
701 * This is also different from read in that note off events are written
702 * regardless of the track mode. This is so the user can switch a
703 * recorded track (with note durations from some instrument) to percussive,
704 * save, reload, then switch it back to sustained preserving the original
709 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
710 const MidiEvent& ev = n->on_event();
711 source->append_event_unlocked(ev);
716 LaterNoteEndComparator cmp;
717 ActiveNotes active_notes(cmp);
720 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
722 // Write any pending note offs earlier than this note on
723 while ( ! active_notes.empty() ) {
724 const Note* const earliest_off = active_notes.top();
725 const MidiEvent& off_ev = earliest_off->off_event();
726 if (off_ev.time() <= n->time()) {
727 source->append_event_unlocked(off_ev);
734 // Write this note on
735 source->append_event_unlocked(n->on_event());
736 if (n->duration() > 0)
737 active_notes.push(&(*n));
740 // Write any trailing note offs
741 while ( ! active_notes.empty() ) {
742 source->append_event_unlocked(active_notes.top()->off_event());
754 MidiModel::get_state()
756 XMLNode *node = new XMLNode("MidiModel");