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;
38 void MidiModel::write_lock() {
40 _automation_lock.lock();
43 void MidiModel::write_unlock() {
44 _lock.writer_unlock();
45 _automation_lock.unlock();
48 void MidiModel::read_lock() const {
50 /*_automation_lock.lock();*/
53 void MidiModel::read_unlock() const {
54 _lock.reader_unlock();
55 /*_automation_lock.unlock();*/
58 // Read iterator (const_iterator)
60 MidiModel::const_iterator::const_iterator(const MidiModel& model, double t) :
61 _model(&model), _is_end( (t == DBL_MAX) || model.empty()),
63 //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl;
70 _note_iter = model.notes().end();
71 // find first note which begins after t
72 for (MidiModel::Notes::const_iterator i = model.notes().begin(); i != model.notes().end(); ++i) {
73 if ((*i)->time() >= t) {
79 MidiControlIterator earliest_control(boost::shared_ptr<AutomationList>(), DBL_MAX, 0.0);
81 _control_iters.reserve(model.controls().size());
82 for (Automatable::Controls::const_iterator i = model.controls().begin();
83 i != model.controls().end(); ++i) {
86 i->first.type() == MidiCCAutomation ||
87 i->first.type() == MidiPgmChangeAutomation ||
88 i->first.type() == MidiPitchBenderAutomation ||
89 i->first.type() == MidiChannelAftertouchAutomation
93 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
95 //cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
96 // << ") has no events past " << t << endl;
101 assert(y >= i->first.min());
102 assert(y <= i->first.max());
104 const MidiControlIterator new_iter(i->second->list(), x, y);
106 //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
107 _control_iters.push_back(new_iter);
109 if (x < earliest_control.x) {
110 earliest_control = new_iter;
111 _control_iter = _control_iters.end();
116 if (_note_iter != model.notes().end()) {
117 _event = MIDI::Event((*_note_iter)->on_event(), false);
118 _active_notes.push(*_note_iter);
119 //cerr << " new const iterator: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl;
123 if (earliest_control.automation_list && earliest_control.x < _event.time())
124 model.control_to_midi_event(_event, earliest_control);
126 _control_iter = _control_iters.end();
128 if (_event.size() == 0) {
129 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
132 // FIXME: possible race condition here....
134 _model->read_unlock();
138 printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
142 MidiModel::const_iterator::~const_iterator() {
144 _model->read_unlock();
148 const MidiModel::const_iterator& MidiModel::const_iterator::operator++()
151 throw std::logic_error("Attempt to iterate past end of MidiModel");
153 /*cerr << "const_iterator::operator++: _event type:" << hex << "0x" << int(_event.type())
154 << " buffer: 0x" << int(_event.buffer()[0]) << " 0x" << int(_event.buffer()[1])
155 << " 0x" << int(_event.buffer()[2]) << endl;*/
157 if(! (_event.is_note() || _event.is_cc() || _event.is_pgm_change() || _event.is_pitch_bender() || _event.is_channel_aftertouch()) ) {
158 cerr << "FAILED event buffer: " << hex << int(_event.buffer()[0]) << int(_event.buffer()[1]) << int(_event.buffer()[2]) << endl;
160 assert((_event.is_note() || _event.is_cc() || _event.is_pgm_change() || _event.is_pitch_bender() || _event.is_channel_aftertouch()));
162 // TODO: This code crashes at the marked section
163 // Increment past current control event
164 if (_control_iter != _control_iters.end() && _control_iter->automation_list && _event.is_cc()) {
166 cerr << "control_iter x:" << _control_iter->x << " y:" << _control_iter->y << endl;
167 // v--- this crashes because of a null pointer in the stl containers linked list chain
168 // the crash occurs in _control_iter->automation_list->size();
169 const bool ret = _control_iter->automation_list->rt_safe_earliest_event_unlocked(
170 _control_iter->x, DBL_MAX, x, y, false);
173 //cerr << "Incremented " << _control_iter->automation_list->parameter().id() << " to " << x << endl;
174 _control_iter->x = x;
175 _control_iter->y = y;
177 //cerr << "Hit end of " << _control_iter->automation_list->parameter().id() << endl;
178 _control_iter->automation_list.reset();
179 _control_iter->x = DBL_MAX;
183 // Now find and point at the earliest event
186 const std::vector<MidiControlIterator>::iterator old_control_iter = _control_iter;
187 _control_iter = _control_iters.begin();
189 for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
190 i != _control_iters.end(); ++i) {
191 if (i->x < _control_iter->x) {
196 enum Type {NIL, NOTE_ON, NOTE_OFF, AUTOMATION};
201 // Next earliest note on
202 if (_note_iter != _model->notes().end()) {
204 t = (*_note_iter)->time();
207 // Use the next earliest note off iff it's earlier than the note on
208 if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
209 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
211 t = _active_notes.top()->end_time();
215 // Use the next earliest controller iff it's earlier than the note event
216 if (_control_iter != _control_iters.end()
217 && _control_iter->x != DBL_MAX
218 && _control_iter != old_control_iter)
219 if (type == NIL || _control_iter->x < t)
222 if (type == NOTE_ON) {
223 cerr << "********** MIDI Iterator = note on" << endl;
224 _event = MIDI::Event((*_note_iter)->on_event(), false);
225 _active_notes.push(*_note_iter);
227 } else if (type == NOTE_OFF) {
228 cerr << "********** MIDI Iterator = note off" << endl;
229 _event = MIDI::Event(_active_notes.top()->off_event(), false);
231 } else if (type == AUTOMATION) {
232 cerr << "********** MIDI Iterator = AUTOMATION" << endl;
233 _model->control_to_midi_event(_event, *_control_iter);
235 cerr << "********** MIDI Iterator = END" << endl;
239 assert(_is_end || _event.size()> 0);
244 bool MidiModel::const_iterator::operator==(const const_iterator& other) const
246 if (_is_end || other._is_end)
247 return (_is_end == other._is_end);
249 return (_event == other._event);
252 MidiModel::const_iterator& MidiModel::const_iterator::operator=(const const_iterator& other)
254 if (_locked && _model != other._model)
255 _model->read_unlock();
257 assert( ! other._event.owns_buffer());
259 _model = other._model;
260 _event = other._event;
261 _active_notes = other._active_notes;
262 _is_end = other._is_end;
263 _locked = other._locked;
264 _note_iter = other._note_iter;
265 _control_iters = other._control_iters;
266 _control_iter = other._control_iter;
268 assert( ! _event.owns_buffer());
275 MidiModel::MidiModel(MidiSource *s, size_t size) :
276 Automatable(s->session(), "midi model"), _notes(size),
277 _note_mode(Sustained), _writing(false), _edited(false), _end_iter(
278 *this, DBL_MAX), _next_read(UINT32_MAX), _read_iter(*this,
279 DBL_MAX), _midi_source(s) {
280 assert(_end_iter._is_end);
281 assert( ! _end_iter._locked);
284 /** Read events in frame range \a start .. \a start+cnt into \a dst,
285 * adding \a stamp_offset to each event's timestamp.
286 * \return number of events written to \a dst
288 size_t MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes,
289 nframes_t stamp_offset, nframes_t negative_stamp_offset) const {
290 //cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
291 //cerr << this << " MM # notes: " << n_notes() << endl;
293 size_t read_events = 0;
295 if (start != _next_read) {
296 _read_iter = const_iterator(*this, (double)start);
297 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
299 //cerr << "Using cached iterator at " << _next_read << endl;
302 _next_read = start + nframes;
304 while (_read_iter != end() && _read_iter->time() < start + nframes) {
305 assert(_read_iter->size()> 0);
306 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset,
307 _read_iter->size(), _read_iter->buffer());
310 cerr << this << " MidiModel::read event @ " << _read_iter->time()
311 << " type: " << hex << int(_read_iter->type()) << dec
312 << " note: " << int(_read_iter->note())
313 << " velocity: " << int(_read_iter->velocity())
324 bool MidiModel::control_to_midi_event(MIDI::Event& ev,
325 const MidiControlIterator& iter) const {
326 switch (iter.automation_list->parameter().type()) {
327 case MidiCCAutomation:
329 ev.set_buffer((Byte*)malloc(3), true);
331 assert(iter.automation_list);
332 assert(iter.automation_list->parameter().channel() < 16);
333 assert(iter.automation_list->parameter().id() <= INT8_MAX);
334 assert(iter.y <= INT8_MAX);
335 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.automation_list->parameter().channel();
336 ev.buffer()[1] = (Byte)iter.automation_list->parameter().id();
337 ev.buffer()[2] = (Byte)iter.y;
342 case MidiPgmChangeAutomation:
344 ev.set_buffer((Byte*)malloc(3), true);
346 assert(iter.automation_list);
347 assert(iter.automation_list->parameter().channel() < 16);
348 assert(iter.automation_list->parameter().id() <= INT8_MAX);
349 assert(iter.y <= INT8_MAX);
350 ev.buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.automation_list->parameter().channel();
351 ev.buffer()[1] = (Byte)iter.y;
357 case MidiPitchBenderAutomation:
359 ev.set_buffer((Byte*)malloc(3), true);
361 assert(iter.automation_list);
362 assert(iter.automation_list->parameter().channel() < 16);
363 assert(iter.automation_list->parameter().id() <= INT8_MAX);
364 assert(iter.y < (1<<14));
365 ev.buffer()[0] = MIDI_CMD_BENDER + iter.automation_list->parameter().channel();
366 ev.buffer()[1] = ((Byte)iter.y) & 0x7F; // LSB
367 ev.buffer()[2] = (((Byte)iter.y) >> 7) & 0x7F; // MSB
372 case MidiChannelAftertouchAutomation:
374 ev.set_buffer((Byte*)malloc(3), true);
376 assert(iter.automation_list);
377 assert(iter.automation_list->parameter().channel() < 16);
378 assert(iter.automation_list->parameter().id() <= INT8_MAX);
379 assert(iter.y <= INT8_MAX);
381 = MIDI_CMD_CHANNEL_PRESSURE + iter.automation_list->parameter().channel();
382 ev.buffer()[1] = (Byte)iter.y;
393 /** Begin a write of events to the model.
395 * If \a mode is Sustained, complete notes with duration are constructed as note
396 * on/off events are received. Otherwise (Percussive), only note on events are
397 * stored; note off events are discarded entirely and all contained notes will
400 void MidiModel::start_write() {
401 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
404 for (int i = 0; i < 16; ++i)
405 _write_notes[i].clear();
407 _dirty_automations.clear();
411 /** Finish a write of events to the model.
413 * If \a delete_stuck is true and the current mode is Sustained, note on events
414 * that were never resolved with a corresonding note off will be deleted.
415 * Otherwise they will remain as notes with duration 0.
417 void MidiModel::end_write(bool delete_stuck) {
421 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
423 if (_note_mode == Sustained && delete_stuck) {
424 for (Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
425 if ((*n)->duration() == 0) {
426 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
428 // we have to break here because erase invalidates the iterator
436 for (int i = 0; i < 16; ++i) {
437 if (!_write_notes[i].empty()) {
438 cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
439 << _write_notes[i].size() << " stuck notes" << endl;
441 _write_notes[i].clear();
444 for(AutomationLists::const_iterator i = _dirty_automations.begin(); i != _dirty_automations.end(); ++i) {
446 (*i)->lookup_cache().left = -1;
447 (*i)->search_cache().left = -1;
454 /** Append \a in_event to model. NOT realtime safe.
456 * Timestamps of events in \a buf are expected to be relative to
457 * the start of this model (t=0) and MUST be monotonically increasing
458 * and MUST be >= the latest event currently in the model.
460 void MidiModel::append(const MIDI::Event& ev) {
464 cerr << "MidiModel::append event type: " << hex << "0x" << int(ev.type()) << endl;
466 assert(_notes.empty() || ev.time() >= _notes.back()->time());
469 if (ev.is_note_on()) {
470 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(),
472 } else if (ev.is_note_off()) {
473 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
474 } else if (ev.is_cc()) {
475 append_automation_event_unlocked(MidiCCAutomation, ev.channel(),
476 ev.time(), ev.cc_number(), ev.cc_value());
477 } else if (ev.is_pgm_change()) {
478 append_automation_event_unlocked(MidiPgmChangeAutomation, ev.channel(),
479 ev.time(), ev.pgm_number(), 0);
480 } else if (ev.is_pitch_bender()) {
481 append_automation_event_unlocked(MidiPitchBenderAutomation,
482 ev.channel(), ev.time(), ev.pitch_bender_lsb(),
483 ev.pitch_bender_msb());
484 } else if (ev.is_channel_aftertouch()) {
485 append_automation_event_unlocked(MidiChannelAftertouchAutomation,
486 ev.channel(), ev.time(), ev.channel_aftertouch(), 0);
488 printf("MM Unknown event type %X\n", ev.type());
494 void MidiModel::append_note_on_unlocked(uint8_t chan, double time,
495 uint8_t note_num, uint8_t velocity) {
496 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
497 " note " << (int)note_num << " on @ " << time << endl;*/
503 _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
504 if (_note_mode == Sustained) {
505 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
506 _write_notes[chan].push_back(_notes.size() - 1);
508 cerr << "MM Percussive: NOT appending active note on" << endl;
512 void MidiModel::append_note_off_unlocked(uint8_t chan, double time,
514 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
515 " note " << (int)note_num << " off @ " << time << endl;*/
521 if (_note_mode == Percussive) {
522 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
526 /* FIXME: make _write_notes fixed size (127 noted) for speed */
528 /* FIXME: note off velocity for that one guy out there who actually has
529 * keys that send it */
531 bool resolved = false;
533 for (WriteNotes::iterator n = _write_notes[chan].begin(); n
534 != _write_notes[chan].end(); ++n) {
535 Note& note = *_notes[*n].get();
536 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
537 if (note.note() == note_num) {
538 assert(time >= note.time());
539 note.set_duration(time - note.time());
540 _write_notes[chan].erase(n);
541 //cerr << "MM resolved note, duration: " << note.duration() << endl;
548 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
549 << ", note " << (int)note_num << " @ " << time << endl;
552 void MidiModel::append_automation_event_unlocked(AutomationType type,
553 uint8_t chan, double time, uint8_t first_byte, uint8_t second_byte) {
554 //cerr << "MidiModel " << this << " chan " << (int)chan <<
555 // " CC " << (int)number << " = " << (int)value << " @ " << time << endl;
565 case MidiCCAutomation:
567 value = double(second_byte);
569 case MidiChannelAftertouchAutomation:
570 case MidiPgmChangeAutomation:
572 value = double(first_byte);
574 case MidiPitchBenderAutomation:
576 value = double((0x7F & second_byte) << 7 | (0x7F & first_byte));
582 Parameter param(type, id, chan);
583 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
584 control->list()->fast_simple_add(time, value);
585 cerr << "control list size after fast simple add: " << control->list()->size() << endl;
588 void MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note) {
589 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
591 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
592 note_time_comparator);
593 _notes.insert(i, note);
596 void MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note) {
598 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
599 for (Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
601 const Note& _note = *note;
602 // TODO: There is still the issue, that after restarting ardour
603 // persisted undo does not work, because of rounding errors in the
604 // event times after saving/restoring to/from MIDI files
605 cerr << "======================================= " << endl;
606 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.duration()) << "-- #" << int(_n.velocity()) << endl;
607 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.duration()) << "-- #" << int(_note.velocity()) << endl;
608 cerr << "Equal: " << bool(_n == _note) << endl;
609 cerr << endl << endl;
612 // we have to break here, because erase invalidates all iterators, ie. n itself
618 /** Slow! for debugging only. */
620 bool MidiModel::is_sorted() const {
622 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
623 if ((*n)->time() < t)
632 /** Start a new command.
634 * This has no side-effects on the model or Session, the returned command
635 * can be held on to for as long as the caller wishes, or discarded without
636 * formality, until apply_command is called and ownership is taken.
638 MidiModel::DeltaCommand* MidiModel::new_delta_command(const string name) {
639 DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
645 * Ownership of cmd is taken, it must not be deleted by the caller.
646 * The command will constitute one item on the undo stack.
648 void MidiModel::apply_command(Command* cmd) {
649 _session.begin_reversible_command(cmd->name());
652 _session.commit_reversible_command(cmd);
658 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
659 const std::string& name) :
660 Command(name), _model(m), _name(name) {
664 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
665 const XMLNode& node) :
670 void MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note) {
671 //cerr << "MEC: apply" << endl;
673 _removed_notes.remove(note);
674 _added_notes.push_back(note);
677 void MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note) {
678 //cerr << "MEC: remove" << endl;
680 _added_notes.remove(note);
681 _removed_notes.push_back(note);
684 void MidiModel::DeltaCommand::operator()()
686 // This could be made much faster by using a priority_queue for added and
687 // removed notes (or sort here), and doing a single iteration over _model
689 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
690 const bool reset_iter = (_model->_read_iter.locked());
691 const double iter_time = _model->_read_iter->time();
694 _model->_read_iter = _model->end(); // drop read lock
696 assert( ! _model->_read_iter.locked());
698 _model->write_lock();
700 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
701 _model->add_note_unlocked(*i);
703 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
704 _model->remove_note_unlocked(*i);
706 _model->write_unlock();
709 _model->_read_iter = const_iterator(*_model.get(), iter_time);
711 _model->ContentsChanged(); /* EMIT SIGNAL */
714 void MidiModel::DeltaCommand::undo() {
715 // This could be made much faster by using a priority_queue for added and
716 // removed notes (or sort here), and doing a single iteration over _model
718 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
719 const bool reset_iter = (_model->_read_iter.locked());
720 const double iter_time = _model->_read_iter->time();
723 _model->_read_iter = _model->end(); // drop read lock
725 assert( ! _model->_read_iter.locked());
727 _model->write_lock();
729 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i
730 != _added_notes.end(); ++i)
731 _model->remove_note_unlocked(*i);
733 for (std::list< boost::shared_ptr<Note> >::iterator i =
734 _removed_notes.begin(); i != _removed_notes.end(); ++i)
735 _model->add_note_unlocked(*i);
737 _model->write_unlock();
740 _model->_read_iter = const_iterator(*_model.get(), iter_time);
742 _model->ContentsChanged(); /* EMIT SIGNAL */
745 XMLNode & MidiModel::DeltaCommand::marshal_note(
746 const boost::shared_ptr<Note> note) {
747 XMLNode *xml_note = new XMLNode("note");
748 ostringstream note_str(ios::ate);
749 note_str << int(note->note());
750 xml_note->add_property("note", note_str.str());
752 ostringstream channel_str(ios::ate);
753 channel_str << int(note->channel());
754 xml_note->add_property("channel", channel_str.str());
756 ostringstream time_str(ios::ate);
757 time_str << int(note->time());
758 xml_note->add_property("time", time_str.str());
760 ostringstream duration_str(ios::ate);
761 duration_str <<(unsigned int) note->duration();
762 xml_note->add_property("duration", duration_str.str());
764 ostringstream velocity_str(ios::ate);
765 velocity_str << (unsigned int) note->velocity();
766 xml_note->add_property("velocity", velocity_str.str());
771 boost::shared_ptr<Note> MidiModel::DeltaCommand::unmarshal_note(
774 istringstream note_str(xml_note->property("note")->value());
777 unsigned int channel;
778 istringstream channel_str(xml_note->property("channel")->value());
779 channel_str >> channel;
782 istringstream time_str(xml_note->property("time")->value());
785 unsigned int duration;
786 istringstream duration_str(xml_note->property("duration")->value());
787 duration_str >> duration;
789 unsigned int velocity;
790 istringstream velocity_str(xml_note->property("velocity")->value());
791 velocity_str >> velocity;
793 boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
797 #define ADDED_NOTES_ELEMENT "added_notes"
798 #define REMOVED_NOTES_ELEMENT "removed_notes"
799 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
801 int MidiModel::DeltaCommand::set_state(const XMLNode& delta_command) {
802 if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
806 _added_notes.clear();
807 XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
808 XMLNodeList notes = added_notes->children();
809 transform(notes.begin(), notes.end(), back_inserter(_added_notes),
810 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
812 _removed_notes.clear();
813 XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
814 notes = removed_notes->children();
815 transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
816 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
821 XMLNode& MidiModel::DeltaCommand::get_state() {
822 XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
823 delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
825 XMLNode *added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
826 for_each(_added_notes.begin(), _added_notes.end(), sigc::compose(
827 sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
828 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
830 XMLNode *removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
831 for_each(_removed_notes.begin(), _removed_notes.end(), sigc::compose(
832 sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
833 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
835 return *delta_command;
838 struct EventTimeComparator {
839 typedef const MIDI::Event* value_type;
840 inline bool operator()(const MIDI::Event* a, const MIDI::Event* b) const {
841 return a->time() >= b->time();
845 bool MidiModel::write_to(boost::shared_ptr<MidiSource> source) {
846 cerr << "Writing model to " << source->name() << endl;
848 /* This could be done using a temporary MidiRingBuffer and using
849 * MidiModel::read and MidiSource::write, but this is more efficient
850 * and doesn't require any buffer size assumptions (ie it's worth
851 * the code duplication).
853 * This is also different from read in that note off events are written
854 * regardless of the track mode. This is so the user can switch a
855 * recorded track (with note durations from some instrument) to percussive,
856 * save, reload, then switch it back to sustained preserving the original
862 LaterNoteEndComparator cmp;
863 ActiveNotes active_notes(cmp);
865 EventTimeComparator comp;
866 typedef std::priority_queue<
868 std::deque<const MIDI::Event*>,
869 EventTimeComparator> MidiEvents;
871 MidiEvents events(comp);
873 /* Why sort manually, when a priority queue does the job for us,
874 * (I am probably wrong here, but I needed that to test program
875 * change code quickly) ???
878 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
880 // Write any pending note offs earlier than this note on
881 while ( !active_notes.empty() ) {
882 const boost::shared_ptr<const Note> earliest_off =
884 const MIDI::Event& off_ev = earliest_off->off_event();
885 if (off_ev.time() <= (*n)->time()) {
886 events.push(&off_ev);
893 // Write this note on
894 events.push(&(*n)->on_event());
895 if ((*n)->duration() > 0)
896 active_notes.push(*n);
899 // Write any trailing note offs
900 while ( !active_notes.empty() ) {
901 events.push(&active_notes.top()->off_event());
905 while (!events.empty()) {
906 source->append_event_unlocked(Frames, *events.top());
907 //cerr << "MidiModel::write_to appending event with time:" << dec << int(events.top()->time()) << hex << " buffer: 0x" << int(events.top()->buffer()[0]) << " 0x" << int(events.top()->buffer()[1]) << " 0x" << int(events.top()->buffer()[2]) << endl;
918 XMLNode& MidiModel::get_state() {
919 XMLNode *node = new XMLNode("MidiModel");
923 const MidiSource * MidiModel::midi_source() const {
927 void MidiModel::set_midi_source(MidiSource *source) {
928 _midi_source = source;