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(MidiSource *s, size_t size)
276 : Automatable(s->session(), "midi model")
278 , _note_mode(Sustained)
281 , _end_iter(*this, DBL_MAX)
282 , _next_read(UINT32_MAX)
283 , _read_iter(*this, DBL_MAX)
286 assert(_end_iter._is_end);
287 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 for(Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
531 /** Slow! for debugging only. */
534 MidiModel::is_sorted() const
537 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
538 if ((*n)->time() < t)
547 /** Start a new command.
549 * This has no side-effects on the model or Session, the returned command
550 * can be held on to for as long as the caller wishes, or discarded without
551 * formality, until apply_command is called and ownership is taken.
553 MidiModel::DeltaCommand*
554 MidiModel::new_delta_command(const string name)
556 DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
563 * Ownership of cmd is taken, it must not be deleted by the caller.
564 * The command will constitute one item on the undo stack.
567 MidiModel::apply_command(Command* cmd)
569 _session.begin_reversible_command(cmd->name());
572 _session.commit_reversible_command(cmd);
579 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
580 : Command(name), _model(m), _name(name)
585 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
592 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
594 //cerr << "MEC: apply" << endl;
596 _removed_notes.remove(note);
597 _added_notes.push_back(note);
602 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
604 //cerr << "MEC: remove" << endl;
606 _added_notes.remove(note);
607 _removed_notes.push_back(note);
612 MidiModel::DeltaCommand::operator()()
614 // This could be made much faster by using a priority_queue for added and
615 // removed notes (or sort here), and doing a single iteration over _model
617 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
618 const bool reset_iter = (_model->_read_iter.locked());
619 const double iter_time = _model->_read_iter->time();
622 _model->_read_iter = _model->end(); // drop read lock
624 assert( ! _model->_read_iter.locked());
626 _model->write_lock();
628 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
629 _model->add_note_unlocked(*i);
631 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
632 _model->remove_note_unlocked(*i);
634 _model->write_unlock();
637 _model->_read_iter = const_iterator(*_model.get(), iter_time);
639 _model->ContentsChanged(); /* EMIT SIGNAL */
644 MidiModel::DeltaCommand::undo()
646 // This could be made much faster by using a priority_queue for added and
647 // removed notes (or sort here), and doing a single iteration over _model
649 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
650 const bool reset_iter = (_model->_read_iter.locked());
651 const double iter_time = _model->_read_iter->time();
654 _model->_read_iter = _model->end(); // drop read lock
656 assert( ! _model->_read_iter.locked());
658 _model->write_lock();
660 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
661 _model->remove_note_unlocked(*i);
663 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
664 _model->add_note_unlocked(*i);
666 _model->write_unlock();
669 _model->_read_iter = const_iterator(*_model.get(), iter_time);
671 _model->ContentsChanged(); /* EMIT SIGNAL */
675 MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Note> note)
677 XMLNode *xml_note = new XMLNode("note");
678 ostringstream note_str(ios::ate);
679 note_str << int(note->note());
680 xml_note->add_property("note", note_str.str());
682 ostringstream channel_str(ios::ate);
683 channel_str << int(note->channel());
684 xml_note->add_property("channel", channel_str.str());
686 ostringstream time_str(ios::ate);
687 time_str << int(note->time());
688 xml_note->add_property("time", time_str.str());
690 ostringstream duration_str(ios::ate);
691 duration_str <<(unsigned int) note->duration();
692 xml_note->add_property("duration", duration_str.str());
694 ostringstream velocity_str(ios::ate);
695 velocity_str << (unsigned int) note->velocity();
696 xml_note->add_property("velocity", velocity_str.str());
701 boost::shared_ptr<Note>
702 MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
705 istringstream note_str(xml_note->property("note")->value());
708 unsigned int channel;
709 istringstream channel_str(xml_note->property("channel")->value());
710 channel_str >> channel;
713 istringstream time_str(xml_note->property("time")->value());
716 unsigned int duration;
717 istringstream duration_str(xml_note->property("duration")->value());
718 duration_str >> duration;
720 unsigned int velocity;
721 istringstream velocity_str(xml_note->property("velocity")->value());
722 velocity_str >> velocity;
724 boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
728 #define ADDED_NOTES_ELEMENT "added_notes"
729 #define REMOVED_NOTES_ELEMENT "removed_notes"
730 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
733 MidiModel::DeltaCommand::set_state (const XMLNode& delta_command)
735 if(delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
739 _added_notes.clear();
740 XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
741 XMLNodeList notes = added_notes->children();
742 transform(notes.begin(), notes.end(), back_inserter(_added_notes),
743 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
745 _removed_notes.clear();
746 XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
747 notes = removed_notes->children();
748 transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
749 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
755 MidiModel::DeltaCommand::get_state ()
757 XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
758 delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
760 XMLNode *added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
761 for_each(_added_notes.begin(), _added_notes.end(),
762 sigc::compose(sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
763 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
765 XMLNode *removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
766 for_each(_removed_notes.begin(), _removed_notes.end(),
767 sigc::compose(sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
768 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
770 return *delta_command;
775 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
777 //cerr << "Writing model to " << source->name() << endl;
779 /* This could be done using a temporary MidiRingBuffer and using
780 * MidiModel::read and MidiSource::write, but this is more efficient
781 * and doesn't require any buffer size assumptions (ie it's worth
782 * the code duplication).
784 * This is also different from read in that note off events are written
785 * regardless of the track mode. This is so the user can switch a
786 * recorded track (with note durations from some instrument) to percussive,
787 * save, reload, then switch it back to sustained preserving the original
792 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
793 const MIDI::Event& ev = n->on_event();
794 source->append_event_unlocked(ev);
799 LaterNoteEndComparator cmp;
800 ActiveNotes active_notes(cmp);
803 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
805 // Write any pending note offs earlier than this note on
806 while ( ! active_notes.empty() ) {
807 const boost::shared_ptr<const Note> earliest_off = active_notes.top();
808 const MIDI::Event& off_ev = earliest_off->off_event();
809 if (off_ev.time() <= (*n)->time()) {
810 source->append_event_unlocked(Frames, off_ev);
817 // Write this note on
818 source->append_event_unlocked(Frames, (*n)->on_event());
819 if ((*n)->duration() > 0)
820 active_notes.push(*n);
823 // Write any trailing note offs
824 while ( ! active_notes.empty() ) {
825 source->append_event_unlocked(Frames, active_notes.top()->off_event());
837 MidiModel::get_state()
839 XMLNode *node = new XMLNode("MidiModel");