Remove unnecessary 0 checks before delete; see http://www.parashift.com/c++-faq-lite...
[ardour.git] / libs / ardour / midi_model.cc
index 1c6990e84df0a4816f3827842b33fc60cbc2537a..c1d53a25539d9247852e2de6d19f9bc79940e24c 100644 (file)
 /*
   Copyright (C) 2007 Paul Davis 
      Written by Dave Robillard, 2007
+ Copyright (C) 2007 Paul Davis 
+ Written by Dave Robillard, 2007
 
   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
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
+ 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
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
 
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
 
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
-*/
+ */
+
+#define __STDC_LIMIT_MACROS 1
 
 #include <iostream>
+#include <algorithm>
+#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_events.h>
+#include <ardour/midi_source.h>
 #include <ardour/types.h>
 #include <ardour/session.h>
 
 using namespace std;
 using namespace ARDOUR;
+using namespace PBD;
 
-
-MidiModel::MidiModel(Session& s, size_t size)
-       : _session(s)
-       , _notes(size)
-       , _command(NULL)
+MidiModel::MidiModel(MidiSource *s, size_t size)
+       : AutomatableSequence(s->session(), size)
+       , _midi_source(s)
 {
+       cerr << "MidiModel \"" << s->name() << "\" constructed: " << this << endl;
 }
 
-
-/** Begin a write of events to the model.
+/** Start a new command.
  *
- * As note on and off events are written, complete notes with duration are
- * constructed
+ * 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.
  */
-void
-MidiModel::start_write()
+MidiModel::DeltaCommand* MidiModel::new_delta_command(const string name)
 {
-       _write_notes.clear();
+       DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
+       return cmd;
 }
 
-
-
-/** Finish a write of events to the model.
+/** Apply a command.
  *
- * If \a delete_stuck is true, note on events that were never resolved with
- * a corresonding note off will be deleted.  Otherwise they will remain as
- * notes with duration 0.
+ * 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::end_write(bool delete_stuck)
+MidiModel::apply_command(Session& session, Command* cmd)
 {
-       if (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;
-                       }
-               }
-       }
-
-       _write_notes.clear();
+       session.begin_reversible_command(cmd->name());
+       (*cmd)();
+       assert(is_sorted());
+       session.commit_reversible_command(cmd);
+       set_edited(true);
 }
 
 
-/** 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)
-{ 
-       for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
-               const MidiEvent& ev = *i;
-               
-               assert(_notes.empty() || ev.time >= _notes.back().start);
+// DeltaCommand
 
-               if (ev.type() == MIDI_CMD_NOTE_ON)
-                       append_note_on(ev.time, ev.note(), ev.velocity());
-               else if (ev.type() == MIDI_CMD_NOTE_OFF)
-                       append_note_off(ev.time, ev.note());
-       }
+MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
+               const std::string& name)
+       : Command(name)
+       , _model(m)
+       , _name(name)
+{
 }
 
-
-/** 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(double time, size_t size, const Byte* buf)
+MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
+               const XMLNode& node)
+       : _model(m)
 {
-       assert(_notes.empty() || time >= _notes.back().start);
-
-       if ((buf[0] & 0xF0) == MIDI_CMD_NOTE_ON)
-               append_note_on(time, buf[1], buf[2]);
-       else if ((buf[0] & 0xF0) == MIDI_CMD_NOTE_OFF)
-               append_note_off(time, buf[1]);
+       set_state(node);
 }
 
-
 void
-MidiModel::append_note_on(double time, uint8_t note_num, uint8_t velocity)
+MidiModel::DeltaCommand::add(const boost::shared_ptr<Evoral::Note> note)
 {
-       _notes.push_back(Note(time, 0, note_num, velocity));
-       _write_notes.push_back(_notes.size() - 1);
+       //cerr << "MEC: apply" << endl;
+       _removed_notes.remove(note);
+       _added_notes.push_back(note);
 }
 
-
 void
-MidiModel::append_note_off(double time, uint8_t note_num)
+MidiModel::DeltaCommand::remove(const boost::shared_ptr<Evoral::Note> note)
 {
-       /* _write_notes (active notes) is presumably small enough for linear
-        * search to be a good idea.  maybe not with instruments (percussion)
-        * that don't send note off at all though.... FIXME? */
-
-       /* 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];
-               if (note.note == note_num) {
-                       assert(time > note.start);
-                       note.duration = time - note.start;
-                       _write_notes.erase(n);
-                       //cerr << "MidiModel resolved note, duration: " << note.duration << endl;
-                       break;
-               }
-       }
+       //cerr << "MEC: remove" << endl;
+       _added_notes.remove(note);
+       _removed_notes.push_back(note);
 }
 
-
 void
-MidiModel::add_note(const Note& note)
+MidiModel::DeltaCommand::operator()()
 {
-       Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
-       _notes.insert(i, note);
-       if (_command)
-               _command->add_note(note);
-}
+       // 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();
+
+       // Store the current seek position so we can restore the read iterator
+       // after modifying the contents of the model
+       const double read_time = _model->read_time();
+
+       for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
+               _model->add_note_unlocked(*i);
+
+       for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
+               _model->remove_note_unlocked(*i);
+
+       _model->write_unlock();
+       // FIXME: race?
+       _model->read_seek(read_time); // restore read position
 
+       _model->ContentsChanged(); /* EMIT SIGNAL */
+}
 
 void
-MidiModel::remove_note(const Note& note)
+MidiModel::DeltaCommand::undo()
 {
-       Notes::iterator n = find(_notes.begin(), _notes.end(), note);
-       if (n != _notes.end())
-               _notes.erase(n);
+       // 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
        
-       if (_command)
-               _command->remove_note(note);
-}
+       _model->write_lock();
 
+       // Store the current seek position so we can restore the read iterator
+       // after modifying the contents of the model
+       const double read_time = _model->read_time();
 
+       for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
+               _model->remove_note_unlocked(*i);
 
-void
-MidiModel::begin_command()
-{
-       assert(!_command);
-       _session.begin_reversible_command("midi edit");
-       _command = new MidiEditCommand(*this);
-}
+       for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
+               _model->add_note_unlocked(*i);
 
+       _model->write_unlock();
+       // FIXME: race?
+       _model->read_seek(read_time); // restore read position
 
-void
-MidiModel::finish_command()
-{
-       _session.commit_reversible_command(_command);
-       _command = NULL;
+       _model->ContentsChanged(); /* EMIT SIGNAL */
 }
 
+XMLNode&
+MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Evoral::Note> note)
+{
+       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());
 
-// MidiEditCommand
+       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());
 
-void
-MidiModel::MidiEditCommand::add_note(const Note& note)
+       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::DeltaCommand::unmarshal_note(XMLNode *xml_note)
 {
-       //cerr << "MEC: apply" << endl;
+       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;
+       }
 
-       _removed_notes.remove(note);
-       _added_notes.push_back(note);
+       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;
+               note = 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;
+       }
+
+       boost::shared_ptr<Evoral::Note> note_ptr(new Evoral::Note(channel, time, length, note, velocity));
+       return note_ptr;
 }
 
+#define ADDED_NOTES_ELEMENT "added_notes"
+#define REMOVED_NOTES_ELEMENT "removed_notes"
+#define DELTA_COMMAND_ELEMENT "DeltaCommand"
 
-void
-MidiModel::MidiEditCommand::remove_note(const Note& note)
+int MidiModel::DeltaCommand::set_state(const XMLNode& delta_command)
 {
-       //cerr << "MEC: remove" << endl;
+       if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
+               return 1;
+       }
 
-       _added_notes.remove(note);
-       _removed_notes.push_back(note);
+       _added_notes.clear();
+       XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
+       XMLNodeList notes = added_notes->children();
+       transform(notes.begin(), notes.end(), back_inserter(_added_notes),
+                       sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
+
+       _removed_notes.clear();
+       XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
+       notes = removed_notes->children();
+       transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
+                       sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
+
+       return 0;
 }
 
-               
-void 
-MidiModel::MidiEditCommand::operator()()
+XMLNode& MidiModel::DeltaCommand::get_state()
 {
-       //cerr << "MEC: apply" << endl;
-       assert(!_model.current_command());
-       
-       for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
-               _model.add_note(*i);
-       
-       for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
-               _model.remove_note(*i);
+       XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
+       delta_command->add_property("midi-source", _model->midi_source()->id().to_s());
 
-       _model.ContentsChanged(); /* EMIT SIGNAL */
-}
+       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)));
 
-void
-MidiModel::MidiEditCommand::undo()
+       return *delta_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 << "MEC: undo" << endl;
-       assert(!_model.current_command());
+       read_lock();
 
-       for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
-               _model.remove_note(*i);
+       const bool old_percussive = percussive();
+       set_percussive(false);
        
-       for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
-               _model.add_note(*i);
+       for (Evoral::Sequence::const_iterator i = begin(); i != end(); ++i) {
+               source->append_event_unlocked(Frames, *i);
+       }
+               
+       set_percussive(old_percussive);
        
-       _model.ContentsChanged(); /* EMIT SIGNAL */
+       read_unlock();
+       set_edited(false);
+
+       return true;
+}
+
+XMLNode& MidiModel::get_state()
+{
+       XMLNode *node = new XMLNode("MidiModel");
+       return *node;
 }