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 /* TODO: Disabled for stablility reasons
91 MidiControlIterator earliest_control(boost::shared_ptr<AutomationList>(), 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(i->second->list(), 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.x) {
117 earliest_control = new_iter;
118 _control_iter = _control_iters.end();
125 if (_note_iter != model.notes().end()) {
126 _event = MIDI::Event((*_note_iter)->on_event(), false);
127 _active_notes.push(*_note_iter);
128 //cerr << " new const iterator: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl;
132 /** TODO: Disabled for stability reasons
133 if (earliest_control.automation_list && earliest_control.x < _event.time())
134 model.control_to_midi_event(_event, earliest_control);
136 _control_iter = _control_iters.end();
139 _pgm_change_iter = model.pgm_changes().end();
140 // find first program change which begins after t
141 for (PgmChanges::const_iterator i = model.pgm_changes().begin(); i != model.pgm_changes().end(); ++i) {
142 if ((*i)->time() >= t) {
143 _pgm_change_iter = i;
148 if(_pgm_change_iter != model.pgm_changes().end()) {
149 if((*_pgm_change_iter)->time() <= _event.time()) {
150 _event = MIDI::Event(*(*_pgm_change_iter), false);
154 if (_event.size() == 0) {
155 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
158 // FIXME: possible race condition here....
160 _model->read_unlock();
164 printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
169 MidiModel::const_iterator::~const_iterator()
172 _model->read_unlock();
176 const MidiModel::const_iterator&
177 MidiModel::const_iterator::operator++()
180 throw std::logic_error("Attempt to iterate past end of MidiModel");
182 cerr << "const_iterator::operator++: _event type:" << hex << "0x" << int(_event.type())
183 << " buffer: 0x" << int(_event.buffer()[0]) << " 0x" << int(_event.buffer()[1])
184 << " 0x" << int(_event.buffer()[2]) << endl;
186 if(! (_event.is_note() || _event.is_cc() || _event.is_pgm_change())) {
187 cerr << "FAILED pgm change vector size: " << _model->pgm_changes().size() << endl;
188 cerr << "FAILED event buffer: " << hex << int(_event.buffer()[0]) << int(_event.buffer()[1]) << int(_event.buffer()[2]) << endl;
190 assert(_event.is_note() || _event.is_cc() || _event.is_pgm_change());
192 // TODO: This code crashes at the marked section
194 // Increment past current control event
195 if (_control_iter != _control_iters.end() && _control_iter->automation_list && _event.is_cc()) {
197 cerr << "control_iter x:" << _control_iter->x << " y:" << _control_iter->y << endl;
198 // v--- this crashes because of a null pointer in the stl containers linked list chain
199 // the crash occurs in _control_iter->automation_list->size();
200 const bool ret = _control_iter->automation_list->rt_safe_earliest_event_unlocked(
201 _control_iter->x, DBL_MAX, x, y, false);
204 //cerr << "Incremented " << _control_iter->automation_list->parameter().id() << " to " << x << endl;
205 _control_iter->x = x;
206 _control_iter->x = y;
208 //cerr << "Hit end of " << _control_iter->automation_list->parameter().id() << endl;
209 _control_iter->automation_list.reset();
210 _control_iter->x = DBL_MAX;
214 // Now find and point at the earliest event
216 _control_iter = _control_iters.begin();
218 for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
219 i != _control_iters.end(); ++i) {
220 if (i->x < _control_iter->x) {
227 enum Type { NIL, NOTE_ON, NOTE_OFF, CC, PGM_CHANGE, PITCH_BENDER };
232 // Next earliest note on
233 if (_note_iter != _model->notes().end()) {
235 t = (*_note_iter)->time();
238 // Use the next earliest note off iff it's earlier than the note on
239 if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
240 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
242 t = _active_notes.top()->end_time();
246 /* disabled for above mentioned reason, this loops endlessly otherwise
247 // Use the next earliest controller iff it's earlier than the note event
248 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX)
249 if (type == NIL || _control_iter->x < t)
252 if(_pgm_change_iter != _model->pgm_changes().end()) {
253 if((*_pgm_change_iter)->time() <= t) {
255 t = (*_pgm_change_iter)->time();
256 cerr << "operator++ got PGM CHANGE with time " << t << " and type " << hex
257 << int((*_pgm_change_iter)->type()) << " and channel " << int((*_pgm_change_iter)->channel())
258 << " and program " << int((*_pgm_change_iter)->pgm_number()) << endl;
262 if (type == NOTE_ON) {
263 cerr << "********** MIDI Iterator = note on" << endl;
264 _event = MIDI::Event((*_note_iter)->on_event(), false);
265 _active_notes.push(*_note_iter);
267 } else if (type == NOTE_OFF) {
268 cerr << "********** MIDI Iterator = note off" << endl;
269 _event = MIDI::Event(_active_notes.top()->off_event(), false);
271 } else if (type == CC) {
272 cerr << "********** MIDI Iterator = CC" << endl;
273 _model->control_to_midi_event(_event, *_control_iter);
274 } else if (type == PGM_CHANGE) {
275 cerr << "********** MIDI Iterator = program change" << endl;
276 _event = MIDI::Event(*(*_pgm_change_iter), false);
279 cerr << "********** MIDI Iterator = END" << endl;
283 assert(_is_end || _event.size() > 0);
290 MidiModel::const_iterator::operator==(const const_iterator& other) const
292 if (_is_end || other._is_end)
293 return (_is_end == other._is_end);
295 return (_event == other._event);
299 MidiModel::const_iterator&
300 MidiModel::const_iterator::operator=(const const_iterator& other)
302 if (_locked && _model != other._model)
303 _model->read_unlock();
305 assert( ! other._event.owns_buffer());
307 _model = other._model;
308 _event = other._event;
309 _active_notes = other._active_notes;
310 _is_end = other._is_end;
311 _locked = other._locked;
312 _note_iter = other._note_iter;
313 _control_iters = other._control_iters;
314 _control_iter = other._control_iter;
315 _pgm_change_iter = other._pgm_change_iter;
317 assert( ! _event.owns_buffer());
325 MidiModel::MidiModel(MidiSource *s, size_t size)
326 : Automatable(s->session(), "midi model")
328 , _note_mode(Sustained)
331 , _end_iter(*this, DBL_MAX)
332 , _next_read(UINT32_MAX)
333 , _read_iter(*this, DBL_MAX)
336 assert(_end_iter._is_end);
337 assert( ! _end_iter._locked);
340 /** Read events in frame range \a start .. \a start+cnt into \a dst,
341 * adding \a stamp_offset to each event's timestamp.
342 * \return number of events written to \a dst
345 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
347 //cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
348 //cerr << this << " MM # notes: " << n_notes() << endl;
350 size_t read_events = 0;
352 if (start != _next_read) {
353 _read_iter = const_iterator(*this, (double)start);
354 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
356 //cerr << "Using cached iterator at " << _next_read << endl;
359 _next_read = start + nframes;
361 while (_read_iter != end() && _read_iter->time() < start + nframes) {
362 assert(_read_iter->size() > 0);
363 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset, _read_iter->size(), _read_iter->buffer());
366 cerr << this << " MidiModel::read event @ " << _read_iter->time()
367 << " type: " << hex << int(_read_iter->type()) << dec
368 << " note: " << int(_read_iter->note())
369 << " velocity: " << int(_read_iter->velocity())
382 MidiModel::control_to_midi_event(MIDI::Event& ev, const MidiControlIterator& iter) const
384 if (iter.automation_list->parameter().type() == MidiCCAutomation) {
386 ev.set_buffer((Byte*)malloc(3), true);
388 assert(iter.automation_list);
389 assert(iter.automation_list->parameter().channel() < 16);
390 assert(iter.automation_list->parameter().id() <= INT8_MAX);
391 assert(iter.y <= INT8_MAX);
392 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.automation_list->parameter().channel();
393 ev.buffer()[1] = (Byte)iter.automation_list->parameter().id();
394 ev.buffer()[2] = (Byte)iter.y;
404 /** Begin a write of events to the model.
406 * If \a mode is Sustained, complete notes with duration are constructed as note
407 * on/off events are received. Otherwise (Percussive), only note on events are
408 * stored; note off events are discarded entirely and all contained notes will
412 MidiModel::start_write()
414 //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
417 for (int i = 0; i < 16; ++i)
418 _write_notes[i].clear();
424 /** Finish a write of events to the model.
426 * If \a delete_stuck is true and the current mode is Sustained, note on events
427 * that were never resolved with a corresonding note off will be deleted.
428 * Otherwise they will remain as notes with duration 0.
431 MidiModel::end_write(bool delete_stuck)
436 //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
438 if (_note_mode == Sustained && delete_stuck) {
439 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
440 if ((*n)->duration() == 0) {
441 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
443 // we have to break here because erase invalidates the iterator
451 for (int i = 0; i < 16; ++i) {
452 if (!_write_notes[i].empty()) {
453 cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
454 << _write_notes[i].size() << " stuck notes" << endl;
456 _write_notes[i].clear();
464 /** Append \a in_event to model. NOT realtime safe.
466 * Timestamps of events in \a buf are expected to be relative to
467 * the start of this model (t=0) and MUST be monotonically increasing
468 * and MUST be >= the latest event currently in the model.
471 MidiModel::append(const MIDI::Event& ev)
476 cerr << "MidiModel::append event type: " << hex << "0x" << int(ev.type()) << endl;
478 assert(_notes.empty() || ev.time() >= _notes.back()->time());
481 if (ev.is_note_on()) {
482 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
483 } else if (ev.is_note_off()) {
484 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
485 } else if (ev.is_cc()) {
486 append_cc_unlocked(ev.channel(), ev.time(), ev.cc_number(), ev.cc_value());
487 } else if (ev.is_pgm_change()) {
488 append_pgm_change_unlocked(ev.channel(), ev.time(), ev.pgm_number());
490 printf("MM Unknown event type %X\n", ev.type());
498 MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity)
500 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
501 " note " << (int)note_num << " on @ " << time << endl;*/
507 _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
508 if (_note_mode == Sustained) {
509 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
510 _write_notes[chan].push_back(_notes.size() - 1);
512 cerr << "MM Percussive: NOT appending active note on" << endl;
518 MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num)
520 /*cerr << "MidiModel " << this << " chan " << (int)chan <<
521 " note " << (int)note_num << " off @ " << time << endl;*/
527 if (_note_mode == Percussive) {
528 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
532 /* FIXME: make _write_notes fixed size (127 noted) for speed */
534 /* FIXME: note off velocity for that one guy out there who actually has
535 * keys that send it */
537 bool resolved = false;
539 for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].end(); ++n) {
540 Note& note = *_notes[*n].get();
541 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
542 if (note.note() == note_num) {
543 assert(time >= note.time());
544 note.set_duration(time - note.time());
545 _write_notes[chan].erase(n);
546 //cerr << "MM resolved note, duration: " << note.duration() << endl;
553 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
554 << ", note " << (int)note_num << " @ " << time << endl;
559 MidiModel::append_cc_unlocked(uint8_t chan, double time, uint8_t number, uint8_t value)
561 //cerr << "MidiModel " << this << " chan " << (int)chan <<
562 // " CC " << (int)number << " = " << (int)value << " @ " << time << endl;
566 /** TODO: disabled for now until debugged....
569 Parameter param(MidiCCAutomation, number, chan);
570 boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
571 control->list()->fast_simple_add(time, (double)value);
576 MidiModel::append_pgm_change_unlocked(uint8_t chan, double time, uint8_t number)
578 //cerr << "MidiModel::append_pgm_change_unlocked: channel " << int(chan) << " time: " << time << " program number: " << int(number) <<endl;
583 boost::shared_ptr<MIDI::Event> event_ptr(new MIDI::Event(time, 3, 0, true));
584 event_ptr->set_type(MIDI_CMD_PGM_CHANGE);
585 event_ptr->set_channel(chan);
586 event_ptr->set_pgm_number(number);
587 _pgm_changes.push_back(event_ptr);
591 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
593 //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
595 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
596 _notes.insert(i, note);
601 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
604 //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
605 for(Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
607 const Note& _note = *note;
608 // TODO: There is still the issue, that after restarting ardour
609 // persisted undo does not work, because of rounding errors in the
610 // event times after saving/restoring to/from MIDI files
611 cerr << "======================================= " << endl;
612 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.duration()) << "-- #" << int(_n.velocity()) << endl;
613 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.duration()) << "-- #" << int(_note.velocity()) << endl;
614 cerr << "Equal: " << bool(_n == _note) << endl;
615 cerr << endl << endl;
618 // we have to break here, because erase invalidates all iterators, ie. n itself
624 /** Slow! for debugging only. */
627 MidiModel::is_sorted() const
630 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
631 if ((*n)->time() < t)
640 /** Start a new command.
642 * This has no side-effects on the model or Session, the returned command
643 * can be held on to for as long as the caller wishes, or discarded without
644 * formality, until apply_command is called and ownership is taken.
646 MidiModel::DeltaCommand*
647 MidiModel::new_delta_command(const string name)
649 DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
656 * Ownership of cmd is taken, it must not be deleted by the caller.
657 * The command will constitute one item on the undo stack.
660 MidiModel::apply_command(Command* cmd)
662 _session.begin_reversible_command(cmd->name());
665 _session.commit_reversible_command(cmd);
672 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
673 : Command(name), _model(m), _name(name)
678 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
685 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
687 //cerr << "MEC: apply" << endl;
689 _removed_notes.remove(note);
690 _added_notes.push_back(note);
695 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
697 //cerr << "MEC: remove" << endl;
699 _added_notes.remove(note);
700 _removed_notes.push_back(note);
705 MidiModel::DeltaCommand::operator()()
707 // This could be made much faster by using a priority_queue for added and
708 // removed notes (or sort here), and doing a single iteration over _model
710 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
711 const bool reset_iter = (_model->_read_iter.locked());
712 const double iter_time = _model->_read_iter->time();
715 _model->_read_iter = _model->end(); // drop read lock
717 assert( ! _model->_read_iter.locked());
719 _model->write_lock();
721 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
722 _model->add_note_unlocked(*i);
724 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
725 _model->remove_note_unlocked(*i);
727 _model->write_unlock();
730 _model->_read_iter = const_iterator(*_model.get(), iter_time);
732 _model->ContentsChanged(); /* EMIT SIGNAL */
737 MidiModel::DeltaCommand::undo()
739 // This could be made much faster by using a priority_queue for added and
740 // removed notes (or sort here), and doing a single iteration over _model
742 // Need to reset iterator to drop the read lock it holds, or we'll deadlock
743 const bool reset_iter = (_model->_read_iter.locked());
744 const double iter_time = _model->_read_iter->time();
747 _model->_read_iter = _model->end(); // drop read lock
749 assert( ! _model->_read_iter.locked());
751 _model->write_lock();
753 for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
754 _model->remove_note_unlocked(*i);
756 for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
757 _model->add_note_unlocked(*i);
759 _model->write_unlock();
762 _model->_read_iter = const_iterator(*_model.get(), iter_time);
764 _model->ContentsChanged(); /* EMIT SIGNAL */
768 MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Note> note)
770 XMLNode *xml_note = new XMLNode("note");
771 ostringstream note_str(ios::ate);
772 note_str << int(note->note());
773 xml_note->add_property("note", note_str.str());
775 ostringstream channel_str(ios::ate);
776 channel_str << int(note->channel());
777 xml_note->add_property("channel", channel_str.str());
779 ostringstream time_str(ios::ate);
780 time_str << int(note->time());
781 xml_note->add_property("time", time_str.str());
783 ostringstream duration_str(ios::ate);
784 duration_str <<(unsigned int) note->duration();
785 xml_note->add_property("duration", duration_str.str());
787 ostringstream velocity_str(ios::ate);
788 velocity_str << (unsigned int) note->velocity();
789 xml_note->add_property("velocity", velocity_str.str());
794 boost::shared_ptr<Note>
795 MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
798 istringstream note_str(xml_note->property("note")->value());
801 unsigned int channel;
802 istringstream channel_str(xml_note->property("channel")->value());
803 channel_str >> channel;
806 istringstream time_str(xml_note->property("time")->value());
809 unsigned int duration;
810 istringstream duration_str(xml_note->property("duration")->value());
811 duration_str >> duration;
813 unsigned int velocity;
814 istringstream velocity_str(xml_note->property("velocity")->value());
815 velocity_str >> velocity;
817 boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
821 #define ADDED_NOTES_ELEMENT "added_notes"
822 #define REMOVED_NOTES_ELEMENT "removed_notes"
823 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
826 MidiModel::DeltaCommand::set_state (const XMLNode& delta_command)
828 if(delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
832 _added_notes.clear();
833 XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
834 XMLNodeList notes = added_notes->children();
835 transform(notes.begin(), notes.end(), back_inserter(_added_notes),
836 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
838 _removed_notes.clear();
839 XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
840 notes = removed_notes->children();
841 transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
842 sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
848 MidiModel::DeltaCommand::get_state ()
850 XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
851 delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
853 XMLNode *added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
854 for_each(_added_notes.begin(), _added_notes.end(),
855 sigc::compose(sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
856 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
858 XMLNode *removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
859 for_each(_removed_notes.begin(), _removed_notes.end(),
860 sigc::compose(sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
861 sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
863 return *delta_command;
867 struct EventTimeComparator {
868 typedef const MIDI::Event* value_type;
869 inline bool operator()(const MIDI::Event* a,
870 const MIDI::Event* b) const {
871 return a->time() >= b->time();
876 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
878 cerr << "Writing model to " << source->name() << endl;
880 /* This could be done using a temporary MidiRingBuffer and using
881 * MidiModel::read and MidiSource::write, but this is more efficient
882 * and doesn't require any buffer size assumptions (ie it's worth
883 * the code duplication).
885 * This is also different from read in that note off events are written
886 * regardless of the track mode. This is so the user can switch a
887 * recorded track (with note durations from some instrument) to percussive,
888 * save, reload, then switch it back to sustained preserving the original
894 LaterNoteEndComparator cmp;
895 ActiveNotes active_notes(cmp);
897 EventTimeComparator comp;
898 typedef std::priority_queue<
900 std::deque<const MIDI::Event*>,
901 EventTimeComparator> MidiEvents;
903 MidiEvents events(comp);
905 /* Why sort manyally, when a priority queue does the job for us,
906 * (I am probably wrong here, but I needed that to test program
907 * change code quickly) ???
910 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
912 // Write any pending note offs earlier than this note on
913 while ( ! active_notes.empty() ) {
914 const boost::shared_ptr<const Note> earliest_off = active_notes.top();
915 const MIDI::Event& off_ev = earliest_off->off_event();
916 if (off_ev.time() <= (*n)->time()) {
917 events.push(&off_ev);
924 // Write this note on
925 events.push(&(*n)->on_event());
926 if ((*n)->duration() > 0)
927 active_notes.push(*n);
930 // Write any trailing note offs
931 while ( ! active_notes.empty() ) {
932 events.push(&active_notes.top()->off_event());
936 //write program changes
937 for (PgmChanges::const_iterator p = _pgm_changes.begin(); p != _pgm_changes.end(); ++p) {
938 events.push((*p).get());
941 while(!events.empty()) {
942 source->append_event_unlocked(Frames, *events.top());
943 cerr << "MidiModel::write_to appending event with time:" << dec << int(events.top()->time()) << hex
944 << " buffer: 0x" << int(events.top()->buffer()[0]) << " 0x" << int(events.top()->buffer()[1])
945 << " 0x" << int(events.top()->buffer()[2]) << endl;
957 MidiModel::get_state()
959 XMLNode *node = new XMLNode("MidiModel");
964 MidiModel::midi_source() const
970 MidiModel::set_midi_source(MidiSource *source)
972 _midi_source = source;