X-Git-Url: https://main.carlh.net/gitweb/?a=blobdiff_plain;f=libs%2Fardour%2Fmidi_model.cc;h=baa3c2c7c016d4c54b408de7cf38e48c6d78e126;hb=405def9215a2fc7b70dd2999a06d16e704ddd058;hp=43ac4b0f960ae471deb695be7291bce0b9d1331b;hpb=f39606f985223d211d218799c9e0de1e7c0e7f0c;p=ardour.git diff --git a/libs/ardour/midi_model.cc b/libs/ardour/midi_model.cc index 43ac4b0f96..baa3c2c7c0 100644 --- a/libs/ardour/midi_model.cc +++ b/libs/ardour/midi_model.cc @@ -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 @@ -24,698 +24,683 @@ #include #include #include -#include -#include +#include "pbd/error.h" +#include "pbd/enumwriter.h" +#include "midi++/events.h" -#include -#include -#include -#include +#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; - -void -MidiModel::write_lock() -{ - _lock.writer_lock(); - _automation_lock.lock(); +MidiModel::MidiModel(MidiSource* s, size_t size) + : AutomatableSequence(s->session(), size) + , _midi_source(s) +{ } -void -MidiModel::write_unlock() -{ - _lock.writer_unlock(); - _automation_lock.unlock(); +/** 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; } -void -MidiModel::read_lock() const -{ - _lock.reader_lock(); - /*_automation_lock.lock();*/ +/** 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; } -void -MidiModel::read_unlock() const -{ - _lock.reader_unlock(); - /*_automation_lock.unlock();*/ +/** 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); } -// Read iterator (const_iterator) - -MidiModel::const_iterator::const_iterator(const MidiModel& model, double t) - : _model(&model) - , _is_end( (t == DBL_MAX) || model.empty()) - , _locked( ! _is_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) { - //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl; - - if (_is_end) - return; - - model.read_lock(); - - _note_iter = model.notes().end(); - // find first note which begins after t - 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(), - 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; - } - } + (*cmd)(); + session.add_command(cmd); + set_edited(true); +} - if (_note_iter != model.notes().end()) { - _event = MIDI::Event((*_note_iter)->on_event(), false); - _active_notes.push(*_note_iter); - cerr << " new const iterator: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl; - ++_note_iter; - } - if (earliest_control.first && earliest_control.second.first < _event.time()) - model.control_to_midi_event(_event, earliest_control); - else - _control_iter = _control_iters.end(); +// DeltaCommand - if (_event.size() == 0) { - //cerr << "Created MIDI iterator @ " << t << " is at end." << endl; - _is_end = true; - if(_locked) { - _model->read_unlock(); - _locked = false; - } - } else { - printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time()); -} +MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr m, const std::string& name) + : Command(name) + , _model(m) + , _name(name) +{ + assert(_model); } +MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr 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 > note) { - if (_locked) { - _model->read_unlock(); + _removed_notes.remove(note); + _added_notes.push_back(note); } + +void +MidiModel::DeltaCommand::remove(const boost::shared_ptr< Evoral::Note > note) +{ + _added_notes.remove(note); + _removed_notes.push_back(note); } - -const MidiModel::const_iterator& -MidiModel::const_iterator::operator++() +void +MidiModel::DeltaCommand::operator()() { - if (_is_end) - throw std::logic_error("Attempt to iterate past end of MidiModel"); + // 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 - assert(_event.is_note() || _event.is_cc()); + MidiModel::WriteLock lock(_model->edit_lock()); - // 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); + for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) { + _model->add_note_unlocked(*i); + } - 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 = _removed_notes.begin(); i != _removed_notes.end(); ++i) { + _model->remove_note_unlocked(*i); } - // Now find and point at the earliest event + lock.reset(); + _model->ContentsChanged(); /* EMIT SIGNAL */ +} - _control_iter = _control_iters.begin(); +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 - for (std::vector::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(); - } - - cerr << " operator++ before test: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl; - // 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 = MIDI::Event((*_note_iter)->on_event(), false); - _active_notes.push(*_note_iter); - ++_note_iter; - } else if (type == NOTE_OFF) { - cerr << "********** MIDI Iterator = note off" << endl; - _event = MIDI::Event(_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; + 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 > 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; - _active_notes = other._active_notes; - _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()); - - 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, nframes_t negative_stamp_offset) const -{ - cerr << this << " MM::read @ " << start << " frames: " << 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::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; } - _next_read = start + nframes; + if ((prop = xml_note->property("channel")) != 0) { + istringstream channel_str(prop->value()); + channel_str >> channel; + } else { + warning << "note information missing channel" << endmsg; + channel = 0; + } - while (_read_iter != end() && _read_iter->time() < start + nframes) { - assert(_read_iter->size() > 0); - dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset, _read_iter->size(), _read_iter->buffer()); - cerr << this << " MM::read event @ " << _read_iter->time() - << " type: " << hex << int(_read_iter->type()) << dec - << " note: " << int(_read_iter->note()) - << " velocity: " << int(_read_iter->velocity()) - << endl; - ++_read_iter; - ++read_events; + if ((prop = xml_note->property("time")) != 0) { + istringstream time_str(prop->value()); + time_str >> time; + } else { + warning << "note information missing time" << endmsg; + time = 0; } - return 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; + } -bool -MidiModel::control_to_midi_event(MIDI::Event& ev, const MidiControlIterator& iter) const -{ - if (iter.first->parameter().type() == MidiCCAutomation) { - if (ev.size() < 3) - ev.set_buffer((Byte*)malloc(3), true); - - assert(iter.first); - assert(iter.first->parameter().channel() < 16); - assert(iter.first->parameter().id() <= INT8_MAX); - assert(iter.second.second <= INT8_MAX); - ev.buffer()[0] = MIDI_CMD_CONTROL + iter.first->parameter().channel(); - 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; + if ((prop = xml_note->property("velocity")) != 0) { + istringstream velocity_str(prop->value()); + velocity_str >> velocity; } else { - return false; + warning << "note information missing velocity" << endmsg; + velocity = 127; } -} - -/** 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() -{ - //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl; - write_lock(); - _writing = true; - for (int i = 0; i < 16; ++i) - _write_notes[i].clear(); - write_unlock(); + boost::shared_ptr< Evoral::Note > note_ptr(new Evoral::Note( + channel, time, length, note, velocity)); + return note_ptr; } +#define ADDED_NOTES_ELEMENT "AddedNotes" +#define REMOVED_NOTES_ELEMENT "RemovedNotes" +#define DELTA_COMMAND_ELEMENT "DeltaCommand" - -/** 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) +int +MidiModel::DeltaCommand::set_state (const XMLNode& delta_command, int /*version*/) { - 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; - } - } + if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) { + return 1; } - for (int i = 0; i < 16; ++i) { - if (!_write_notes[i].empty()) { - cerr << "WARNING: MidiModel::end_write: Channel " << i << " has " - << _write_notes[i].size() << " stuck notes" << endl; - } - _write_notes[i].clear(); + _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)); } - - _writing = false; - write_unlock(); -} + _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)); + } -/** 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 MIDI::Event& ev) + return 0; +} + +XMLNode& +MidiModel::DeltaCommand::get_state() { - write_lock(); - - assert(_notes.empty() || ev.time() >= _notes.back()->time()); - assert(_writing); - - if (ev.is_note_on()) - append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity()); - else if (ev.is_note_off()) - append_note_off_unlocked(ev.channel(), ev.time(), ev.note()); - else if (ev.is_cc()) - append_cc_unlocked(ev.channel(), ev.time(), ev.cc_number(), ev.cc_value()); - else - printf("MM Unknown event type %X\n", ev.type()); - - 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 ********************/ -void -MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity) +#define DIFF_NOTES_ELEMENT "ChangedNotes" +#define DIFF_COMMAND_ELEMENT "DiffCommand" + +MidiModel::DiffCommand::DiffCommand(boost::shared_ptr m, const std::string& name) + : Command(name) + , _model(m) + , _name(name) { - /*cerr << "MidiModel " << this << " chan " << (int)chan << - " note " << (int)note_num << " on @ " << time << endl;*/ - - assert(chan < 16); - assert(_writing); - - _notes.push_back(boost::shared_ptr(new Note(chan, time, 0, note_num, velocity))); - if (_note_mode == Sustained) { - //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl; - _write_notes[chan].push_back(_notes.size() - 1); - }/* else { - cerr << "MM Percussive: NOT appending active note on" << endl; - }*/ + assert(_model); } +MidiModel::DiffCommand::DiffCommand(boost::shared_ptr m, const XMLNode& node) + : _model(m) +{ + assert(_model); + set_state(node, Stateful::loading_state_version); +} void -MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num) +MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note > note, Property prop, + uint8_t new_value) { - /*cerr << "MidiModel " << this << " chan " << (int)chan << - " note " << (int)note_num << " off @ " << time << 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; + } - assert(chan < 16); - assert(_writing); + _changes.push_back (change); +} - if (_note_mode == Percussive) { - cerr << "MidiModel Ignoring note off (percussive mode)" << endl; - return; +void +MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note > 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; } - /* 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 */ + _changes.push_back (change); +} - bool resolved = false; +void +MidiModel::DiffCommand::operator()() +{ + MidiModel::WriteLock lock(_model->edit_lock()); - for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].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[chan].erase(n); - //cerr << "MM resolved note, duration: " << note.duration() << endl; - resolved = true; + 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; } } - if (!resolved) - cerr << "MidiModel " << this << " spurious note off chan " << (int)chan - << ", note " << (int)note_num << " @ " << time << endl; + lock.reset(); + _model->ContentsChanged(); /* EMIT SIGNAL */ } - void -MidiModel::append_cc_unlocked(uint8_t chan, double time, uint8_t number, uint8_t value) +MidiModel::DiffCommand::undo() { - /*cerr << "MidiModel " << this << " chan " << (int)chan << - " CC " << (int)number << " = " << (int)value << " @ " << time << endl;*/ - - assert(chan < 16); - assert(_writing); - - Parameter param(MidiCCAutomation, number, chan); - - boost::shared_ptr control = Automatable::control(param, true); - control->list()->fast_simple_add(time, (double)value); -} + MidiModel::WriteLock lock(_model->edit_lock()); + + 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 boost::shared_ptr 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 boost::shared_ptr 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 (_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) -{ - //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 > new_note (new Evoral::Note (channel, time, length, note, velocity)); -void -MidiModel::DeltaCommand::remove(const boost::shared_ptr 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 >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) - _model.add_note_unlocked(*i); - - for (std::list< boost::shared_ptr >::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 >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) - _model.remove_note_unlocked(*i); - - for (std::list< boost::shared_ptr >::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 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 MIDI::Event& 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 earliest_off = active_notes.top(); - const MIDI::Event& off_ev = earliest_off->off_event(); - if (off_ev.time() <= (*n)->time()) { - source->append_event_unlocked(Frames, off_ev); - active_notes.pop(); - } else { - break; - } - } + ReadLock lock(read_lock()); - // Write this note on - source->append_event_unlocked(Frames, (*n)->on_event()); - if ((*n)->duration() > 0) - active_notes.push(*n); - } - - // Write any trailing note offs - while ( ! active_notes.empty() ) { - source->append_event_unlocked(Frames, 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::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; } @@ -727,3 +712,39 @@ MidiModel::get_state() return *node; } +boost::shared_ptr > +MidiModel::find_note (boost::shared_ptr > 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 >(); +} + +/** 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)); +}