MidiClock_SlaveTest: add basic framework
[ardour.git] / libs / ardour / midi_model.cc
index 9a87e89ab8c3fdd4143748eb1aeb71843785889e..baa3c2c7c016d4c54b408de7cf38e48c6d78e126 100644 (file)
@@ -1,6 +1,6 @@
 /*
-    Copyright (C) 2007 Paul Davis 
-       Written by Dave Robillard, 2007
+    Copyright (C) 2007 Paul Davis
+    Author: Dave Robillard
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
 #include <algorithm>
 #include <stdexcept>
 #include <stdint.h>
-#include <pbd/enumwriter.h>
-#include <ardour/midi_model.h>
-#include <ardour/midi_events.h>
-#include <ardour/midi_source.h>
-#include <ardour/types.h>
-#include <ardour/session.h>
+#include "pbd/error.h"
+#include "pbd/enumwriter.h"
+#include "midi++/events.h"
+
+#include "ardour/midi_model.h"
+#include "ardour/midi_source.h"
+#include "ardour/smf_source.h"
+#include "ardour/types.h"
+#include "ardour/session.h"
 
 using namespace std;
 using namespace ARDOUR;
+using namespace PBD;
 
+MidiModel::MidiModel(MidiSource* s, size_t size)
+       : AutomatableSequence<TimeType>(s->session(), size)
+       , _midi_source(s)
+{
+}
 
-// Read iterator (const_iterator)
+/** Start a new Delta command.
+ *
+ * This has no side-effects on the model or Session, the returned command
+ * can be held on to for as long as the caller wishes, or discarded without
+ * formality, until apply_command is called and ownership is taken.
+ */
+MidiModel::DeltaCommand*
+MidiModel::new_delta_command(const string name)
+{
+       DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
+       return cmd;
+}
 
-MidiModel::const_iterator::const_iterator(const MidiModel& model, double t)
-       : _model(&model)
-       , _is_end( (t == DBL_MAX) || model.empty())
-       , _locked( ! _is_end)
+/** Start a new Diff command.
+ *
+ * This has no side-effects on the model or Session, the returned command
+ * can be held on to for as long as the caller wishes, or discarded without
+ * formality, until apply_command is called and ownership is taken.
+ */
+MidiModel::DiffCommand*
+MidiModel::new_diff_command(const string name)
 {
-       //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl;
-       
-       if (_is_end)
-               return;
-
-       model.read_lock();
-       
-       _note_iter = model.notes().end();
-
-       for (MidiModel::Notes::const_iterator i = model.notes().begin(); i != model.notes().end(); ++i) {
-               if ((*i)->time() >= t) {
-                       _note_iter = i;
-                       break;
-               }
-       }
-                       
-       MidiControlIterator earliest_control = make_pair(boost::shared_ptr<AutomationList>(),
-                       make_pair(DBL_MAX, 0.0));
-
-       _control_iters.reserve(model.controls().size());
-       for (Automatable::Controls::const_iterator i = model.controls().begin();
-                       i != model.controls().end(); ++i) {
-
-               assert(i->first.type() == MidiCCAutomation);
-
-               double x, y;
-               bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
-               if (!ret) {
-                       /*cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
-                               << ") has no events past " << t << endl;*/
-                       continue;
-               } 
-
-               assert(x >= 0);
-               assert(y >= 0);
-               assert(y <= UINT8_MAX);
-               
-               const MidiControlIterator new_iter = make_pair(i->second->list(), make_pair(x, y));
-               
-               //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
-               _control_iters.push_back(new_iter);
-
-               if (x < earliest_control.second.first) {
-                       earliest_control = new_iter;
-                       _control_iter = _control_iters.end();
-                       --_control_iter;
-               }
-       }
+       DiffCommand* cmd = new DiffCommand(_midi_source->model(), name);
+       return cmd;
+}
 
-       if (_note_iter != model.notes().end()) {
-               _event = MidiEvent((*_note_iter)->on_event(), false);
-               _active_notes.push(*_note_iter);
-               ++_note_iter;
-       }
+/** Apply a command.
+ *
+ * Ownership of cmd is taken, it must not be deleted by the caller.
+ * The command will constitute one item on the undo stack.
+ */
+void
+MidiModel::apply_command(Session& session, Command* cmd)
+{
+       session.begin_reversible_command(cmd->name());
+       (*cmd)();
+       session.commit_reversible_command(cmd);
+       set_edited(true);
+}
 
-       if (earliest_control.first && earliest_control.second.first < _event.time())
-               model.control_to_midi_event(_event, earliest_control);
-       else
-               _control_iter = _control_iters.end();
+/** Apply a command as part of a larger reversible transaction
+ *
+ * Ownership of cmd is taken, it must not be deleted by the caller.
+ * The command will constitute one item on the undo stack.
+ */
+void
+MidiModel::apply_command_as_subcommand(Session& session, Command* cmd)
+{
+       (*cmd)();
+       session.add_command(cmd);
+       set_edited(true);
+}
 
-       if (_event.size() == 0) {
-               //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
-               _is_end = true;
-               _model->read_unlock();
-               _locked = false;
-       } /*else {
-               printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
-       }*/
+
+// DeltaCommand
+
+MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
+       : Command(name)
+       , _model(m)
+       , _name(name)
+{
+       assert(_model);
 }
 
+MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
+       : _model(m)
+{
+       assert(_model);
+       set_state(node, Stateful::loading_state_version);
+}
 
-MidiModel::const_iterator::~const_iterator()
+void
+MidiModel::DeltaCommand::add(const boost::shared_ptr< Evoral::Note<TimeType> > note)
 {
-       if (_locked)
-               _model->read_unlock();
+       _removed_notes.remove(note);
+       _added_notes.push_back(note);
 }
-               
 
-const MidiModel::const_iterator&
-MidiModel::const_iterator::operator++()
+void
+MidiModel::DeltaCommand::remove(const boost::shared_ptr< Evoral::Note<TimeType> > note)
 {
-       if (_is_end)
-               throw std::logic_error("Attempt to iterate past end of MidiModel");
+       _added_notes.remove(note);
+       _removed_notes.push_back(note);
+}
 
-       assert(_event.is_note() || _event.is_cc());
+void
+MidiModel::DeltaCommand::operator()()
+{
+       // This could be made much faster by using a priority_queue for added and
+       // removed notes (or sort here), and doing a single iteration over _model
 
-       // Increment past current control event
-       if (_control_iter != _control_iters.end() && _control_iter->first && _event.is_cc()) {
-               double x, y;
-               const bool ret = _control_iter->first->rt_safe_earliest_event_unlocked(
-                               _control_iter->second.first, DBL_MAX, x, y, false);
+       MidiModel::WriteLock lock(_model->edit_lock());
 
-               if (ret) {
-                       //cerr << "Incremented " << _control_iter->first->parameter().id() << " to " << x << endl;
-                       _control_iter->second.first = x;
-                       _control_iter->second.second = y;
-               } else {
-                       //cerr << "Hit end of " << _control_iter->first->parameter().id() << endl;
-                       _control_iter->first.reset();
-                       _control_iter->second.first = DBL_MAX;
-               }
+       for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) {
+               _model->add_note_unlocked(*i);
        }
 
-       // Now find and point at the earliest event
+       for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i) {
+               _model->remove_note_unlocked(*i);
+       }
 
-       _control_iter = _control_iters.begin();
+       lock.reset();
+       _model->ContentsChanged(); /* EMIT SIGNAL */
+}
 
-       for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
-                       i != _control_iters.end(); ++i) {
-               if (i->second.first < _control_iter->second.first) {
-                       _control_iter = i;
-               }
-       }
-       
-       enum Type { NIL, NOTE_ON, NOTE_OFF, CC };
-       
-       Type   type = NIL;
-       double t    = 0;
-
-       // Next earliest note on
-       if (_note_iter != _model->notes().end()) {
-               type = NOTE_ON;
-               t = (*_note_iter)->time();
-       }
-       
-       // Use the next earliest note off iff it's earlier than the note on
-       if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
-               if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
-                       type = NOTE_OFF;
-                       t = _active_notes.top()->end_time();
-               }
-       }
-       
-       // Use the next earliest controller iff it's earlier than the note event
-       if (_control_iter != _control_iters.end() && _control_iter->second.first != DBL_MAX)
-               if (type == NIL || _control_iter->second.first < t)
-                       type = CC;
-
-       if (type == NOTE_ON) {
-               //cerr << "********** MIDI Iterator = note on" << endl;
-               _event = MidiEvent((*_note_iter)->on_event(), false);
-               _active_notes.push(*_note_iter);
-               ++_note_iter;
-       } else if (type == NOTE_OFF) {
-               //cerr << "********** MIDI Iterator = note off" << endl;
-               _event = MidiEvent(_active_notes.top()->off_event(), false);
-               _active_notes.pop();
-       } else if (type == CC) {
-               //cerr << "********** MIDI Iterator = CC" << endl;
-               _model->control_to_midi_event(_event, *_control_iter);
-       } else {
-               //cerr << "********** MIDI Iterator = END" << endl;
-               _is_end = true;
-               _model->read_unlock();
-               _locked = false;
+void
+MidiModel::DeltaCommand::undo()
+{
+       // This could be made much faster by using a priority_queue for added and
+       // removed notes (or sort here), and doing a single iteration over _model
+
+       MidiModel::WriteLock lock(_model->edit_lock());;
+
+       for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) {
+               _model->remove_note_unlocked(*i);
        }
 
-       assert(_is_end || _event.size() > 0);
+       for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i) {
+               _model->add_note_unlocked(*i);
+       }
 
-       return *this;
+       lock.reset();
+       _model->ContentsChanged(); /* EMIT SIGNAL */
 }
-               
 
-bool
-MidiModel::const_iterator::operator==(const const_iterator& other) const
+XMLNode&
+MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr< Evoral::Note<TimeType> > note)
 {
-       if (_is_end || other._is_end)
-               return (_is_end == other._is_end);
-       else
-               return (_event == other._event);
-}
-               
+       XMLNode* xml_note = new XMLNode("note");
+       ostringstream note_str(ios::ate);
+       note_str << int(note->note());
+       xml_note->add_property("note", note_str.str());
 
-MidiModel::const_iterator&
-MidiModel::const_iterator::operator=(const const_iterator& other)
-{
-       if (_locked && _model != other._model)
-               _model->read_unlock();
-
-       assert( ! other._event.owns_buffer());
-
-       _model = other._model;
-       _event = other._event;
-       _is_end = other._is_end;
-       _locked = other._locked;
-       _note_iter = other._note_iter;
-       _control_iters = other._control_iters;
-       _control_iter = other._control_iter;
-       
-       assert( ! _event.owns_buffer());
-       
-       if (_locked)
-               _model->read_lock();
-
-       return *this;
-}
+       ostringstream channel_str(ios::ate);
+       channel_str << int(note->channel());
+       xml_note->add_property("channel", channel_str.str());
 
-       
-// MidiModel
-
-MidiModel::MidiModel(Session& s, size_t size)
-       : Automatable(s, "midi model")
-       , _notes(size)
-       , _note_mode(Sustained)
-       , _writing(false)
-       , _edited(false)
-       , _end_iter(*this, DBL_MAX)
-       , _next_read(UINT32_MAX)
-       , _read_iter(*this, DBL_MAX)
-{
-       assert(_end_iter._is_end);
-       assert( ! _end_iter._locked);
-}
+       ostringstream time_str(ios::ate);
+       time_str << int(note->time());
+       xml_note->add_property("time", time_str.str());
 
+       ostringstream length_str(ios::ate);
+       length_str <<(unsigned int) note->length();
+       xml_note->add_property("length", length_str.str());
 
-/** Read events in frame range \a start .. \a start+cnt into \a dst,
- * adding \a stamp_offset to each event's timestamp.
- * \return number of events written to \a dst
- */
-size_t
-MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset) const
-{
-       //cerr << this << " MM::read @ " << start << " * " << nframes << " + " << stamp_offset << endl;
-       //cerr << this << " MM # notes: " << n_notes() << endl;
+       ostringstream velocity_str(ios::ate);
+       velocity_str << (unsigned int) note->velocity();
+       xml_note->add_property("velocity", velocity_str.str());
 
-       size_t read_events = 0;
+       return *xml_note;
+}
 
-       if (start != _next_read) {
-               _read_iter = const_iterator(*this, (double)start);
-               //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
+boost::shared_ptr< Evoral::Note<MidiModel::TimeType> >
+MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
+{
+       unsigned int note;
+       XMLProperty* prop;
+       unsigned int channel;
+       unsigned int time;
+       unsigned int length;
+       unsigned int velocity;
+
+       if ((prop = xml_note->property("note")) != 0) {
+               istringstream note_str(prop->value());
+               note_str >> note;
        } else {
-               //cerr << "Using cached iterator at " << _next_read << endl;
+               warning << "note information missing note value" << endmsg;
+               note = 127;
        }
 
-       if (_read_iter == end()) {
-               //cerr << this << " MM::read: at end @ " << _read_iter->time() << endl;
+       if ((prop = xml_note->property("channel")) != 0) {
+               istringstream channel_str(prop->value());
+               channel_str >> channel;
        } else {
-               //cerr << this << " MM::read: at " << _read_iter->time() << endl;
+               warning << "note information missing channel" << endmsg;
+               channel = 0;
        }
 
-       _next_read = start + nframes;
+       if ((prop = xml_note->property("time")) != 0) {
+               istringstream time_str(prop->value());
+               time_str >> time;
+       } else {
+               warning << "note information missing time" << endmsg;
+               time = 0;
+       }
 
-       while (_read_iter != end() && _read_iter->time() < start + nframes) {
-               assert(_read_iter->size() > 0);
-               dst.write(_read_iter->time() + stamp_offset, _read_iter->size(), _read_iter->buffer());
-               //cerr << this << " MM::read event @ " << _read_iter->time() << endl;
-               ++_read_iter;
-               ++read_events;
+       if ((prop = xml_note->property("length")) != 0) {
+               istringstream length_str(prop->value());
+               length_str >> length;
+       } else {
+               warning << "note information missing length" << endmsg;
+               length = 1;
+       }
+
+       if ((prop = xml_note->property("velocity")) != 0) {
+               istringstream velocity_str(prop->value());
+               velocity_str >> velocity;
+       } else {
+               warning << "note information missing velocity" << endmsg;
+               velocity = 127;
        }
 
-       return read_events;
+       boost::shared_ptr< Evoral::Note<TimeType> > note_ptr(new Evoral::Note<TimeType>(
+                       channel, time, length, note, velocity));
+       return note_ptr;
 }
-       
 
-bool
-MidiModel::control_to_midi_event(MidiEvent& ev, const MidiControlIterator& iter) const
+#define ADDED_NOTES_ELEMENT "AddedNotes"
+#define REMOVED_NOTES_ELEMENT "RemovedNotes"
+#define DELTA_COMMAND_ELEMENT "DeltaCommand"
+
+int
+MidiModel::DeltaCommand::set_state (const XMLNode& delta_command, int /*version*/)
 {
-       if (iter.first->parameter().type() == MidiCCAutomation) {
-               if (ev.size() < 3)
-                       ev.set_buffer((Byte*)malloc(3), true);
-
-               assert(iter.first);
-               assert(iter.first->parameter().id() <= INT8_MAX);
-               assert(iter.second.second <= INT8_MAX);
-               ev.buffer()[0] = MIDI_CMD_CONTROL;
-               ev.buffer()[1] = (Byte)iter.first->parameter().id();
-               ev.buffer()[2] = (Byte)iter.second.second;
-               ev.time() = iter.second.first; // x
-               ev.size() = 3;
-               return true;
-       } else {
-               return false;
+       if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
+               return 1;
+       }
+
+       _added_notes.clear();
+       XMLNode* added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
+       if (added_notes) {
+               XMLNodeList notes = added_notes->children();
+               transform(notes.begin(), notes.end(), back_inserter(_added_notes),
+                         boost::bind (&DeltaCommand::unmarshal_note, this, _1));
+       }
+
+       _removed_notes.clear();
+       XMLNode* removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
+       if (removed_notes) {
+               XMLNodeList notes = removed_notes->children();
+               transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
+                         boost::bind (&DeltaCommand::unmarshal_note, this, _1));
        }
+
+       return 0;
 }
 
-       
-/** Begin a write of events to the model.
- *
- * If \a mode is Sustained, complete notes with duration are constructed as note
- * on/off events are received.  Otherwise (Percussive), only note on events are
- * stored; note off events are discarded entirely and all contained notes will
- * have duration 0.
- */
-void
-MidiModel::start_write()
+XMLNode&
+MidiModel::DeltaCommand::get_state()
 {
-       //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
-       write_lock();
-       _writing = true;
-       _write_notes.clear();
-       write_unlock();
+       XMLNode* delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
+       delta_command->add_property("midi-source", _model->midi_source()->id().to_s());
+
+       XMLNode* added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
+       for_each(_added_notes.begin(), _added_notes.end(), 
+                boost::bind(
+                        boost::bind (&XMLNode::add_child_nocopy, *added_notes, _1),
+                        boost::bind (&DeltaCommand::marshal_note, this, _1)));
+
+       XMLNode* removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
+       for_each(_removed_notes.begin(), _removed_notes.end(), 
+                boost::bind (
+                        boost::bind (&XMLNode::add_child_nocopy, *removed_notes, _1),
+                        boost::bind (&DeltaCommand::marshal_note, this, _1)));
+
+       return *delta_command;
 }
 
+/************** DIFF COMMAND ********************/
 
+#define DIFF_NOTES_ELEMENT "ChangedNotes"
+#define DIFF_COMMAND_ELEMENT "DiffCommand"
+
+MidiModel::DiffCommand::DiffCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
+       : Command(name)
+       , _model(m)
+       , _name(name)
+{
+       assert(_model);
+}
+
+MidiModel::DiffCommand::DiffCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
+       : _model(m)
+{
+       assert(_model);
+       set_state(node, Stateful::loading_state_version);
+}
 
-/** Finish a write of events to the model.
- *
- * If \a delete_stuck is true and the current mode is Sustained, note on events
- * that were never resolved with a corresonding note off will be deleted.
- * Otherwise they will remain as notes with duration 0.
- */
 void
-MidiModel::end_write(bool delete_stuck)
+MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
+                              uint8_t new_value)
 {
-       write_lock();
-       assert(_writing);
-       
-       //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
-
-       if (_note_mode == Sustained && delete_stuck) {
-               for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
-                       if ((*n)->duration() == 0) {
-                               cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
-                               n = _notes.erase(n);
-                       } else {
-                               ++n;
-                       }
-               }
+       NotePropertyChange change;
+
+       change.note = note;
+       change.property = prop;
+       change.new_value = new_value;
+
+       switch (prop) {
+       case NoteNumber:
+               change.old_value = note->note();
+               break;
+       case Velocity:
+               change.old_value = note->velocity();
+               break;
+       case StartTime:
+               fatal << "MidiModel::DiffCommand::change() with integer argument called for start time" << endmsg;
+               /*NOTREACHED*/
+               break;
+       case Length:
+               fatal << "MidiModel::DiffCommand::change() with integer argument called for length" << endmsg;
+               /*NOTREACHED*/
+               break;
+       case Channel:
+               change.old_value = note->channel();
+               break;
        }
 
-       _write_notes.clear();
-       _writing = false;
-       write_unlock();
+       _changes.push_back (change);
 }
 
-
-/** Append \a in_event to model.  NOT realtime safe.
- *
- * Timestamps of events in \a buf are expected to be relative to
- * the start of this model (t=0) and MUST be monotonically increasing
- * and MUST be >= the latest event currently in the model.
- */
 void
-MidiModel::append(const MidiEvent& ev)
+MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
+                              TimeType new_time)
 {
-       write_lock();
-
-       assert(_notes.empty() || ev.time() >= _notes.back()->time());
-       assert(_writing);
-
-       if (ev.is_note_on())
-               append_note_on_unlocked(ev.time(), ev.note(), ev.velocity());
-       else if (ev.is_note_off())
-               append_note_off_unlocked(ev.time(), ev.note());
-       else if (ev.is_cc())
-               append_cc_unlocked(ev.time(), ev.cc_number(), ev.cc_value());
-       else
-               printf("MM Unknown event type %X\n", ev.type());
-       
-       write_unlock();
-}
+       NotePropertyChange change;
+
+       change.note = note;
+       change.property = prop;
+       change.new_time = new_time;
+
+       switch (prop) {
+       case NoteNumber:
+       case Channel:
+       case Velocity:
+               fatal << "MidiModel::DiffCommand::change() with time argument called for note, channel or velocity" << endmsg;
+               break;
+       case StartTime:
+               change.old_time = note->time();
+               break;
+       case Length:
+               change.old_time = note->length();
+               break;
+       }
 
+       _changes.push_back (change);
+}
 
 void
-MidiModel::append_note_on_unlocked(double time, uint8_t note_num, uint8_t velocity)
+MidiModel::DiffCommand::operator()()
 {
-       //cerr << "MidiModel " << this << " note " << (int)note_num << " on @ " << time << endl;
+       MidiModel::WriteLock lock(_model->edit_lock());
 
-       assert(_writing);
-       _notes.push_back(boost::shared_ptr<Note>(new Note(time, 0, note_num, velocity)));
-       if (_note_mode == Sustained) {
-               //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
-               _write_notes.push_back(_notes.size() - 1);
-       } else {
-               //cerr << "MM Percussive: NOT appending active note on" << endl;
+       for (ChangeList::iterator i = _changes.begin(); i != _changes.end(); ++i) {
+               Property prop = i->property;
+               switch (prop) {
+               case NoteNumber:
+                       i->note->set_note (i->new_value);
+                       break;
+               case Velocity:
+                       i->note->set_velocity (i->new_value);
+                       break;
+               case StartTime:
+                       i->note->set_time (i->new_time);
+                       break;
+               case Length:
+                       i->note->set_length (i->new_time);
+                       break;
+               case Channel:
+                       i->note->set_channel (i->new_value);
+                       break;
+               }
        }
-}
 
+       lock.reset();
+       _model->ContentsChanged(); /* EMIT SIGNAL */
+}
 
 void
-MidiModel::append_note_off_unlocked(double time, uint8_t note_num)
+MidiModel::DiffCommand::undo()
 {
-       //cerr << "MidiModel " << this << " note " << (int)note_num << " off @ " << time << endl;
+       MidiModel::WriteLock lock(_model->edit_lock());
 
-       assert(_writing);
-       if (_note_mode == Percussive) {
-               //cerr << "MM Ignoring note off (percussive mode)" << endl;
-               return;
-       } else {
-               //cerr << "MM Attempting to resolve note off " << (unsigned)(uint8_t)note_num << endl;
-       }
-
-       /* FIXME: make _write_notes fixed size (127 noted) for speed */
-       
-       /* FIXME: note off velocity for that one guy out there who actually has
-        * keys that send it */
-
-       for (WriteNotes::iterator n = _write_notes.begin(); n != _write_notes.end(); ++n) {
-               Note& note = *_notes[*n].get();
-               //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
-               if (note.note() == note_num) {
-                       assert(time > note.time());
-                       note.set_duration(time - note.time());
-                       _write_notes.erase(n);
-                       //cerr << "MM resolved note, duration: " << note.duration() << endl;
+       for (ChangeList::iterator i = _changes.begin(); i != _changes.end(); ++i) {
+               Property prop = i->property;
+               switch (prop) {
+               case NoteNumber:
+                       i->note->set_note (i->old_value);
+                       break;
+               case Velocity:
+                       i->note->set_velocity (i->old_value);
+                       break;
+               case StartTime:
+                       i->note->set_time (i->old_time);
+                       break;
+               case Length:
+                       i->note->set_length (i->old_time);
+                       break;
+               case Channel:
+                       i->note->set_channel (i->old_value);
                        break;
                }
        }
-}
 
+       lock.reset();
+       _model->ContentsChanged(); /* EMIT SIGNAL */
+}
 
-void
-MidiModel::append_cc_unlocked(double time, uint8_t number, uint8_t value)
+XMLNode&
+MidiModel::DiffCommand::marshal_change(const NotePropertyChange& change)
 {
-       Parameter param(MidiCCAutomation, number);
-       
-       boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
-       //cerr << "MidiModel " << this << "(" << control.get() << ") add CC " << (int)number << " = " << (int)value
-       //      << " @ " << time << endl;
-       control->list()->fast_simple_add(time, (double)value);
-}
+       XMLNode* xml_change = new XMLNode("change");
 
+       /* first, the change itself */
 
-void
-MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
-{
-       //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
-       Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
-       _notes.insert(i, note);
-}
+       xml_change->add_property ("property", enum_2_string (change.property));
 
+       {
+               ostringstream old_value_str (ios::ate);
+               if (change.property == StartTime || change.property == Length) {
+                       old_value_str << change.old_time;
+               } else {
+                       old_value_str << (unsigned int) change.old_value;
+               }
+               xml_change->add_property ("old", old_value_str.str());
+       }
 
-void
-MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
-{
-       //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
-       Notes::iterator n = find(_notes.begin(), _notes.end(), note);
-       if (n != _notes.end())
-               _notes.erase(n);
-}
+       {
+               ostringstream new_value_str (ios::ate);
+               if (change.property == StartTime || change.property == Length) {
+                       new_value_str << change.new_time;
+               } else {
+                       new_value_str << (unsigned int) change.new_value;
+               }
+               xml_change->add_property ("new", new_value_str.str());
+       }
 
-/** Slow!  for debugging only. */
-#ifndef NDEBUG
-bool
-MidiModel::is_sorted() const
-{
-       bool t = 0;
-       for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
-               if ((*n)->time() < t)
-                       return false;
-               else
-                       t = (*n)->time();
+       /* now the rest of the note */
 
-       return true;
+       const SMFSource* smf = dynamic_cast<const SMFSource*> (_model->midi_source());
+
+       if (change.property != NoteNumber) {
+               ostringstream note_str;
+               note_str << int(change.note->note());
+               xml_change->add_property("note", note_str.str());
+       }
+
+       if (change.property != Channel) {
+               ostringstream channel_str;
+               channel_str << int(change.note->channel());
+               xml_change->add_property("channel", channel_str.str());
+       }
+
+       if (change.property != StartTime) {
+               ostringstream time_str;
+               if (smf) {
+                       time_str << smf->round_to_file_precision (change.note->time());
+               } else {
+                       time_str << change.note->time();
+               }
+               xml_change->add_property("time", time_str.str());
+       }
+
+       if (change.property != Length) {
+               ostringstream length_str;
+               if (smf) {
+                       length_str << smf->round_to_file_precision (change.note->length());
+               } else {
+                       length_str << change.note->length();
+               }
+               xml_change->add_property ("length", length_str.str());
+       }
+
+       if (change.property != Velocity) {
+               ostringstream velocity_str;
+               velocity_str << int (change.note->velocity());
+               xml_change->add_property("velocity", velocity_str.str());
+       }
+
+       return *xml_change;
 }
-#endif
 
-/** Start a new command.
- *
- * This has no side-effects on the model or Session, the returned command
- * can be held on to for as long as the caller wishes, or discarded without
- * formality, until apply_command is called and ownership is taken.
- */
-MidiModel::DeltaCommand*
-MidiModel::new_delta_command(const string name)
+MidiModel::DiffCommand::NotePropertyChange
+MidiModel::DiffCommand::unmarshal_change(XMLNode *xml_change)
 {
-       DeltaCommand* cmd =  new DeltaCommand(*this, name);
-       return cmd;
-}
+       XMLProperty* prop;
+       NotePropertyChange change;
+       unsigned int note;
+       unsigned int channel;
+       unsigned int velocity;
+       Evoral::MusicalTime time;
+       Evoral::MusicalTime length;
+
+       if ((prop = xml_change->property("property")) != 0) {
+               change.property = (Property) string_2_enum (prop->value(), change.property);
+       } else {
+               fatal << "!!!" << endmsg;
+               /*NOTREACHED*/
+       }
 
+       if ((prop = xml_change->property ("old")) != 0) {
+               istringstream old_str (prop->value());
+               if (change.property == StartTime || change.property == Length) {
+                       old_str >> change.old_time;
+               } else {
+                       int integer_value_so_that_istream_does_the_right_thing;
+                       old_str >> integer_value_so_that_istream_does_the_right_thing;
+                       change.old_value = integer_value_so_that_istream_does_the_right_thing;
+               }
+       } else {
+               fatal << "!!!" << endmsg;
+               /*NOTREACHED*/
+       }
 
-/** Apply a command.
- *
- * Ownership of cmd is taken, it must not be deleted by the caller.
- * The command will constitute one item on the undo stack.
- */
-void
-MidiModel::apply_command(Command* cmd)
-{
-       _session.begin_reversible_command(cmd->name());
-       (*cmd)();
-       assert(is_sorted());
-       _session.commit_reversible_command(cmd);
-       _edited = true;
-}
+       if ((prop = xml_change->property ("new")) != 0) {
+               istringstream new_str (prop->value());
+               if (change.property == StartTime || change.property == Length) {
+                       new_str >> change.new_time;
+               } else {
+                       int integer_value_so_that_istream_does_the_right_thing;
+                       new_str >> integer_value_so_that_istream_does_the_right_thing;
+                       change.new_value = integer_value_so_that_istream_does_the_right_thing;
+               }
+       } else {
+               fatal << "!!!" << endmsg;
+               /*NOTREACHED*/
+       }
+
+       if (change.property != NoteNumber) {
+               if ((prop = xml_change->property("note")) != 0) {
+                       istringstream note_str(prop->value());
+                       note_str >> note;
+               } else {
+                       warning << "note information missing note value" << endmsg;
+                       note = 127;
+               }
+       } else {
+               note = change.new_value;
+       }
 
+       if (change.property != Channel) {
+               if ((prop = xml_change->property("channel")) != 0) {
+                       istringstream channel_str(prop->value());
+                       channel_str >> channel;
+               } else {
+                       warning << "note information missing channel" << endmsg;
+                       channel = 0;
+               }
+       } else {
+               channel = change.new_value;
+       }
 
-// MidiEditCommand
+       if (change.property != StartTime) {
+               if ((prop = xml_change->property("time")) != 0) {
+                       istringstream time_str(prop->value());
+                       time_str >> time;
+               } else {
+                       warning << "note information missing time" << endmsg;
+                       time = 0;
+               }
+       } else {
+               time = change.new_time;
+       }
 
+       if (change.property != Length) {
+               if ((prop = xml_change->property("length")) != 0) {
+                       istringstream length_str(prop->value());
+                       length_str >> length;
+               } else {
+                       warning << "note information missing length" << endmsg;
+                       length = 1;
+               }
+       } else {
+               length = change.new_time;
+       }
 
-void
-MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
-{
-       //cerr << "MEC: apply" << endl;
+       if (change.property != Velocity) {
+               if ((prop = xml_change->property("velocity")) != 0) {
+                       istringstream velocity_str(prop->value());
+                       velocity_str >> velocity;
+               } else {
+                       warning << "note information missing velocity" << endmsg;
+                       velocity = 127;
+               }
+       } else {
+               velocity = change.new_value;
+       }
 
-       _removed_notes.remove(note);
-       _added_notes.push_back(note);
-}
+       /* we must point at the instance of the note that is actually in the model.
+          so go look for it ...
+       */
 
+       boost::shared_ptr<Evoral::Note<TimeType> > new_note (new Evoral::Note<TimeType> (channel, time, length, note, velocity));
 
-void
-MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
-{
-       //cerr << "MEC: remove" << endl;
+       change.note = _model->find_note (new_note);
 
-       _added_notes.remove(note);
-       _removed_notes.push_back(note);
+       if (!change.note) {
+               warning << "MIDI note " << *new_note << " not found in model - programmers should investigate this" << endmsg;
+               /* use the actual new note */
+               change.note = new_note;
+       }
+
+       return change;
 }
 
-               
-void 
-MidiModel::DeltaCommand::operator()()
+int
+MidiModel::DiffCommand::set_state(const XMLNode& diff_command, int /*version*/)
 {
-       // This could be made much faster by using a priority_queue for added and
-       // removed notes (or sort here), and doing a single iteration over _model
-       
-       // Need to reset iterator to drop the read lock it holds, or we'll deadlock
-       const bool   reset_iter = (_model._read_iter.locked());
-       const double iter_time  = _model._read_iter->time();
-
-       if (reset_iter)
-               _model._read_iter = _model.end(); // drop read lock
-
-       assert( ! _model._read_iter.locked());
-
-       _model.write_lock();
-       
-       for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
-               _model.add_note_unlocked(*i);
-       
-       for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
-               _model.remove_note_unlocked(*i);
-       
-       _model.write_unlock();
-
-       if (reset_iter)
-               _model._read_iter = const_iterator(_model, iter_time);
-       
-       _model.ContentsChanged(); /* EMIT SIGNAL */
-}
+       if (diff_command.name() != string(DIFF_COMMAND_ELEMENT)) {
+               return 1;
+       }
 
+       _changes.clear();
 
-void
-MidiModel::DeltaCommand::undo()
-{
-       // This could be made much faster by using a priority_queue for added and
-       // removed notes (or sort here), and doing a single iteration over _model
-       
-       // Need to reset iterator to drop the read lock it holds, or we'll deadlock
-       const bool   reset_iter = (_model._read_iter.locked());
-       const double iter_time  = _model._read_iter->time();
-
-       if (reset_iter)
-               _model._read_iter = _model.end(); // drop read lock
-       
-       assert( ! _model._read_iter.locked());
-
-       _model.write_lock();
-
-       for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
-               _model.remove_note_unlocked(*i);
-       
-       for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
-               _model.add_note_unlocked(*i);
-       
-       _model.write_unlock();
-       
-       if (reset_iter)
-               _model._read_iter = const_iterator(_model, iter_time);
-       
-       _model.ContentsChanged(); /* EMIT SIGNAL */
+       XMLNode* changed_notes = diff_command.child(DIFF_NOTES_ELEMENT);
+
+       if (changed_notes) {
+               XMLNodeList notes = changed_notes->children();
+               transform (notes.begin(), notes.end(), back_inserter(_changes),
+                          boost::bind (&DiffCommand::unmarshal_change, this, _1));
+
+       }
+
+       return 0;
 }
 
+XMLNode&
+MidiModel::DiffCommand::get_state ()
+{
+       XMLNode* diff_command = new XMLNode(DIFF_COMMAND_ELEMENT);
+       diff_command->add_property("midi-source", _model->midi_source()->id().to_s());
 
+       XMLNode* changes = diff_command->add_child(DIFF_NOTES_ELEMENT);
+       for_each(_changes.begin(), _changes.end(), 
+                boost::bind (
+                        boost::bind (&XMLNode::add_child_nocopy, *changes, _1),
+                        boost::bind (&DiffCommand::marshal_change, this, _1)));
+
+       return *diff_command;
+}
+
+/** Write the model to a MidiSource (i.e. save the model).
+ * This is different from manually using read to write to a source in that
+ * note off events are written regardless of the track mode.  This is so the
+ * user can switch a recorded track (with note durations from some instrument)
+ * to percussive, save, reload, then switch it back to sustained without
+ * destroying the original note durations.
+ */
 bool
 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
 {
-       //cerr << "Writing model to " << source->name() << endl;
-
-       /* This could be done using a temporary MidiRingBuffer and using
-        * MidiModel::read and MidiSource::write, but this is more efficient
-        * and doesn't require any buffer size assumptions (ie it's worth
-        * the code duplication).
-        *
-        * This is also different from read in that note off events are written
-        * regardless of the track mode.  This is so the user can switch a
-        * recorded track (with note durations from some instrument) to percussive,
-        * save, reload, then switch it back to sustained preserving the original
-        * note durations.
-        */
-
-       /* Percussive 
-       for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
-               const MidiEvent& ev = n->on_event();
-               source->append_event_unlocked(ev);
-       }*/
-
-       read_lock();
-
-       LaterNoteEndComparator cmp;
-       ActiveNotes active_notes(cmp);
-               
-       // Foreach note
-       for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
-
-               // Write any pending note offs earlier than this note on
-               while ( ! active_notes.empty() ) {
-                       const boost::shared_ptr<const Note> earliest_off = active_notes.top();
-                       const MidiEvent& off_ev = earliest_off->off_event();
-                       if (off_ev.time() <= (*n)->time()) {
-                               source->append_event_unlocked(off_ev);
-                               active_notes.pop();
-                       } else {
-                               break;
-                       }
-               }
+       ReadLock lock(read_lock());
 
-               // Write this note on
-               source->append_event_unlocked((*n)->on_event());
-               if ((*n)->duration() > 0)
-                       active_notes.push(*n);
-       }
-               
-       // Write any trailing note offs
-       while ( ! active_notes.empty() ) {
-               source->append_event_unlocked(active_notes.top()->off_event());
-               active_notes.pop();
+       const bool old_percussive = percussive();
+       set_percussive(false);
+
+       source->drop_model();
+       source->mark_streaming_midi_write_started(note_mode(), _midi_source->timeline_position());
+
+       for (Evoral::Sequence<TimeType>::const_iterator i = begin(); i != end(); ++i) {
+               source->append_event_unlocked_beats(*i);
        }
 
-       _edited = false;
-       
-       read_unlock();
+       set_percussive(old_percussive);
+       source->mark_streaming_write_completed();
+
+       set_edited(false);
 
        return true;
 }
@@ -675,3 +712,39 @@ MidiModel::get_state()
        return *node;
 }
 
+boost::shared_ptr<Evoral::Note<MidiModel::TimeType> >
+MidiModel::find_note (boost::shared_ptr<Evoral::Note<TimeType> > other)
+{
+       Notes::iterator l = notes().lower_bound(other);
+
+       if (l != notes().end()) {
+               for (; (*l)->time() == other->time(); ++l) {
+                       if (*l == other) {
+                               return *l;
+                       }
+               }
+       }
+
+       return boost::shared_ptr<Evoral::Note<TimeType> >();
+}
+
+/** Lock and invalidate the source.
+ * This should be used by commands and editing things
+ */
+MidiModel::WriteLock
+MidiModel::edit_lock()
+{
+       Glib::Mutex::Lock* source_lock = new Glib::Mutex::Lock(_midi_source->mutex());
+       _midi_source->invalidate(); // Release cached iterator's read lock on model
+       return WriteLock(new WriteLockImpl(source_lock, _lock, _control_lock));
+}
+
+/** Lock just the model, the source lock must already be held.
+ * This should only be called from libardour/evoral places
+ */
+MidiModel::WriteLock
+MidiModel::write_lock()
+{
+       assert(!_midi_source->mutex().trylock());
+       return WriteLock(new WriteLockImpl(NULL, _lock, _control_lock));
+}