debug flag for session destruction and waf option for boost SP debug
[ardour.git] / libs / ardour / midi_model.cc
index 7c80ed9a3b56548fee316a957e0162513f77b7f1..47bc14852c1cf1828521f98fbc57415bebff3938 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
 
 */
 
+#define __STDC_LIMIT_MACROS 1
+
 #include <iostream>
 #include <algorithm>
-#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 <stdexcept>
+#include <stdint.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;
 
-// Note
+MidiModel::MidiModel(MidiSource* s, size_t size)
+       : AutomatableSequence<TimeType>(s->session(), size)
+       , _midi_source(s)
+{
+}
 
-MidiModel::Note::Note(double t, double d, uint8_t n, uint8_t v)
-       : _on_event(t, 3, NULL, true)
-       , _off_event(t + d, 3, NULL, true)
+/** 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)
 {
-       _on_event.buffer()[0] = MIDI_CMD_NOTE_ON;
-       _on_event.buffer()[1] = n;
-       _on_event.buffer()[2] = v;
-       
-       _off_event.buffer()[0] = MIDI_CMD_NOTE_OFF;
-       _off_event.buffer()[1] = n;
-       _off_event.buffer()[2] = 0x40;
-       
-       assert(time() == t);
-       assert(duration() == d);
-       assert(note() == n);
-       assert(velocity() == v);
+       DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
+       return cmd;
 }
 
+/** 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)
+{
+       DiffCommand* cmd = new DiffCommand(_midi_source->model(), name);
+       return cmd;
+}
 
-MidiModel::Note::Note(const Note& copy)
-       : _on_event(copy._on_event, true)
-       , _off_event(copy._off_event, true)
+/** 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)
 {
-       /*
-       assert(copy._on_event.size == 3);
-       _on_event.buffer = _on_event_buffer;
-       memcpy(_on_event_buffer, copy._on_event_buffer, 3);
-       
-       assert(copy._off_event.size == 3);
-       _off_event.buffer = _off_event_buffer;
-       memcpy(_off_event_buffer, copy._off_event_buffer, 3);
-       */
+       session.begin_reversible_command(cmd->name());
+       (*cmd)();
+       session.commit_reversible_command(cmd);
+       set_edited(true);
+}
 
-       assert(time() == copy.time());
-       assert(end_time() == copy.end_time());
-       assert(note() == copy.note());
-       assert(velocity() == copy.velocity());
-       assert(duration() == copy.duration());
+/** 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);
 }
 
 
-const MidiModel::Note&
-MidiModel::Note::operator=(const Note& copy)
+// DeltaCommand
+
+MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
+       : Command(name)
+       , _model(m)
+       , _name(name)
 {
-       _on_event = copy._on_event;
-       _off_event = copy._off_event;
-       /*_on_event.time = copy._on_event.time;
-       assert(copy._on_event.size == 3);
-       memcpy(_on_event_buffer, copy._on_event_buffer, 3);
-       
-       _off_event.time = copy._off_event.time;
-       assert(copy._off_event.size == 3);
-       memcpy(_off_event_buffer, copy._off_event_buffer, 3);
-       */
-       
-       assert(time() == copy.time());
-       assert(end_time() == copy.end_time());
-       assert(note() == copy.note());
-       assert(velocity() == copy.velocity());
-       assert(duration() == copy.duration());
-
-       return *this;
+       assert(_model);
 }
 
-// MidiModel
+MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
+       : _model(m)
+{
+       assert(_model);
+       set_state(node, Stateful::loading_state_version);
+}
 
-MidiModel::MidiModel(Session& s, size_t size)
-       : Automatable(s, "midi model")
-       , _notes(size)
-       , _note_mode(Sustained)
-       , _writing(false)
-       , _edited(false)
-       , _active_notes(LaterNoteEndComparator())
+void
+MidiModel::DeltaCommand::add(const boost::shared_ptr< Evoral::Note<TimeType> > note)
 {
+       _removed_notes.remove(note);
+       _added_notes.push_back(note);
 }
 
+void
+MidiModel::DeltaCommand::remove(const boost::shared_ptr< Evoral::Note<TimeType> > note)
+{
+       _added_notes.remove(note);
+       _removed_notes.push_back(note);
+}
 
-/** 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
+void
+MidiModel::DeltaCommand::operator()()
 {
-       size_t read_events = 0;
+       // 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
 
-       /* FIXME: cache last lookup value to avoid O(n) search every time */
+       MidiModel::WriteLock lock(_model->edit_lock());
 
-       if (_note_mode == Sustained) {
+       for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) {
+               _model->add_note_unlocked(*i);
+       }
 
-               for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
+       for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i) {
+               _model->remove_note_unlocked(*i);
+       }
 
-                       while ( ! _active_notes.empty() ) {
-                               const Note* const earliest_off = _active_notes.top();
-                               const MidiEvent&  off_ev       = earliest_off->off_event();
-                               if (off_ev.time() < start + nframes && off_ev.time() <= n->time()) {
-                                       dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
-                                       _active_notes.pop();
-                                       ++read_events;
-                               } else {
-                                       break;
-                               }
-                       }
+       lock.reset();
+       _model->ContentsChanged(); /* EMIT SIGNAL */
+}
 
-                       if (n->time() >= start + nframes)
-                               break;
+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
 
-                       // Note on
-                       if (n->time() >= start) {
-                               const MidiEvent& on_ev = n->on_event();
-                               dst.write(on_ev.time() + stamp_offset, on_ev.size(), on_ev.buffer());
-                               _active_notes.push(&(*n));
-                               ++read_events;
-                       }
+       MidiModel::WriteLock lock(_model->edit_lock());;
 
-               }
-                       
-               // Write any trailing note offs
-               while ( ! _active_notes.empty() ) {
-                       const Note* const earliest_off = _active_notes.top();
-                       const MidiEvent&  off_ev       = earliest_off->off_event();
-                       if (off_ev.time() < start + nframes) {
-                               dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
-                               _active_notes.pop();
-                               ++read_events;
-                       } else {
-                               break;
-                       }
-               }
+       for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) {
+               _model->remove_note_unlocked(*i);
+       }
 
-       // Percussive
-       } else {
-               for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
-                       // Note on
-                       if (n->time() >= start) {
-                               if (n->time() < start + nframes) {
-                                       const MidiEvent& ev = n->on_event();
-                                       dst.write(ev.time() + stamp_offset, ev.size(), ev.buffer());
-                                       ++read_events;
-                               } else {
-                                       break;
-                               }
-                       }
-               }
+       for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i) {
+               _model->add_note_unlocked(*i);
        }
 
-       return read_events;
+       lock.reset();
+       _model->ContentsChanged(); /* EMIT SIGNAL */
 }
 
-
-/** 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::marshal_note(const boost::shared_ptr< Evoral::Note<TimeType> > note)
 {
-       //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
-       write_lock();
-       _writing = true;
-       _write_notes.clear();
-       write_unlock();
-}
+       XMLNode* xml_note = new XMLNode("note");
+       ostringstream note_str(ios::ate);
+       note_str << int(note->note());
+       xml_note->add_property("note", note_str.str());
 
+       ostringstream channel_str(ios::ate);
+       channel_str << int(note->channel());
+       xml_note->add_property("channel", channel_str.str());
 
+       ostringstream time_str(ios::ate);
+       time_str << int(note->time());
+       xml_note->add_property("time", time_str.str());
 
-/** 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)
+       ostringstream length_str(ios::ate);
+       length_str <<(unsigned int) note->length();
+       xml_note->add_property("length", length_str.str());
+
+       ostringstream velocity_str(ios::ate);
+       velocity_str << (unsigned int) note->velocity();
+       xml_note->add_property("velocity", velocity_str.str());
+
+       return *xml_note;
+}
+
+boost::shared_ptr< Evoral::Note<MidiModel::TimeType> >
+MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
 {
-       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;
-                       }
-               }
+       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 {
+               warning << "note information missing note value" << endmsg;
+               note = 127;
+       }
+
+       if ((prop = xml_note->property("channel")) != 0) {
+               istringstream channel_str(prop->value());
+               channel_str >> channel;
+       } else {
+               warning << "note information missing channel" << endmsg;
+               channel = 0;
+       }
+
+       if ((prop = xml_note->property("time")) != 0) {
+               istringstream time_str(prop->value());
+               time_str >> time;
+       } else {
+               warning << "note information missing time" << endmsg;
+               time = 0;
+       }
+
+       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;
        }
 
-       _write_notes.clear();
-       _writing = false;
-       write_unlock();
+       boost::shared_ptr< Evoral::Note<TimeType> > note_ptr(new Evoral::Note<TimeType>(
+                       channel, time, length, note, velocity));
+       return note_ptr;
 }
 
+#define ADDED_NOTES_ELEMENT "AddedNotes"
+#define REMOVED_NOTES_ELEMENT "RemovedNotes"
+#define DELTA_COMMAND_ELEMENT "DeltaCommand"
 
-/** Append contents of \a buf 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.
- *
- * Events in buf are deep copied.
- */
-void
-MidiModel::append(const MidiBuffer& buf)
-{ 
-       write_lock();
+int
+MidiModel::DeltaCommand::set_state (const XMLNode& delta_command, int /*version*/)
+{
+       if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
+               return 1;
+       }
 
-       assert(_writing);
+       _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),
+                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
+       }
 
-       for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
-               assert(_notes.empty() || (*i).time() >= _notes.back().time());
-               append(*i);
+       _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),
+                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
        }
-       
-       write_unlock();
+
+       return 0;
 }
 
+XMLNode&
+MidiModel::DeltaCommand::get_state()
+{
+       XMLNode* delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
+       delta_command->add_property("midi-source", _model->midi_source()->id().to_s());
 
-/** 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)
+       XMLNode* added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
+       for_each(_added_notes.begin(), _added_notes.end(), sigc::compose(
+                       sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
+                       sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
+
+       XMLNode* removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
+       for_each(_removed_notes.begin(), _removed_notes.end(), sigc::compose(
+                       sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
+                       sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
+
+       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)
 {
-       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();
+       assert(_model);
 }
 
+MidiModel::DiffCommand::DiffCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
+       : _model(m)
+{
+       assert(_model);
+       set_state(node, Stateful::loading_state_version);
+}
 
 void
-MidiModel::append_note_on_unlocked(double time, uint8_t note_num, uint8_t velocity)
+MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
+                              uint8_t new_value)
 {
-       //cerr << "MidiModel " << this << " note " << (int)note_num << " on @ " << time << endl;
-
-       assert(_writing);
-       _notes.push_back(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;
+       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;
        }
+
+       _changes.push_back (change);
 }
 
+void
+MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
+                              TimeType new_time)
+{
+       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_off_unlocked(double time, uint8_t note_num)
+MidiModel::DiffCommand::operator()()
 {
-       //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];
-               //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->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_cc_unlocked(double time, uint8_t number, uint8_t value)
+MidiModel::DiffCommand::undo()
 {
-       Parameter param(MidiCCAutomation, number);
+       MidiModel::WriteLock lock(_model->edit_lock());
 
-       //cerr << "MidiModel " << this << " add CC " << (int)number << " = " << (int)value
-       //      << " @ " << time << endl;
-       
-       boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
-       control->list()->fast_simple_add(time, (double)value);
-}
+       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::add_note_unlocked(const Note& note)
+XMLNode&
+MidiModel::DiffCommand::marshal_change(const NotePropertyChange& change)
 {
-       //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);
-}
+       XMLNode* xml_change = new XMLNode("change");
 
+       /* first, the change itself */
 
-void
-MidiModel::remove_note_unlocked(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);
-}
+       xml_change->add_property ("property", enum_2_string (change.property));
 
-/** 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();
+       {
+               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());
+       }
 
-       return true;
+       {
+               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());
+       }
+
+       /* now the rest of the note */
+
+       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 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 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
-       
-       _model.write_lock();
-       
-       for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
-               _model.add_note_unlocked(*i);
-       
-       for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
-               _model.remove_note_unlocked(*i);
-       
-       _model.write_unlock();
-       
-       _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
-       
-       _model.write_lock();
-
-       for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
-               _model.remove_note_unlocked(*i);
-       
-       for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
-               _model.add_note_unlocked(*i);
-       
-       _model.write_unlock();
-       
-       _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),
+                          sigc::mem_fun(*this, &DiffCommand::unmarshal_change));
+       }
+
+       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(), sigc::compose(
+                        sigc::mem_fun(*changes, &XMLNode::add_child_nocopy),
+                        sigc::mem_fun(*this, &DiffCommand::marshal_change)));
 
+       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 Note* const 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;
 }
@@ -540,3 +709,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));
+}