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(boost::shared_ptr<AutomationList>(), DBL_MAX, 0.0);
92 _control_iters.reserve(model.controls().size());
93 for (Automatable::Controls::const_iterator i = model.controls().begin();
94 i != model.controls().end(); ++i) {
97 i->first.type() == MidiCCAutomation ||
98 i->first.type() == MidiPgmChangeAutomation ||
99 i->first.type() == MidiPitchBenderAutomation ||
100 i->first.type() == MidiChannelAftertouchAutomation
104 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
106 //cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
107 // << ") has no events past " << t << endl;
113 assert(y <= UINT8_MAX);
115 const MidiControlIterator new_iter(i->second->list(), x, y);
117 //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
118 _control_iters.push_back(new_iter);
120 if (x < earliest_control.x) {
121 earliest_control = new_iter;
122 _control_iter = _control_iters.end();
127 if (_note_iter != model.notes().end()) {
128 _event = MIDI::Event((*_note_iter)->on_event(), false);
129 _active_notes.push(*_note_iter);
130 //cerr << " new const iterator: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl;
134 if (earliest_control.automation_list && earliest_control.x < _event.time())
135 model.control_to_midi_event(_event, earliest_control);
137 _control_iter = _control_iters.end();
139 if (_event.size() == 0) {
140 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
143 // FIXME: possible race condition here....
145 _model->read_unlock();
149 printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
154 MidiModel::const_iterator::~const_iterator()
157 _model->read_unlock();
161 const MidiModel::const_iterator&
162 MidiModel::const_iterator::operator++()
165 throw std::logic_error("Attempt to iterate past end of MidiModel");
167 /*cerr << "const_iterator::operator++: _event type:" << hex << "0x" << int(_event.type())
168 << " buffer: 0x" << int(_event.buffer()[0]) << " 0x" << int(_event.buffer()[1])
169 << " 0x" << int(_event.buffer()[2]) << endl;*/
171 if(! (_event.is_note() || _event.is_cc() || _event.is_pgm_change() || _event.is_pitch_bender() || _event.is_channel_aftertouch()) ) {
172 cerr << "FAILED event buffer: " << hex << int(_event.buffer()[0]) << int(_event.buffer()[1]) << int(_event.buffer()[2]) << endl;
174 assert((_event.is_note() || _event.is_cc() || _event.is_pgm_change() || _event.is_pitch_bender() || _event.is_channel_aftertouch()));
176 // TODO: This code crashes at the marked section
177 // Increment past current control event
178 if (_control_iter != _control_iters.end() && _control_iter->automation_list && _event.is_cc()) {
180 cerr << "control_iter x:" << _control_iter->x << " y:" << _control_iter->y << endl;
181 // v--- this crashes because of a null pointer in the stl containers linked list chain
182 // the crash occurs in _control_iter->automation_list->size();
183 const bool ret = _control_iter->automation_list->rt_safe_earliest_event_unlocked(
184 _control_iter->x, DBL_MAX, x, y, false);
187 //cerr << "Incremented " << _control_iter->automation_list->parameter().id() << " to " << x << endl;
188 _control_iter->x = x;
189 _control_iter->y = y;
191 //cerr << "Hit end of " << _control_iter->automation_list->parameter().id() << endl;
192 _control_iter->automation_list.reset();
193 _control_iter->x = DBL_MAX;
197 // Now find and point at the earliest event
200 const std::vector<MidiControlIterator>::iterator old_control_iter = _control_iter;
201 _control_iter = _control_iters.begin();
203 for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
204 i != _control_iters.end(); ++i) {
205 if (i->x < _control_iter->x && i != old_control_iter) {
210 enum Type { NIL, NOTE_ON, NOTE_OFF, AUTOMATION };
215 // Next earliest note on
216 if (_note_iter != _model->notes().end()) {
218 t = (*_note_iter)->time();
221 // Use the next earliest note off iff it's earlier than the note on
222 if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
223 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
225 t = _active_notes.top()->end_time();
229 // Use the next earliest controller iff it's earlier than the note event
230 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX)
231 if (type == NIL || _control_iter->x < t)
234 if (type == NOTE_ON) {
235 cerr << "********** MIDI Iterator = note on" << endl;
236 _event = MIDI::Event((*_note_iter)->on_event(), false);
237 _active_notes.push(*_note_iter);
239 } else if (type == NOTE_OFF) {
240 cerr << "********** MIDI Iterator = note off" << endl;
241 _event = MIDI::Event(_active_notes.top()->off_event(), false);
243 } else if (type == AUTOMATION) {
244 cerr << "********** MIDI Iterator = AUTOMATION" << endl;
245 _model->control_to_midi_event(_event, *_control_iter);
247 cerr << "********** MIDI Iterator = END" << endl;
251 assert(_is_end || _event.size() > 0);
258 MidiModel::const_iterator::operator==(const const_iterator& other) const
260 if (_is_end || other._is_end)
261 return (_is_end == other._is_end);
263 return (_event == other._event);
267 MidiModel::const_iterator&
268 MidiModel::const_iterator::operator=(const const_iterator& other)
270 if (_locked && _model != other._model)
271 _model->read_unlock();
273 assert( ! other._event.owns_buffer());
275 _model = other._model;
276 _event = other._event;
277 _active_notes = other._active_notes;
278 _is_end = other._is_end;
279 _locked = other._locked;
280 _note_iter = other._note_iter;
281 _control_iters = other._control_iters;
282 _control_iter = other._control_iter;
284 assert( ! _event.owns_buffer());
292 MidiModel::MidiModel(MidiSource *s, size_t size)
293 : Automatable(s->session(), "midi model")
295 , _note_mode(Sustained)
298 , _end_iter(*this, DBL_MAX)
299 , _next_read(UINT32_MAX)
300 , _read_iter(*this, DBL_MAX)
303 assert(_end_iter._is_end);
304 assert( ! _end_iter._locked);
307 /** Read events in frame range \a start .. \a start+cnt into \a dst,
308 * adding \a stamp_offset to each event's timestamp.
309 * \return number of events written to \a dst
312 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
314 //cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
315 //cerr << this << " MM # notes: " << n_notes() << endl;
317 size_t read_events = 0;
319 if (start != _next_read) {
320 _read_iter = const_iterator(*this, (double)start);
321 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
323 //cerr << "Using cached iterator at " << _next_read << endl;
326 _next_read = start + nframes;
328 while (_read_iter != end() && _read_iter->time() < start + nframes) {
329 assert(_read_iter->size() > 0);
330 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset, _read_iter->size(), _read_iter->buffer());
333 cerr << this << " MidiModel::read event @ " << _read_iter->time()
334 << " type: " << hex << int(_read_iter->type()) << dec
335 << " note: " << int(_read_iter->note())
336 << " velocity: " << int(_read_iter->velocity())
349 MidiModel::control_to_midi_event(MIDI::Event& ev, const MidiControlIterator& iter) const
351 switch(iter.automation_list->parameter().type()) {
352 case MidiCCAutomation:
354 ev.set_buffer((Byte*)malloc(3), true);
356 assert(iter.automation_list);
357 assert(iter.automation_list->parameter().channel() < 16);
358 assert(iter.automation_list->parameter().id() <= INT8_MAX);
359 assert(iter.y <= INT8_MAX);
360 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.automation_list->parameter().channel();
361 ev.buffer()[1] = (Byte)iter.automation_list->parameter().id();
362 ev.buffer()[2] = (Byte)iter.y;
367 case MidiPgmChangeAutomation:
369 ev.set_buffer((Byte*)malloc(3), true);
371 assert(iter.automation_list);
372 assert(iter.automation_list->parameter().channel() < 16);
373 assert(iter.automation_list->parameter().id() <= INT8_MAX);
374 assert(iter.y <= INT8_MAX);
375 ev.buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.automation_list->parameter().channel();
376 ev.buffer()[1] = (Byte)iter.y;
382 case MidiPitchBenderAutomation:
384 ev.set_buffer((Byte*)malloc(3), true);
386 assert(iter.automation_list);
387 assert(iter.automation_list->parameter().channel() < 16);
388 assert(iter.automation_list->parameter().id() <= INT8_MAX);
389 assert(iter.y <= INT8_MAX);
390 ev.buffer()[0] = MIDI_CMD_BENDER + iter.automation_list->parameter().channel();
391 ev.buffer()[1] = ((Byte)iter.y) & 0x7F; // LSB
392 ev.buffer()[2] = (((Byte)iter.y) >> 7) & 0x7F; // MSB
397 case MidiChannelAftertouchAutomation:
399 ev.set_buffer((Byte*)malloc(3), true);
401 assert(iter.automation_list);
402 assert(iter.automation_list->parameter().channel() < 16);
403 assert(iter.automation_list->parameter().id() <= INT8_MAX);
404 assert(iter.y <= INT8_MAX);
405 ev.buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.automation_list->parameter().channel();
406 ev.buffer()[1] = (Byte)iter.y;
418 /** Begin a write of events to the model.
420 * If \a mode is Sustained, complete notes with duration are constructed as note
421 * on/off events are received. Otherwise (Percussive), only note on events are
422 * stored; note off events are discarded entirely and all contained notes will
426 MidiModel::start_write()
428 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
431 for (int i = 0; i < 16; ++i)
432 _write_notes[i].clear();
438 /** Finish a write of events to the model.
440 * If \a delete_stuck is true and the current mode is Sustained, note on events
441 * that were never resolved with a corresonding note off will be deleted.
442 * Otherwise they will remain as notes with duration 0.
445 MidiModel::end_write(bool delete_stuck)
450 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
452 if (_note_mode == Sustained && delete_stuck) {
453 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
454 if ((*n)->duration() == 0) {
455 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
457 // we have to break here because erase invalidates the iterator
465 for (int i = 0; i < 16; ++i) {
466 if (!_write_notes[i].empty()) {
467 cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
468 << _write_notes[i].size() << " stuck notes" << endl;
470 _write_notes[i].clear();
478 /** Append \a in_event to model. NOT realtime safe.
480 * Timestamps of events in \a buf are expected to be relative to
481 * the start of this model (t=0) and MUST be monotonically increasing
482 * and MUST be >= the latest event currently in the model.
485 MidiModel::append(const MIDI::Event& ev)
490 cerr << "MidiModel::append event type: " << hex << "0x" << int(ev.type()) << endl;
492 assert(_notes.empty() || ev.time() >= _notes.back()->time());
495 if (ev.is_note_on()) {
496 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
497 } else if (ev.is_note_off()) {
498 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
499 } else if (ev.is_cc()) {
500 append_automation_event_unlocked(MidiCCAutomation, ev.channel(), ev.time(), ev.cc_number(), ev.cc_value());
501 } else if (ev.is_pgm_change()) {
502 append_automation_event_unlocked(MidiPgmChangeAutomation, ev.channel(), ev.time(), ev.pgm_number(), 0);
503 } else if (ev.is_pitch_bender()) {
504 append_automation_event_unlocked(MidiPitchBenderAutomation, ev.channel(), ev.time(), ev.pitch_bender_lsb(), ev.pitch_bender_msb());
505 } else if (ev.is_channel_aftertouch()) {
506 append_automation_event_unlocked(MidiChannelAftertouchAutomation, ev.channel(), ev.time(), ev.channel_aftertouch(), 0);
508 printf("MM Unknown event type %X\n", ev.type());
516 MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity)
518 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
519 " note " << (int)note_num << " on @ " << time << endl;*/
525 _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
526 if (_note_mode == Sustained) {
527 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
528 _write_notes[chan].push_back(_notes.size() - 1);
530 cerr << "MM Percussive: NOT appending active note on" << endl;
536 MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num)
538 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
539 " note " << (int)note_num << " off @ " << time << endl;*/
545 if (_note_mode == Percussive) {
546 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
550 /* FIXME: make _write_notes fixed size (127 noted) for speed */
552 /* FIXME: note off velocity for that one guy out there who actually has
553 * keys that send it */
555 bool resolved = false;
557 for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].end(); ++n) {
558 Note& note = *_notes[*n].get();
559 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
560 if (note.note() == note_num) {
561 assert(time >= note.time());
562 note.set_duration(time - note.time());
563 _write_notes[chan].erase(n);
564 //cerr << "MM resolved note, duration: " << note.duration() << endl;
571 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
572 << ", note " << (int)note_num << " @ " << time << endl;
577 MidiModel::append_automation_event_unlocked(AutomationType type, uint8_t chan, double time, uint8_t first_byte, uint8_t second_byte)
579 //cerr << "MidiModel " << this << " chan " << (int)chan <<
580 // " CC " << (int)number << " = " << (int)value << " @ " << time << endl;
590 case MidiCCAutomation:
592 value = double(second_byte);
594 case MidiChannelAftertouchAutomation:
595 case MidiPgmChangeAutomation:
597 value = double(first_byte);
599 case MidiPitchBenderAutomation:
601 value = double((0x7F & second_byte) << 7 | (0x7F & first_byte));
607 Parameter param(type, id, chan);
608 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
609 control->list()->fast_simple_add(time, value);
613 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
615 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
617 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
618 _notes.insert(i, note);
623 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
626 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
627 for(Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
629 const Note& _note = *note;
630 // TODO: There is still the issue, that after restarting ardour
631 // persisted undo does not work, because of rounding errors in the
632 // event times after saving/restoring to/from MIDI files
633 cerr << "======================================= " << endl;
634 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.duration()) << "-- #" << int(_n.velocity()) << endl;
635 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.duration()) << "-- #" << int(_note.velocity()) << endl;
636 cerr << "Equal: " << bool(_n == _note) << endl;
637 cerr << endl << endl;
640 // we have to break here, because erase invalidates all iterators, ie. n itself
646 /** Slow! for debugging only. */
649 MidiModel::is_sorted() const
652 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
653 if ((*n)->time() < t)
662 /** Start a new command.
664 * This has no side-effects on the model or Session, the returned command
665 * can be held on to for as long as the caller wishes, or discarded without
666 * formality, until apply_command is called and ownership is taken.
668 MidiModel::DeltaCommand*
669 MidiModel::new_delta_command(const string name)
671 DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
678 * Ownership of cmd is taken, it must not be deleted by the caller.
679 * The command will constitute one item on the undo stack.
682 MidiModel::apply_command(Command* cmd)
684 _session.begin_reversible_command(cmd->name());
687 _session.commit_reversible_command(cmd);
694 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
695 : Command(name), _model(m), _name(name)
700 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
707 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
709 //cerr << "MEC: apply" << endl;
711 _removed_notes.remove(note);
712 _added_notes.push_back(note);
717 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
719 //cerr << "MEC: remove" << endl;
721 _added_notes.remove(note);
722 _removed_notes.push_back(note);
727 MidiModel::DeltaCommand::operator()()
729 // This could be made much faster by using a priority_queue for added and
730 // removed notes (or sort here), and doing a single iteration over _model
732 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
733 const bool reset_iter = (_model->_read_iter.locked());
734 const double iter_time = _model->_read_iter->time();
737 _model->_read_iter = _model->end(); // drop read lock
739 assert( ! _model->_read_iter.locked());
741 _model->write_lock();
743 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
744 _model->add_note_unlocked(*i);
746 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
747 _model->remove_note_unlocked(*i);
749 _model->write_unlock();
752 _model->_read_iter = const_iterator(*_model.get(), iter_time);
754 _model->ContentsChanged(); /* EMIT SIGNAL */
759 MidiModel::DeltaCommand::undo()
761 // This could be made much faster by using a priority_queue for added and
762 // removed notes (or sort here), and doing a single iteration over _model
764 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
765 const bool reset_iter = (_model->_read_iter.locked());
766 const double iter_time = _model->_read_iter->time();
769 _model->_read_iter = _model->end(); // drop read lock
771 assert( ! _model->_read_iter.locked());
773 _model->write_lock();
775 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
776 _model->remove_note_unlocked(*i);
778 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
779 _model->add_note_unlocked(*i);
781 _model->write_unlock();
784 _model->_read_iter = const_iterator(*_model.get(), iter_time);
786 _model->ContentsChanged(); /* EMIT SIGNAL */
790 MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Note> note)
792 XMLNode *xml_note = new XMLNode("note");
793 ostringstream note_str(ios::ate);
794 note_str << int(note->note());
795 xml_note->add_property("note", note_str.str());
797 ostringstream channel_str(ios::ate);
798 channel_str << int(note->channel());
799 xml_note->add_property("channel", channel_str.str());
801 ostringstream time_str(ios::ate);
802 time_str << int(note->time());
803 xml_note->add_property("time", time_str.str());
805 ostringstream duration_str(ios::ate);
806 duration_str <<(unsigned int) note->duration();
807 xml_note->add_property("duration", duration_str.str());
809 ostringstream velocity_str(ios::ate);
810 velocity_str << (unsigned int) note->velocity();
811 xml_note->add_property("velocity", velocity_str.str());
816 boost::shared_ptr<Note>
817 MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
820 istringstream note_str(xml_note->property("note")->value());
823 unsigned int channel;
824 istringstream channel_str(xml_note->property("channel")->value());
825 channel_str >> channel;
828 istringstream time_str(xml_note->property("time")->value());
831 unsigned int duration;
832 istringstream duration_str(xml_note->property("duration")->value());
833 duration_str >> duration;
835 unsigned int velocity;
836 istringstream velocity_str(xml_note->property("velocity")->value());
837 velocity_str >> velocity;
839 boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
843 #define ADDED_NOTES_ELEMENT "added_notes"
844 #define REMOVED_NOTES_ELEMENT "removed_notes"
845 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
848 MidiModel::DeltaCommand::set_state (const XMLNode& delta_command)
850 if(delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
854 _added_notes.clear();
855 XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
856 XMLNodeList notes = added_notes->children();
857 transform(notes.begin(), notes.end(), back_inserter(_added_notes),
858 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
860 _removed_notes.clear();
861 XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
862 notes = removed_notes->children();
863 transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
864 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
870 MidiModel::DeltaCommand::get_state ()
872 XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
873 delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
875 XMLNode *added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
876 for_each(_added_notes.begin(), _added_notes.end(),
877 sigc::compose(sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
878 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
880 XMLNode *removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
881 for_each(_removed_notes.begin(), _removed_notes.end(),
882 sigc::compose(sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
883 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
885 return *delta_command;
889 struct EventTimeComparator {
890 typedef const MIDI::Event* value_type;
891 inline bool operator()(const MIDI::Event* a,
892 const MIDI::Event* b) const {
893 return a->time() >= b->time();
898 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
900 cerr << "Writing model to " << source->name() << endl;
902 /* This could be done using a temporary MidiRingBuffer and using
903 * MidiModel::read and MidiSource::write, but this is more efficient
904 * and doesn't require any buffer size assumptions (ie it's worth
905 * the code duplication).
907 * This is also different from read in that note off events are written
908 * regardless of the track mode. This is so the user can switch a
909 * recorded track (with note durations from some instrument) to percussive,
910 * save, reload, then switch it back to sustained preserving the original
916 LaterNoteEndComparator cmp;
917 ActiveNotes active_notes(cmp);
919 EventTimeComparator comp;
920 typedef std::priority_queue<
922 std::deque<const MIDI::Event*>,
923 EventTimeComparator> MidiEvents;
925 MidiEvents events(comp);
927 /* Why sort manyally, when a priority queue does the job for us,
928 * (I am probably wrong here, but I needed that to test program
929 * change code quickly) ???
932 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
934 // Write any pending note offs earlier than this note on
935 while ( ! active_notes.empty() ) {
936 const boost::shared_ptr<const Note> earliest_off = active_notes.top();
937 const MIDI::Event& off_ev = earliest_off->off_event();
938 if (off_ev.time() <= (*n)->time()) {
939 events.push(&off_ev);
946 // Write this note on
947 events.push(&(*n)->on_event());
948 if ((*n)->duration() > 0)
949 active_notes.push(*n);
952 // Write any trailing note offs
953 while ( ! active_notes.empty() ) {
954 events.push(&active_notes.top()->off_event());
958 while(!events.empty()) {
959 source->append_event_unlocked(Frames, *events.top());
960 cerr << "MidiModel::write_to appending event with time:" << dec << int(events.top()->time()) << hex
961 << " buffer: 0x" << int(events.top()->buffer()[0]) << " 0x" << int(events.top()->buffer()[1])
962 << " 0x" << int(events.top()->buffer()[2]) << endl;
974 MidiModel::get_state()
976 XMLNode *node = new XMLNode("MidiModel");
981 MidiModel::midi_source() const
987 MidiModel::set_midi_source(MidiSource *source)
989 _midi_source = source;