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->x = 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
199 _control_iter = _control_iters.begin();
201 for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
202 i != _control_iters.end(); ++i) {
203 if (i->x < _control_iter->x) {
208 enum Type { NIL, NOTE_ON, NOTE_OFF, AUTOMATION };
213 // Next earliest note on
214 if (_note_iter != _model->notes().end()) {
216 t = (*_note_iter)->time();
219 // Use the next earliest note off iff it's earlier than the note on
220 if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
221 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
223 t = _active_notes.top()->end_time();
227 // Use the next earliest controller iff it's earlier than the note event
228 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX)
229 if (type == NIL || _control_iter->x < t)
232 if (type == NOTE_ON) {
233 cerr << "********** MIDI Iterator = note on" << endl;
234 _event = MIDI::Event((*_note_iter)->on_event(), false);
235 _active_notes.push(*_note_iter);
237 } else if (type == NOTE_OFF) {
238 cerr << "********** MIDI Iterator = note off" << endl;
239 _event = MIDI::Event(_active_notes.top()->off_event(), false);
241 } else if (type == AUTOMATION) {
242 cerr << "********** MIDI Iterator = AUTOMATION" << endl;
243 _model->control_to_midi_event(_event, *_control_iter);
245 cerr << "********** MIDI Iterator = END" << endl;
249 assert(_is_end || _event.size() > 0);
256 MidiModel::const_iterator::operator==(const const_iterator& other) const
258 if (_is_end || other._is_end)
259 return (_is_end == other._is_end);
261 return (_event == other._event);
265 MidiModel::const_iterator&
266 MidiModel::const_iterator::operator=(const const_iterator& other)
268 if (_locked && _model != other._model)
269 _model->read_unlock();
271 assert( ! other._event.owns_buffer());
273 _model = other._model;
274 _event = other._event;
275 _active_notes = other._active_notes;
276 _is_end = other._is_end;
277 _locked = other._locked;
278 _note_iter = other._note_iter;
279 _control_iters = other._control_iters;
280 _control_iter = other._control_iter;
282 assert( ! _event.owns_buffer());
290 MidiModel::MidiModel(MidiSource *s, size_t size)
291 : Automatable(s->session(), "midi model")
293 , _note_mode(Sustained)
296 , _end_iter(*this, DBL_MAX)
297 , _next_read(UINT32_MAX)
298 , _read_iter(*this, DBL_MAX)
301 assert(_end_iter._is_end);
302 assert( ! _end_iter._locked);
305 /** Read events in frame range \a start .. \a start+cnt into \a dst,
306 * adding \a stamp_offset to each event's timestamp.
307 * \return number of events written to \a dst
310 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
312 //cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
313 //cerr << this << " MM # notes: " << n_notes() << endl;
315 size_t read_events = 0;
317 if (start != _next_read) {
318 _read_iter = const_iterator(*this, (double)start);
319 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
321 //cerr << "Using cached iterator at " << _next_read << endl;
324 _next_read = start + nframes;
326 while (_read_iter != end() && _read_iter->time() < start + nframes) {
327 assert(_read_iter->size() > 0);
328 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset, _read_iter->size(), _read_iter->buffer());
331 cerr << this << " MidiModel::read event @ " << _read_iter->time()
332 << " type: " << hex << int(_read_iter->type()) << dec
333 << " note: " << int(_read_iter->note())
334 << " velocity: " << int(_read_iter->velocity())
347 MidiModel::control_to_midi_event(MIDI::Event& ev, const MidiControlIterator& iter) const
349 switch(iter.automation_list->parameter().type()) {
350 case MidiCCAutomation:
352 ev.set_buffer((Byte*)malloc(3), true);
354 assert(iter.automation_list);
355 assert(iter.automation_list->parameter().channel() < 16);
356 assert(iter.automation_list->parameter().id() <= INT8_MAX);
357 assert(iter.y <= INT8_MAX);
358 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.automation_list->parameter().channel();
359 ev.buffer()[1] = (Byte)iter.automation_list->parameter().id();
360 ev.buffer()[2] = (Byte)iter.y;
365 case MidiPgmChangeAutomation:
367 ev.set_buffer((Byte*)malloc(3), true);
369 assert(iter.automation_list);
370 assert(iter.automation_list->parameter().channel() < 16);
371 assert(iter.automation_list->parameter().id() <= INT8_MAX);
372 assert(iter.y <= INT8_MAX);
373 ev.buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.automation_list->parameter().channel();
374 ev.buffer()[1] = (Byte)iter.y;
380 case MidiPitchBenderAutomation:
382 ev.set_buffer((Byte*)malloc(3), true);
384 assert(iter.automation_list);
385 assert(iter.automation_list->parameter().channel() < 16);
386 assert(iter.automation_list->parameter().id() <= INT8_MAX);
387 assert(iter.y <= INT8_MAX);
388 ev.buffer()[0] = MIDI_CMD_BENDER + iter.automation_list->parameter().channel();
389 ev.buffer()[1] = ((Byte)iter.y) & 0x7F; // LSB
390 ev.buffer()[2] = (((Byte)iter.y) >> 7) & 0x7F; // MSB
395 case MidiChannelAftertouchAutomation:
397 ev.set_buffer((Byte*)malloc(3), true);
399 assert(iter.automation_list);
400 assert(iter.automation_list->parameter().channel() < 16);
401 assert(iter.automation_list->parameter().id() <= INT8_MAX);
402 assert(iter.y <= INT8_MAX);
403 ev.buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.automation_list->parameter().channel();
404 ev.buffer()[1] = (Byte)iter.y;
416 /** Begin a write of events to the model.
418 * If \a mode is Sustained, complete notes with duration are constructed as note
419 * on/off events are received. Otherwise (Percussive), only note on events are
420 * stored; note off events are discarded entirely and all contained notes will
424 MidiModel::start_write()
426 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
429 for (int i = 0; i < 16; ++i)
430 _write_notes[i].clear();
436 /** Finish a write of events to the model.
438 * If \a delete_stuck is true and the current mode is Sustained, note on events
439 * that were never resolved with a corresonding note off will be deleted.
440 * Otherwise they will remain as notes with duration 0.
443 MidiModel::end_write(bool delete_stuck)
448 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
450 if (_note_mode == Sustained && delete_stuck) {
451 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
452 if ((*n)->duration() == 0) {
453 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
455 // we have to break here because erase invalidates the iterator
463 for (int i = 0; i < 16; ++i) {
464 if (!_write_notes[i].empty()) {
465 cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
466 << _write_notes[i].size() << " stuck notes" << endl;
468 _write_notes[i].clear();
476 /** Append \a in_event to model. NOT realtime safe.
478 * Timestamps of events in \a buf are expected to be relative to
479 * the start of this model (t=0) and MUST be monotonically increasing
480 * and MUST be >= the latest event currently in the model.
483 MidiModel::append(const MIDI::Event& ev)
488 cerr << "MidiModel::append event type: " << hex << "0x" << int(ev.type()) << endl;
490 assert(_notes.empty() || ev.time() >= _notes.back()->time());
493 if (ev.is_note_on()) {
494 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
495 } else if (ev.is_note_off()) {
496 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
497 } else if (ev.is_cc()) {
498 append_automation_event_unlocked(MidiCCAutomation, ev.channel(), ev.time(), ev.cc_number(), ev.cc_value());
499 } else if (ev.is_pgm_change()) {
500 append_automation_event_unlocked(MidiPgmChangeAutomation, ev.channel(), ev.time(), ev.pgm_number(), 0);
501 } else if (ev.is_pitch_bender()) {
502 append_automation_event_unlocked(MidiPitchBenderAutomation, ev.channel(), ev.time(), ev.pitch_bender_lsb(), ev.pitch_bender_msb());
503 } else if (ev.is_channel_aftertouch()) {
504 append_automation_event_unlocked(MidiChannelAftertouchAutomation, ev.channel(), ev.time(), ev.channel_aftertouch(), 0);
506 printf("MM Unknown event type %X\n", ev.type());
514 MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity)
516 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
517 " note " << (int)note_num << " on @ " << time << endl;*/
523 _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
524 if (_note_mode == Sustained) {
525 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
526 _write_notes[chan].push_back(_notes.size() - 1);
528 cerr << "MM Percussive: NOT appending active note on" << endl;
534 MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num)
536 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
537 " note " << (int)note_num << " off @ " << time << endl;*/
543 if (_note_mode == Percussive) {
544 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
548 /* FIXME: make _write_notes fixed size (127 noted) for speed */
550 /* FIXME: note off velocity for that one guy out there who actually has
551 * keys that send it */
553 bool resolved = false;
555 for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].end(); ++n) {
556 Note& note = *_notes[*n].get();
557 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
558 if (note.note() == note_num) {
559 assert(time >= note.time());
560 note.set_duration(time - note.time());
561 _write_notes[chan].erase(n);
562 //cerr << "MM resolved note, duration: " << note.duration() << endl;
569 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
570 << ", note " << (int)note_num << " @ " << time << endl;
575 MidiModel::append_automation_event_unlocked(AutomationType type, uint8_t chan, double time, uint8_t first_byte, uint8_t second_byte)
577 //cerr << "MidiModel " << this << " chan " << (int)chan <<
578 // " CC " << (int)number << " = " << (int)value << " @ " << time << endl;
588 case MidiCCAutomation:
590 value = double(second_byte);
592 case MidiChannelAftertouchAutomation:
593 case MidiPgmChangeAutomation:
595 value = double(first_byte);
597 case MidiPitchBenderAutomation:
599 value = double((0x7F & second_byte) << 7 | (0x7F & first_byte));
605 Parameter param(type, id, chan);
606 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
607 control->list()->fast_simple_add(time, value);
611 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
613 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
615 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
616 _notes.insert(i, note);
621 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
624 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
625 for(Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
627 const Note& _note = *note;
628 // TODO: There is still the issue, that after restarting ardour
629 // persisted undo does not work, because of rounding errors in the
630 // event times after saving/restoring to/from MIDI files
631 cerr << "======================================= " << endl;
632 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.duration()) << "-- #" << int(_n.velocity()) << endl;
633 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.duration()) << "-- #" << int(_note.velocity()) << endl;
634 cerr << "Equal: " << bool(_n == _note) << endl;
635 cerr << endl << endl;
638 // we have to break here, because erase invalidates all iterators, ie. n itself
644 /** Slow! for debugging only. */
647 MidiModel::is_sorted() const
650 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
651 if ((*n)->time() < t)
660 /** Start a new command.
662 * This has no side-effects on the model or Session, the returned command
663 * can be held on to for as long as the caller wishes, or discarded without
664 * formality, until apply_command is called and ownership is taken.
666 MidiModel::DeltaCommand*
667 MidiModel::new_delta_command(const string name)
669 DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
676 * Ownership of cmd is taken, it must not be deleted by the caller.
677 * The command will constitute one item on the undo stack.
680 MidiModel::apply_command(Command* cmd)
682 _session.begin_reversible_command(cmd->name());
685 _session.commit_reversible_command(cmd);
692 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
693 : Command(name), _model(m), _name(name)
698 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
705 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
707 //cerr << "MEC: apply" << endl;
709 _removed_notes.remove(note);
710 _added_notes.push_back(note);
715 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
717 //cerr << "MEC: remove" << endl;
719 _added_notes.remove(note);
720 _removed_notes.push_back(note);
725 MidiModel::DeltaCommand::operator()()
727 // This could be made much faster by using a priority_queue for added and
728 // removed notes (or sort here), and doing a single iteration over _model
730 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
731 const bool reset_iter = (_model->_read_iter.locked());
732 const double iter_time = _model->_read_iter->time();
735 _model->_read_iter = _model->end(); // drop read lock
737 assert( ! _model->_read_iter.locked());
739 _model->write_lock();
741 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
742 _model->add_note_unlocked(*i);
744 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
745 _model->remove_note_unlocked(*i);
747 _model->write_unlock();
750 _model->_read_iter = const_iterator(*_model.get(), iter_time);
752 _model->ContentsChanged(); /* EMIT SIGNAL */
757 MidiModel::DeltaCommand::undo()
759 // This could be made much faster by using a priority_queue for added and
760 // removed notes (or sort here), and doing a single iteration over _model
762 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
763 const bool reset_iter = (_model->_read_iter.locked());
764 const double iter_time = _model->_read_iter->time();
767 _model->_read_iter = _model->end(); // drop read lock
769 assert( ! _model->_read_iter.locked());
771 _model->write_lock();
773 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
774 _model->remove_note_unlocked(*i);
776 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
777 _model->add_note_unlocked(*i);
779 _model->write_unlock();
782 _model->_read_iter = const_iterator(*_model.get(), iter_time);
784 _model->ContentsChanged(); /* EMIT SIGNAL */
788 MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Note> note)
790 XMLNode *xml_note = new XMLNode("note");
791 ostringstream note_str(ios::ate);
792 note_str << int(note->note());
793 xml_note->add_property("note", note_str.str());
795 ostringstream channel_str(ios::ate);
796 channel_str << int(note->channel());
797 xml_note->add_property("channel", channel_str.str());
799 ostringstream time_str(ios::ate);
800 time_str << int(note->time());
801 xml_note->add_property("time", time_str.str());
803 ostringstream duration_str(ios::ate);
804 duration_str <<(unsigned int) note->duration();
805 xml_note->add_property("duration", duration_str.str());
807 ostringstream velocity_str(ios::ate);
808 velocity_str << (unsigned int) note->velocity();
809 xml_note->add_property("velocity", velocity_str.str());
814 boost::shared_ptr<Note>
815 MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
818 istringstream note_str(xml_note->property("note")->value());
821 unsigned int channel;
822 istringstream channel_str(xml_note->property("channel")->value());
823 channel_str >> channel;
826 istringstream time_str(xml_note->property("time")->value());
829 unsigned int duration;
830 istringstream duration_str(xml_note->property("duration")->value());
831 duration_str >> duration;
833 unsigned int velocity;
834 istringstream velocity_str(xml_note->property("velocity")->value());
835 velocity_str >> velocity;
837 boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
841 #define ADDED_NOTES_ELEMENT "added_notes"
842 #define REMOVED_NOTES_ELEMENT "removed_notes"
843 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
846 MidiModel::DeltaCommand::set_state (const XMLNode& delta_command)
848 if(delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
852 _added_notes.clear();
853 XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
854 XMLNodeList notes = added_notes->children();
855 transform(notes.begin(), notes.end(), back_inserter(_added_notes),
856 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
858 _removed_notes.clear();
859 XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
860 notes = removed_notes->children();
861 transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
862 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
868 MidiModel::DeltaCommand::get_state ()
870 XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
871 delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
873 XMLNode *added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
874 for_each(_added_notes.begin(), _added_notes.end(),
875 sigc::compose(sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
876 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
878 XMLNode *removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
879 for_each(_removed_notes.begin(), _removed_notes.end(),
880 sigc::compose(sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
881 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
883 return *delta_command;
887 struct EventTimeComparator {
888 typedef const MIDI::Event* value_type;
889 inline bool operator()(const MIDI::Event* a,
890 const MIDI::Event* b) const {
891 return a->time() >= b->time();
896 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
898 cerr << "Writing model to " << source->name() << endl;
900 /* This could be done using a temporary MidiRingBuffer and using
901 * MidiModel::read and MidiSource::write, but this is more efficient
902 * and doesn't require any buffer size assumptions (ie it's worth
903 * the code duplication).
905 * This is also different from read in that note off events are written
906 * regardless of the track mode. This is so the user can switch a
907 * recorded track (with note durations from some instrument) to percussive,
908 * save, reload, then switch it back to sustained preserving the original
914 LaterNoteEndComparator cmp;
915 ActiveNotes active_notes(cmp);
917 EventTimeComparator comp;
918 typedef std::priority_queue<
920 std::deque<const MIDI::Event*>,
921 EventTimeComparator> MidiEvents;
923 MidiEvents events(comp);
925 /* Why sort manyally, when a priority queue does the job for us,
926 * (I am probably wrong here, but I needed that to test program
927 * change code quickly) ???
930 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
932 // Write any pending note offs earlier than this note on
933 while ( ! active_notes.empty() ) {
934 const boost::shared_ptr<const Note> earliest_off = active_notes.top();
935 const MIDI::Event& off_ev = earliest_off->off_event();
936 if (off_ev.time() <= (*n)->time()) {
937 events.push(&off_ev);
944 // Write this note on
945 events.push(&(*n)->on_event());
946 if ((*n)->duration() > 0)
947 active_notes.push(*n);
950 // Write any trailing note offs
951 while ( ! active_notes.empty() ) {
952 events.push(&active_notes.top()->off_event());
956 while(!events.empty()) {
957 source->append_event_unlocked(Frames, *events.top());
958 cerr << "MidiModel::write_to appending event with time:" << dec << int(events.top()->time()) << hex
959 << " buffer: 0x" << int(events.top()->buffer()[0]) << " 0x" << int(events.top()->buffer()[1])
960 << " 0x" << int(events.top()->buffer()[2]) << endl;
972 MidiModel::get_state()
974 XMLNode *node = new XMLNode("MidiModel");
979 MidiModel::midi_source() const
985 MidiModel::set_midi_source(MidiSource *source)
987 _midi_source = source;