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 _next_read = start + nframes;
281 while (_read_iter != end() && _read_iter->time() < start + nframes) {
282 assert(_read_iter->size() > 0);
283 dst.write(_read_iter->time() + stamp_offset, _read_iter->size(), _read_iter->buffer());
284 //cerr << this << " MM::read event @ " << _read_iter->time() << endl;
294 MidiModel::control_to_midi_event(MidiEvent& ev, const MidiControlIterator& iter) const
296 if (iter.first->parameter().type() == MidiCCAutomation) {
298 ev.set_buffer((Byte*)malloc(3), true);
301 assert(iter.first->parameter().channel() < 16);
302 assert(iter.first->parameter().id() <= INT8_MAX);
303 assert(iter.second.second <= INT8_MAX);
304 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.first->parameter().channel();
305 ev.buffer()[1] = (Byte)iter.first->parameter().id();
306 ev.buffer()[2] = (Byte)iter.second.second;
307 ev.time() = iter.second.first; // x
316 /** Begin a write of events to the model.
318 * If \a mode is Sustained, complete notes with duration are constructed as note
319 * on/off events are received. Otherwise (Percussive), only note on events are
320 * stored; note off events are discarded entirely and all contained notes will
324 MidiModel::start_write()
326 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
329 for (int i = 0; i < 16; ++i)
330 _write_notes[i].clear();
336 /** Finish a write of events to the model.
338 * If \a delete_stuck is true and the current mode is Sustained, note on events
339 * that were never resolved with a corresonding note off will be deleted.
340 * Otherwise they will remain as notes with duration 0.
343 MidiModel::end_write(bool delete_stuck)
348 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
350 if (_note_mode == Sustained && delete_stuck) {
351 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
352 if ((*n)->duration() == 0) {
353 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
361 for (int i = 0; i < 16; ++i) {
362 if (!_write_notes[i].empty()) {
363 cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
364 << _write_notes[i].size() << " stuck notes" << endl;
366 _write_notes[i].clear();
374 /** Append \a in_event to model. NOT realtime safe.
376 * Timestamps of events in \a buf are expected to be relative to
377 * the start of this model (t=0) and MUST be monotonically increasing
378 * and MUST be >= the latest event currently in the model.
381 MidiModel::append(const MidiEvent& ev)
385 assert(_notes.empty() || ev.time() >= _notes.back()->time());
389 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
390 else if (ev.is_note_off())
391 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
393 append_cc_unlocked(ev.channel(), ev.time(), ev.cc_number(), ev.cc_value());
395 printf("MM Unknown event type %X\n", ev.type());
402 MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity)
404 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
405 " note " << (int)note_num << " on @ " << time << endl;*/
410 _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
411 if (_note_mode == Sustained) {
412 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
413 _write_notes[chan].push_back(_notes.size() - 1);
415 cerr << "MM Percussive: NOT appending active note on" << endl;
421 MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num)
423 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
424 " note " << (int)note_num << " off @ " << time << endl;*/
429 if (_note_mode == Percussive) {
430 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
434 /* FIXME: make _write_notes fixed size (127 noted) for speed */
436 /* FIXME: note off velocity for that one guy out there who actually has
437 * keys that send it */
439 bool resolved = false;
441 for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].end(); ++n) {
442 Note& note = *_notes[*n].get();
443 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
444 if (note.note() == note_num) {
445 assert(time >= note.time());
446 note.set_duration(time - note.time());
447 _write_notes[chan].erase(n);
448 //cerr << "MM resolved note, duration: " << note.duration() << endl;
455 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
456 << ", note " << (int)note_num << " @ " << time << endl;
461 MidiModel::append_cc_unlocked(uint8_t chan, double time, uint8_t number, uint8_t value)
463 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
464 " CC " << (int)number << " = " << (int)value << " @ " << time << endl;*/
469 Parameter param(MidiCCAutomation, number, chan);
471 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
472 control->list()->fast_simple_add(time, (double)value);
477 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
479 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
480 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
481 _notes.insert(i, note);
486 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
488 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
489 Notes::iterator n = find(_notes.begin(), _notes.end(), note);
490 if (n != _notes.end())
494 /** Slow! for debugging only. */
497 MidiModel::is_sorted() const
500 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
501 if ((*n)->time() < t)
510 /** Start a new command.
512 * This has no side-effects on the model or Session, the returned command
513 * can be held on to for as long as the caller wishes, or discarded without
514 * formality, until apply_command is called and ownership is taken.
516 MidiModel::DeltaCommand*
517 MidiModel::new_delta_command(const string name)
519 DeltaCommand* cmd = new DeltaCommand(*this, name);
526 * Ownership of cmd is taken, it must not be deleted by the caller.
527 * The command will constitute one item on the undo stack.
530 MidiModel::apply_command(Command* cmd)
532 _session.begin_reversible_command(cmd->name());
535 _session.commit_reversible_command(cmd);
544 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
546 //cerr << "MEC: apply" << endl;
548 _removed_notes.remove(note);
549 _added_notes.push_back(note);
554 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
556 //cerr << "MEC: remove" << endl;
558 _added_notes.remove(note);
559 _removed_notes.push_back(note);
564 MidiModel::DeltaCommand::operator()()
566 // This could be made much faster by using a priority_queue for added and
567 // removed notes (or sort here), and doing a single iteration over _model
569 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
570 const bool reset_iter = (_model._read_iter.locked());
571 const double iter_time = _model._read_iter->time();
574 _model._read_iter = _model.end(); // drop read lock
576 assert( ! _model._read_iter.locked());
580 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
581 _model.add_note_unlocked(*i);
583 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
584 _model.remove_note_unlocked(*i);
586 _model.write_unlock();
589 _model._read_iter = const_iterator(_model, iter_time);
591 _model.ContentsChanged(); /* EMIT SIGNAL */
596 MidiModel::DeltaCommand::undo()
598 // This could be made much faster by using a priority_queue for added and
599 // removed notes (or sort here), and doing a single iteration over _model
601 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
602 const bool reset_iter = (_model._read_iter.locked());
603 const double iter_time = _model._read_iter->time();
606 _model._read_iter = _model.end(); // drop read lock
608 assert( ! _model._read_iter.locked());
612 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
613 _model.remove_note_unlocked(*i);
615 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
616 _model.add_note_unlocked(*i);
618 _model.write_unlock();
621 _model._read_iter = const_iterator(_model, iter_time);
623 _model.ContentsChanged(); /* EMIT SIGNAL */
628 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
630 //cerr << "Writing model to " << source->name() << endl;
632 /* This could be done using a temporary MidiRingBuffer and using
633 * MidiModel::read and MidiSource::write, but this is more efficient
634 * and doesn't require any buffer size assumptions (ie it's worth
635 * the code duplication).
637 * This is also different from read in that note off events are written
638 * regardless of the track mode. This is so the user can switch a
639 * recorded track (with note durations from some instrument) to percussive,
640 * save, reload, then switch it back to sustained preserving the original
645 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
646 const MidiEvent& ev = n->on_event();
647 source->append_event_unlocked(ev);
652 LaterNoteEndComparator cmp;
653 ActiveNotes active_notes(cmp);
656 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
658 // Write any pending note offs earlier than this note on
659 while ( ! active_notes.empty() ) {
660 const boost::shared_ptr<const Note> earliest_off = active_notes.top();
661 const MidiEvent& off_ev = earliest_off->off_event();
662 if (off_ev.time() <= (*n)->time()) {
663 source->append_event_unlocked(off_ev);
670 // Write this note on
671 source->append_event_unlocked((*n)->on_event());
672 if ((*n)->duration() > 0)
673 active_notes.push(*n);
676 // Write any trailing note offs
677 while ( ! active_notes.empty() ) {
678 source->append_event_unlocked(active_notes.top()->off_event());
690 MidiModel::get_state()
692 XMLNode *node = new XMLNode("MidiModel");