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 <midi++/events.h>
30 #include <ardour/midi_model.h>
31 #include <ardour/midi_source.h>
32 #include <ardour/types.h>
33 #include <ardour/session.h>
36 using namespace ARDOUR;
40 MidiModel::write_lock()
43 _automation_lock.lock();
47 MidiModel::write_unlock()
49 _lock.writer_unlock();
50 _automation_lock.unlock();
54 MidiModel::read_lock() const
57 /*_automation_lock.lock();*/
61 MidiModel::read_unlock() const
63 _lock.reader_unlock();
64 /*_automation_lock.unlock();*/
67 // Read iterator (const_iterator)
69 MidiModel::const_iterator::const_iterator(const MidiModel& model, double t)
71 , _is_end( (t == DBL_MAX) || model.empty())
74 //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl;
81 _note_iter = model.notes().end();
82 // find first note which begins after t
83 for (MidiModel::Notes::const_iterator i = model.notes().begin(); i != model.notes().end(); ++i) {
84 if ((*i)->time() >= t) {
90 MidiControlIterator earliest_control = make_pair(boost::shared_ptr<AutomationList>(),
91 make_pair(DBL_MAX, 0.0));
93 _control_iters.reserve(model.controls().size());
94 for (Automatable::Controls::const_iterator i = model.controls().begin();
95 i != model.controls().end(); ++i) {
97 assert(i->first.type() == MidiCCAutomation);
100 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
102 /*cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
103 << ") has no events past " << t << endl;*/
109 assert(y <= UINT8_MAX);
111 const MidiControlIterator new_iter = make_pair(i->second->list(), make_pair(x, y));
113 //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
114 _control_iters.push_back(new_iter);
116 if (x < earliest_control.second.first) {
117 earliest_control = new_iter;
118 _control_iter = _control_iters.end();
123 if (_note_iter != model.notes().end()) {
124 _event = MIDI::Event((*_note_iter)->on_event(), false);
125 _active_notes.push(*_note_iter);
126 cerr << " new const iterator: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl;
130 if (earliest_control.first && earliest_control.second.first < _event.time())
131 model.control_to_midi_event(_event, earliest_control);
133 _control_iter = _control_iters.end();
135 if (_event.size() == 0) {
136 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
139 _model->read_unlock();
143 printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
148 MidiModel::const_iterator::~const_iterator()
151 _model->read_unlock();
156 const MidiModel::const_iterator&
157 MidiModel::const_iterator::operator++()
160 throw std::logic_error("Attempt to iterate past end of MidiModel");
162 assert(_event.is_note() || _event.is_cc());
164 // Increment past current control event
165 if (_control_iter != _control_iters.end() && _control_iter->first && _event.is_cc()) {
167 const bool ret = _control_iter->first->rt_safe_earliest_event_unlocked(
168 _control_iter->second.first, DBL_MAX, x, y, false);
171 //cerr << "Incremented " << _control_iter->first->parameter().id() << " to " << x << endl;
172 _control_iter->second.first = x;
173 _control_iter->second.second = y;
175 //cerr << "Hit end of " << _control_iter->first->parameter().id() << endl;
176 _control_iter->first.reset();
177 _control_iter->second.first = DBL_MAX;
181 // Now find and point at the earliest event
183 _control_iter = _control_iters.begin();
185 for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
186 i != _control_iters.end(); ++i) {
187 if (i->second.first < _control_iter->second.first) {
192 enum Type { NIL, NOTE_ON, NOTE_OFF, CC };
197 // Next earliest note on
198 if (_note_iter != _model->notes().end()) {
200 t = (*_note_iter)->time();
203 cerr << " operator++ before test: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl;
204 // Use the next earliest note off iff it's earlier than the note on
205 if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
206 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
208 t = _active_notes.top()->end_time();
212 // Use the next earliest controller iff it's earlier than the note event
213 if (_control_iter != _control_iters.end() && _control_iter->second.first != DBL_MAX)
214 if (type == NIL || _control_iter->second.first < t)
217 if (type == NOTE_ON) {
218 cerr << "********** MIDI Iterator = note on" << endl;
219 _event = MIDI::Event((*_note_iter)->on_event(), false);
220 _active_notes.push(*_note_iter);
222 } else if (type == NOTE_OFF) {
223 cerr << "********** MIDI Iterator = note off" << endl;
224 _event = MIDI::Event(_active_notes.top()->off_event(), false);
226 } else if (type == CC) {
227 cerr << "********** MIDI Iterator = CC" << endl;
228 _model->control_to_midi_event(_event, *_control_iter);
230 cerr << "********** MIDI Iterator = END" << endl;
234 assert(_is_end || _event.size() > 0);
241 MidiModel::const_iterator::operator==(const const_iterator& other) const
243 if (_is_end || other._is_end)
244 return (_is_end == other._is_end);
246 return (_event == other._event);
250 MidiModel::const_iterator&
251 MidiModel::const_iterator::operator=(const const_iterator& other)
253 if (_locked && _model != other._model)
254 _model->read_unlock();
256 assert( ! other._event.owns_buffer());
258 _model = other._model;
259 _event = other._event;
260 _active_notes = other._active_notes;
261 _is_end = other._is_end;
262 _locked = other._locked;
263 _note_iter = other._note_iter;
264 _control_iters = other._control_iters;
265 _control_iter = other._control_iter;
267 assert( ! _event.owns_buffer());
275 MidiModel::MidiModel(Session& s, size_t size)
276 : Automatable(s, "midi model")
278 , _note_mode(Sustained)
281 , _end_iter(*this, DBL_MAX)
282 , _next_read(UINT32_MAX)
283 , _read_iter(*this, DBL_MAX)
285 assert(_end_iter._is_end);
286 assert( ! _end_iter._locked);
290 /** Read events in frame range \a start .. \a start+cnt into \a dst,
291 * adding \a stamp_offset to each event's timestamp.
292 * \return number of events written to \a dst
295 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
297 cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
298 cerr << this << " MM # notes: " << n_notes() << endl;
300 size_t read_events = 0;
302 if (start != _next_read) {
303 _read_iter = const_iterator(*this, (double)start);
304 cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
306 cerr << "Using cached iterator at " << _next_read << endl;
309 _next_read = start + nframes;
311 while (_read_iter != end() && _read_iter->time() < start + nframes) {
312 assert(_read_iter->size() > 0);
313 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset, _read_iter->size(), _read_iter->buffer());
314 cerr << this << " MM::read event @ " << _read_iter->time()
315 << " type: " << hex << int(_read_iter->type()) << dec
316 << " note: " << int(_read_iter->note())
317 << " velocity: " << int(_read_iter->velocity())
328 MidiModel::control_to_midi_event(MIDI::Event& ev, const MidiControlIterator& iter) const
330 if (iter.first->parameter().type() == MidiCCAutomation) {
332 ev.set_buffer((Byte*)malloc(3), true);
335 assert(iter.first->parameter().channel() < 16);
336 assert(iter.first->parameter().id() <= INT8_MAX);
337 assert(iter.second.second <= INT8_MAX);
338 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.first->parameter().channel();
339 ev.buffer()[1] = (Byte)iter.first->parameter().id();
340 ev.buffer()[2] = (Byte)iter.second.second;
341 ev.time() = iter.second.first; // x
350 /** Begin a write of events to the model.
352 * If \a mode is Sustained, complete notes with duration are constructed as note
353 * on/off events are received. Otherwise (Percussive), only note on events are
354 * stored; note off events are discarded entirely and all contained notes will
358 MidiModel::start_write()
360 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
363 for (int i = 0; i < 16; ++i)
364 _write_notes[i].clear();
370 /** Finish a write of events to the model.
372 * If \a delete_stuck is true and the current mode is Sustained, note on events
373 * that were never resolved with a corresonding note off will be deleted.
374 * Otherwise they will remain as notes with duration 0.
377 MidiModel::end_write(bool delete_stuck)
382 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
384 if (_note_mode == Sustained && delete_stuck) {
385 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
386 if ((*n)->duration() == 0) {
387 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
395 for (int i = 0; i < 16; ++i) {
396 if (!_write_notes[i].empty()) {
397 cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
398 << _write_notes[i].size() << " stuck notes" << endl;
400 _write_notes[i].clear();
408 /** Append \a in_event to model. NOT realtime safe.
410 * Timestamps of events in \a buf are expected to be relative to
411 * the start of this model (t=0) and MUST be monotonically increasing
412 * and MUST be >= the latest event currently in the model.
415 MidiModel::append(const MIDI::Event& ev)
419 assert(_notes.empty() || ev.time() >= _notes.back()->time());
423 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
424 else if (ev.is_note_off())
425 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
427 append_cc_unlocked(ev.channel(), ev.time(), ev.cc_number(), ev.cc_value());
429 printf("MM Unknown event type %X\n", ev.type());
436 MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity)
438 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
439 " note " << (int)note_num << " on @ " << time << endl;*/
444 _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
445 if (_note_mode == Sustained) {
446 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
447 _write_notes[chan].push_back(_notes.size() - 1);
449 cerr << "MM Percussive: NOT appending active note on" << endl;
455 MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num)
457 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
458 " note " << (int)note_num << " off @ " << time << endl;*/
463 if (_note_mode == Percussive) {
464 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
468 /* FIXME: make _write_notes fixed size (127 noted) for speed */
470 /* FIXME: note off velocity for that one guy out there who actually has
471 * keys that send it */
473 bool resolved = false;
475 for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].end(); ++n) {
476 Note& note = *_notes[*n].get();
477 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
478 if (note.note() == note_num) {
479 assert(time >= note.time());
480 note.set_duration(time - note.time());
481 _write_notes[chan].erase(n);
482 //cerr << "MM resolved note, duration: " << note.duration() << endl;
489 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
490 << ", note " << (int)note_num << " @ " << time << endl;
495 MidiModel::append_cc_unlocked(uint8_t chan, double time, uint8_t number, uint8_t value)
497 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
498 " CC " << (int)number << " = " << (int)value << " @ " << time << endl;*/
503 Parameter param(MidiCCAutomation, number, chan);
505 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
506 control->list()->fast_simple_add(time, (double)value);
511 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
513 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
514 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
515 _notes.insert(i, note);
520 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
522 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
523 Notes::iterator n = find(_notes.begin(), _notes.end(), note);
524 if (n != _notes.end())
528 /** Slow! for debugging only. */
531 MidiModel::is_sorted() const
534 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
535 if ((*n)->time() < t)
544 /** Start a new command.
546 * This has no side-effects on the model or Session, the returned command
547 * can be held on to for as long as the caller wishes, or discarded without
548 * formality, until apply_command is called and ownership is taken.
550 MidiModel::DeltaCommand*
551 MidiModel::new_delta_command(const string name)
553 DeltaCommand* cmd = new DeltaCommand(*this, name);
560 * Ownership of cmd is taken, it must not be deleted by the caller.
561 * The command will constitute one item on the undo stack.
564 MidiModel::apply_command(Command* cmd)
566 _session.begin_reversible_command(cmd->name());
569 _session.commit_reversible_command(cmd);
578 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
580 //cerr << "MEC: apply" << endl;
582 _removed_notes.remove(note);
583 _added_notes.push_back(note);
588 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
590 //cerr << "MEC: remove" << endl;
592 _added_notes.remove(note);
593 _removed_notes.push_back(note);
598 MidiModel::DeltaCommand::operator()()
600 // This could be made much faster by using a priority_queue for added and
601 // removed notes (or sort here), and doing a single iteration over _model
603 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
604 const bool reset_iter = (_model._read_iter.locked());
605 const double iter_time = _model._read_iter->time();
608 _model._read_iter = _model.end(); // drop read lock
610 assert( ! _model._read_iter.locked());
614 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
615 _model.add_note_unlocked(*i);
617 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
618 _model.remove_note_unlocked(*i);
620 _model.write_unlock();
623 _model._read_iter = const_iterator(_model, iter_time);
625 _model.ContentsChanged(); /* EMIT SIGNAL */
630 MidiModel::DeltaCommand::undo()
632 // This could be made much faster by using a priority_queue for added and
633 // removed notes (or sort here), and doing a single iteration over _model
635 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
636 const bool reset_iter = (_model._read_iter.locked());
637 const double iter_time = _model._read_iter->time();
640 _model._read_iter = _model.end(); // drop read lock
642 assert( ! _model._read_iter.locked());
646 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
647 _model.remove_note_unlocked(*i);
649 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
650 _model.add_note_unlocked(*i);
652 _model.write_unlock();
655 _model._read_iter = const_iterator(_model, iter_time);
657 _model.ContentsChanged(); /* EMIT SIGNAL */
662 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
664 //cerr << "Writing model to " << source->name() << endl;
666 /* This could be done using a temporary MidiRingBuffer and using
667 * MidiModel::read and MidiSource::write, but this is more efficient
668 * and doesn't require any buffer size assumptions (ie it's worth
669 * the code duplication).
671 * This is also different from read in that note off events are written
672 * regardless of the track mode. This is so the user can switch a
673 * recorded track (with note durations from some instrument) to percussive,
674 * save, reload, then switch it back to sustained preserving the original
679 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
680 const MIDI::Event& ev = n->on_event();
681 source->append_event_unlocked(ev);
686 LaterNoteEndComparator cmp;
687 ActiveNotes active_notes(cmp);
690 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
692 // Write any pending note offs earlier than this note on
693 while ( ! active_notes.empty() ) {
694 const boost::shared_ptr<const Note> earliest_off = active_notes.top();
695 const MIDI::Event& off_ev = earliest_off->off_event();
696 if (off_ev.time() <= (*n)->time()) {
697 source->append_event_unlocked(Frames, off_ev);
704 // Write this note on
705 source->append_event_unlocked(Frames, (*n)->on_event());
706 if ((*n)->duration() > 0)
707 active_notes.push(*n);
710 // Write any trailing note offs
711 while ( ! active_notes.empty() ) {
712 source->append_event_unlocked(Frames, active_notes.top()->off_event());
724 MidiModel::get_state()
726 XMLNode *node = new XMLNode("MidiModel");