* persistent undo for MIDI edits works now
[ardour.git] / libs / ardour / midi_model.cc
1 /*
2     Copyright (C) 2007 Paul Davis 
3         Written by Dave Robillard, 2007
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #define __STDC_LIMIT_MACROS 1
22
23 #include <iostream>
24 #include <algorithm>
25 #include <stdexcept>
26 #include <stdint.h>
27 #include <pbd/enumwriter.h>
28 #include <midi++/events.h>
29
30 #include <ardour/midi_model.h>
31 #include <ardour/midi_source.h>
32 #include <ardour/types.h>
33 #include <ardour/session.h>
34
35 using namespace std;
36 using namespace ARDOUR;
37
38
39 void 
40 MidiModel::write_lock()        
41
42         _lock.writer_lock(); 
43         _automation_lock.lock(); 
44 }
45
46 void 
47 MidiModel::write_unlock()      
48
49         _lock.writer_unlock(); 
50         _automation_lock.unlock(); 
51 }
52
53 void 
54 MidiModel::read_lock()   const 
55
56         _lock.reader_lock(); 
57         /*_automation_lock.lock();*/ 
58 }
59
60 void 
61 MidiModel::read_unlock() const 
62
63         _lock.reader_unlock(); 
64         /*_automation_lock.unlock();*/ 
65 }
66
67 // Read iterator (const_iterator)
68
69 MidiModel::const_iterator::const_iterator(const MidiModel& model, double t)
70         : _model(&model)
71         , _is_end( (t == DBL_MAX) || model.empty())
72         , _locked( ! _is_end)
73 {
74         //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl;
75         
76         if (_is_end)
77                 return;
78
79         model.read_lock();
80         
81         _note_iter = model.notes().end();
82         // find first note which begins after t
83         for (MidiModel::Notes::const_iterator i = model.notes().begin(); i != model.notes().end(); ++i) {
84                 if ((*i)->time() >= t) {
85                         _note_iter = i;
86                         break;
87                 }
88         }
89                         
90         MidiControlIterator earliest_control = make_pair(boost::shared_ptr<AutomationList>(),
91                         make_pair(DBL_MAX, 0.0));
92
93         _control_iters.reserve(model.controls().size());
94         for (Automatable::Controls::const_iterator i = model.controls().begin();
95                         i != model.controls().end(); ++i) {
96
97                 assert(i->first.type() == MidiCCAutomation);
98
99                 double x, y;
100                 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
101                 if (!ret) {
102                         /*cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
103                                 << ") has no events past " << t << endl;*/
104                         continue;
105                 } 
106
107                 assert(x >= 0);
108                 assert(y >= 0);
109                 assert(y <= UINT8_MAX);
110                 
111                 const MidiControlIterator new_iter = make_pair(i->second->list(), make_pair(x, y));
112                 
113                 //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
114                 _control_iters.push_back(new_iter);
115
116                 if (x < earliest_control.second.first) {
117                         earliest_control = new_iter;
118                         _control_iter = _control_iters.end();
119                         --_control_iter;
120                 }
121         }
122
123         if (_note_iter != model.notes().end()) {
124                 _event = MIDI::Event((*_note_iter)->on_event(), false);
125                 _active_notes.push(*_note_iter);
126                 cerr << " new const iterator: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl;
127                 ++_note_iter;
128         }
129
130         if (earliest_control.first && earliest_control.second.first < _event.time())
131                 model.control_to_midi_event(_event, earliest_control);
132         else
133                 _control_iter = _control_iters.end();
134
135         if (_event.size() == 0) {
136                 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
137                 _is_end = true;
138                 if(_locked) {
139                 _model->read_unlock();
140                 _locked = false;
141                 }
142         } else {
143                 printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
144 }
145 }
146
147
148 MidiModel::const_iterator::~const_iterator()
149 {
150         if (_locked) {
151                 _model->read_unlock();
152 }
153 }
154                 
155
156 const MidiModel::const_iterator&
157 MidiModel::const_iterator::operator++()
158 {
159         if (_is_end)
160                 throw std::logic_error("Attempt to iterate past end of MidiModel");
161
162         assert(_event.is_note() || _event.is_cc());
163
164         // Increment past current control event
165         if (_control_iter != _control_iters.end() && _control_iter->first && _event.is_cc()) {
166                 double x, y;
167                 const bool ret = _control_iter->first->rt_safe_earliest_event_unlocked(
168                                 _control_iter->second.first, DBL_MAX, x, y, false);
169
170                 if (ret) {
171                         //cerr << "Incremented " << _control_iter->first->parameter().id() << " to " << x << endl;
172                         _control_iter->second.first = x;
173                         _control_iter->second.second = y;
174                 } else {
175                         //cerr << "Hit end of " << _control_iter->first->parameter().id() << endl;
176                         _control_iter->first.reset();
177                         _control_iter->second.first = DBL_MAX;
178                 }
179         }
180
181         // Now find and point at the earliest event
182
183         _control_iter = _control_iters.begin();
184
185         for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
186                         i != _control_iters.end(); ++i) {
187                 if (i->second.first < _control_iter->second.first) {
188                         _control_iter = i;
189                 }
190         }
191         
192         enum Type { NIL, NOTE_ON, NOTE_OFF, CC };
193         
194         Type   type = NIL;
195         double t    = 0;
196
197         // Next earliest note on
198         if (_note_iter != _model->notes().end()) {
199                 type = NOTE_ON;
200                 t = (*_note_iter)->time();
201         }
202         
203         cerr << " operator++ before test: size active notes: " << _active_notes.size() << " is empty: " << _active_notes.empty() << endl;
204         // Use the next earliest note off iff it's earlier than the note on
205         if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
206                 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
207                         type = NOTE_OFF;
208                         t = _active_notes.top()->end_time();
209                 }
210         }
211         
212         // Use the next earliest controller iff it's earlier than the note event
213         if (_control_iter != _control_iters.end() && _control_iter->second.first != DBL_MAX)
214                 if (type == NIL || _control_iter->second.first < t)
215                         type = CC;
216
217         if (type == NOTE_ON) {
218                 cerr << "********** MIDI Iterator = note on" << endl;
219                 _event = MIDI::Event((*_note_iter)->on_event(), false);
220                 _active_notes.push(*_note_iter);
221                 ++_note_iter;
222         } else if (type == NOTE_OFF) {
223                 cerr << "********** MIDI Iterator = note off" << endl;
224                 _event = MIDI::Event(_active_notes.top()->off_event(), false);
225                 _active_notes.pop();
226         } else if (type == CC) {
227                 cerr << "********** MIDI Iterator = CC" << endl;
228                 _model->control_to_midi_event(_event, *_control_iter);
229         } else {
230                 cerr << "********** MIDI Iterator = END" << endl;
231                 _is_end = true;
232         }
233
234         assert(_is_end || _event.size() > 0);
235
236         return *this;
237 }
238                 
239
240 bool
241 MidiModel::const_iterator::operator==(const const_iterator& other) const
242 {
243         if (_is_end || other._is_end)
244                 return (_is_end == other._is_end);
245         else
246                 return (_event == other._event);
247 }
248                 
249
250 MidiModel::const_iterator&
251 MidiModel::const_iterator::operator=(const const_iterator& other)
252 {
253         if (_locked && _model != other._model)
254                 _model->read_unlock();
255
256         assert( ! other._event.owns_buffer());
257
258         _model = other._model;
259         _event = other._event;
260         _active_notes = other._active_notes;
261         _is_end = other._is_end;
262         _locked = other._locked;
263         _note_iter = other._note_iter;
264         _control_iters = other._control_iters;
265         _control_iter = other._control_iter;
266         
267         assert( ! _event.owns_buffer());
268         
269         return *this;
270 }
271
272         
273 // MidiModel
274
275 MidiModel::MidiModel(MidiSource *s, size_t size)
276         : Automatable(s->session(), "midi model")
277         , _notes(size)
278         , _note_mode(Sustained)
279         , _writing(false)
280         , _edited(false)
281         , _end_iter(*this, DBL_MAX)
282         , _next_read(UINT32_MAX)
283         , _read_iter(*this, DBL_MAX)
284         , _midi_source(s)
285 {
286         assert(_end_iter._is_end);
287         assert( ! _end_iter._locked);
288 }
289
290 /** Read events in frame range \a start .. \a start+cnt into \a dst,
291  * adding \a stamp_offset to each event's timestamp.
292  * \return number of events written to \a dst
293  */
294 size_t
295 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset, nframes_t negative_stamp_offset) const
296 {
297         cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
298         cerr << this << " MM # notes: " << n_notes() << endl;
299
300         size_t read_events = 0;
301
302         if (start != _next_read) {
303                 _read_iter = const_iterator(*this, (double)start);
304                 cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
305         } else {
306                 cerr << "Using cached iterator at " << _next_read << endl;
307         }
308
309         _next_read = start + nframes;
310
311         while (_read_iter != end() && _read_iter->time() < start + nframes) {
312                 assert(_read_iter->size() > 0);
313                 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset, _read_iter->size(), _read_iter->buffer());
314                 cerr << this << " MM::read event @ " << _read_iter->time()  
315                      << " type: " << hex << int(_read_iter->type()) << dec 
316                      << " note: " << int(_read_iter->note()) 
317                      << " velocity: " << int(_read_iter->velocity()) 
318                      << endl;
319                 ++_read_iter;
320                 ++read_events;
321         }
322
323         return read_events;
324 }
325         
326
327 bool
328 MidiModel::control_to_midi_event(MIDI::Event& ev, const MidiControlIterator& iter) const
329 {
330         if (iter.first->parameter().type() == MidiCCAutomation) {
331                 if (ev.size() < 3)
332                         ev.set_buffer((Byte*)malloc(3), true);
333
334                 assert(iter.first);
335                 assert(iter.first->parameter().channel() < 16);
336                 assert(iter.first->parameter().id() <= INT8_MAX);
337                 assert(iter.second.second <= INT8_MAX);
338                 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.first->parameter().channel();
339                 ev.buffer()[1] = (Byte)iter.first->parameter().id();
340                 ev.buffer()[2] = (Byte)iter.second.second;
341                 ev.time() = iter.second.first; // x
342                 ev.size() = 3;
343                 return true;
344         } else {
345                 return false;
346         }
347 }
348
349         
350 /** Begin a write of events to the model.
351  *
352  * If \a mode is Sustained, complete notes with duration are constructed as note
353  * on/off events are received.  Otherwise (Percussive), only note on events are
354  * stored; note off events are discarded entirely and all contained notes will
355  * have duration 0.
356  */
357 void
358 MidiModel::start_write()
359 {
360         //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
361         write_lock();
362         _writing = true;
363         for (int i = 0; i < 16; ++i)
364                 _write_notes[i].clear();
365         write_unlock();
366 }
367
368
369
370 /** Finish a write of events to the model.
371  *
372  * If \a delete_stuck is true and the current mode is Sustained, note on events
373  * that were never resolved with a corresonding note off will be deleted.
374  * Otherwise they will remain as notes with duration 0.
375  */
376 void
377 MidiModel::end_write(bool delete_stuck)
378 {
379         write_lock();
380         assert(_writing);
381         
382         //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
383
384         if (_note_mode == Sustained && delete_stuck) {
385                 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
386                         if ((*n)->duration() == 0) {
387                                 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
388                                 n = _notes.erase(n);
389                         } else {
390                                 ++n;
391                         }
392                 }
393         }
394
395         for (int i = 0; i < 16; ++i) {
396                 if (!_write_notes[i].empty()) {
397                         cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
398                                         << _write_notes[i].size() << " stuck notes" << endl;
399                 }
400                 _write_notes[i].clear();
401         }
402         
403         _writing = false;
404         write_unlock();
405 }
406
407
408 /** Append \a in_event to model.  NOT realtime safe.
409  *
410  * Timestamps of events in \a buf are expected to be relative to
411  * the start of this model (t=0) and MUST be monotonically increasing
412  * and MUST be >= the latest event currently in the model.
413  */
414 void
415 MidiModel::append(const MIDI::Event& ev)
416 {
417         write_lock();
418
419         assert(_notes.empty() || ev.time() >= _notes.back()->time());
420         assert(_writing);
421
422         if (ev.is_note_on())
423                 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
424         else if (ev.is_note_off())
425                 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
426         else if (ev.is_cc())
427                 append_cc_unlocked(ev.channel(), ev.time(), ev.cc_number(), ev.cc_value());
428         else
429                 printf("MM Unknown event type %X\n", ev.type());
430         
431         write_unlock();
432 }
433
434
435 void
436 MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity)
437 {
438         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
439                         " note " << (int)note_num << " on @ " << time << endl;*/
440
441         assert(chan < 16);
442         assert(_writing);
443
444         _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
445         if (_note_mode == Sustained) {
446                 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
447                 _write_notes[chan].push_back(_notes.size() - 1);
448         }/* else {
449                 cerr << "MM Percussive: NOT appending active note on" << endl;
450         }*/
451 }
452
453
454 void
455 MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num)
456 {
457         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
458                         " note " << (int)note_num << " off @ " << time << endl;*/
459
460         assert(chan < 16);
461         assert(_writing);
462
463         if (_note_mode == Percussive) {
464                 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
465                 return;
466         }
467
468         /* FIXME: make _write_notes fixed size (127 noted) for speed */
469         
470         /* FIXME: note off velocity for that one guy out there who actually has
471          * keys that send it */
472
473         bool resolved = false;
474
475         for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].end(); ++n) {
476                 Note& note = *_notes[*n].get();
477                 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
478                 if (note.note() == note_num) {
479                         assert(time >= note.time());
480                         note.set_duration(time - note.time());
481                         _write_notes[chan].erase(n);
482                         //cerr << "MM resolved note, duration: " << note.duration() << endl;
483                         resolved = true;
484                         break;
485                 }
486         }
487
488         if (!resolved)
489                 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
490                         << ", note " << (int)note_num << " @ " << time << endl;
491 }
492
493
494 void
495 MidiModel::append_cc_unlocked(uint8_t chan, double time, uint8_t number, uint8_t value)
496 {
497         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
498                         " CC " << (int)number << " = " << (int)value << " @ " << time << endl;*/
499         
500         assert(chan < 16);
501         assert(_writing);
502         
503         Parameter param(MidiCCAutomation, number, chan);
504         
505         boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
506         control->list()->fast_simple_add(time, (double)value);
507 }
508
509
510 void
511 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
512 {
513         //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
514         Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
515         _notes.insert(i, note);
516 }
517
518
519 void
520 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
521 {
522         //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
523         for(Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
524                 if(**n == *note) {
525                         _notes.erase(n);
526                 }
527         }
528         
529 }
530
531 /** Slow!  for debugging only. */
532 #ifndef NDEBUG
533 bool
534 MidiModel::is_sorted() const
535 {
536         bool t = 0;
537         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
538                 if ((*n)->time() < t)
539                         return false;
540                 else
541                         t = (*n)->time();
542
543         return true;
544 }
545 #endif
546
547 /** Start a new command.
548  *
549  * This has no side-effects on the model or Session, the returned command
550  * can be held on to for as long as the caller wishes, or discarded without
551  * formality, until apply_command is called and ownership is taken.
552  */
553 MidiModel::DeltaCommand*
554 MidiModel::new_delta_command(const string name)
555 {
556         DeltaCommand* cmd =  new DeltaCommand(_midi_source->model(), name);
557         return cmd;
558 }
559
560
561 /** Apply a command.
562  *
563  * Ownership of cmd is taken, it must not be deleted by the caller.
564  * The command will constitute one item on the undo stack.
565  */
566 void
567 MidiModel::apply_command(Command* cmd)
568 {
569         _session.begin_reversible_command(cmd->name());
570         (*cmd)();
571         assert(is_sorted());
572         _session.commit_reversible_command(cmd);
573         _edited = true;
574 }
575
576
577 // MidiEditCommand
578
579 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
580         : Command(name), _model(m), _name(name) 
581 {
582         
583 }
584
585 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
586         : _model(m)
587 {
588         set_state(node);
589 }
590
591 void
592 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
593 {
594         //cerr << "MEC: apply" << endl;
595
596         _removed_notes.remove(note);
597         _added_notes.push_back(note);
598 }
599
600
601 void
602 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
603 {
604         //cerr << "MEC: remove" << endl;
605
606         _added_notes.remove(note);
607         _removed_notes.push_back(note);
608 }
609
610                 
611 void 
612 MidiModel::DeltaCommand::operator()()
613 {
614         // This could be made much faster by using a priority_queue for added and
615         // removed notes (or sort here), and doing a single iteration over _model
616         
617         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
618         const bool   reset_iter = (_model->_read_iter.locked());
619         const double iter_time  = _model->_read_iter->time();
620
621         if (reset_iter)
622                 _model->_read_iter = _model->end(); // drop read lock
623
624         assert( ! _model->_read_iter.locked());
625
626         _model->write_lock();
627         
628         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
629                 _model->add_note_unlocked(*i);
630         
631         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
632                 _model->remove_note_unlocked(*i);
633         
634         _model->write_unlock();
635
636         if (reset_iter)
637                 _model->_read_iter = const_iterator(*_model.get(), iter_time);
638         
639         _model->ContentsChanged(); /* EMIT SIGNAL */
640 }
641
642
643 void
644 MidiModel::DeltaCommand::undo()
645 {
646         // This could be made much faster by using a priority_queue for added and
647         // removed notes (or sort here), and doing a single iteration over _model
648         
649         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
650         const bool   reset_iter = (_model->_read_iter.locked());
651         const double iter_time  = _model->_read_iter->time();
652
653         if (reset_iter)
654                 _model->_read_iter = _model->end(); // drop read lock
655         
656         assert( ! _model->_read_iter.locked());
657
658         _model->write_lock();
659
660         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
661                 _model->remove_note_unlocked(*i);
662         
663         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
664                 _model->add_note_unlocked(*i);
665         
666         _model->write_unlock();
667         
668         if (reset_iter)
669                 _model->_read_iter = const_iterator(*_model.get(), iter_time);
670         
671         _model->ContentsChanged(); /* EMIT SIGNAL */
672 }
673
674 XMLNode &
675 MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Note> note)
676 {
677         XMLNode *xml_note = new XMLNode("note");
678         ostringstream note_str(ios::ate);
679         note_str << int(note->note());
680         xml_note->add_property("note", note_str.str());
681
682         ostringstream channel_str(ios::ate);
683         channel_str << int(note->channel());
684         xml_note->add_property("channel", channel_str.str());   
685         
686         ostringstream time_str(ios::ate);
687         time_str << int(note->time());
688         xml_note->add_property("time", time_str.str());
689
690         ostringstream duration_str(ios::ate);
691         duration_str <<(unsigned int) note->duration();
692         xml_note->add_property("duration", duration_str.str());
693
694         ostringstream velocity_str(ios::ate);
695         velocity_str << (unsigned int) note->velocity();
696         xml_note->add_property("velocity", velocity_str.str());
697         
698         return *xml_note;
699 }
700
701 boost::shared_ptr<Note> 
702 MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note) 
703 {
704         unsigned int note;
705         istringstream note_str(xml_note->property("note")->value());
706         note_str >> note;
707
708         unsigned int channel;
709         istringstream channel_str(xml_note->property("channel")->value());
710         channel_str >> channel;
711
712         unsigned int time;
713         istringstream time_str(xml_note->property("time")->value());
714         time_str >> time;
715
716         unsigned int duration;
717         istringstream duration_str(xml_note->property("duration")->value());
718         duration_str >> duration;
719
720         unsigned int velocity;
721         istringstream velocity_str(xml_note->property("velocity")->value());
722         velocity_str >> velocity;
723         
724         boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
725         return note_ptr;
726 }
727
728 #define ADDED_NOTES_ELEMENT "added_notes"
729 #define REMOVED_NOTES_ELEMENT "removed_notes"
730 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
731
732 int 
733 MidiModel::DeltaCommand::set_state (const XMLNode& delta_command)
734 {
735         if(delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
736                 return 1;
737         }
738         
739         _added_notes.clear();
740         XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
741         XMLNodeList notes = added_notes->children();
742         transform(notes.begin(), notes.end(), back_inserter(_added_notes), 
743                   sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
744         
745         _removed_notes.clear();
746         XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
747         notes = removed_notes->children();
748         transform(notes.begin(), notes.end(), back_inserter(_removed_notes), 
749                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
750         
751         return 0;
752 }
753
754 XMLNode& 
755 MidiModel::DeltaCommand::get_state () 
756 {
757         XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
758         delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
759         
760         XMLNode *added_notes   = delta_command->add_child(ADDED_NOTES_ELEMENT);
761         for_each(_added_notes.begin(), _added_notes.end(), 
762                 sigc::compose(sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
763                               sigc::mem_fun(*this, &DeltaCommand::marshal_note))); 
764         
765         XMLNode *removed_notes   = delta_command->add_child(REMOVED_NOTES_ELEMENT);
766         for_each(_removed_notes.begin(), _removed_notes.end(), 
767                 sigc::compose(sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
768                               sigc::mem_fun(*this, &DeltaCommand::marshal_note))); 
769
770         return *delta_command;
771 }
772
773
774 bool
775 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
776 {
777         //cerr << "Writing model to " << source->name() << endl;
778
779         /* This could be done using a temporary MidiRingBuffer and using
780          * MidiModel::read and MidiSource::write, but this is more efficient
781          * and doesn't require any buffer size assumptions (ie it's worth
782          * the code duplication).
783          *
784          * This is also different from read in that note off events are written
785          * regardless of the track mode.  This is so the user can switch a
786          * recorded track (with note durations from some instrument) to percussive,
787          * save, reload, then switch it back to sustained preserving the original
788          * note durations.
789          */
790
791         /* Percussive 
792         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
793                 const MIDI::Event& ev = n->on_event();
794                 source->append_event_unlocked(ev);
795         }*/
796
797         read_lock();
798
799         LaterNoteEndComparator cmp;
800         ActiveNotes active_notes(cmp);
801                 
802         // Foreach note
803         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
804
805                 // Write any pending note offs earlier than this note on
806                 while ( ! active_notes.empty() ) {
807                         const boost::shared_ptr<const Note> earliest_off = active_notes.top();
808                         const MIDI::Event& off_ev = earliest_off->off_event();
809                         if (off_ev.time() <= (*n)->time()) {
810                                 source->append_event_unlocked(Frames, off_ev);
811                                 active_notes.pop();
812                         } else {
813                                 break;
814                         }
815                 }
816
817                 // Write this note on
818                 source->append_event_unlocked(Frames, (*n)->on_event());
819                 if ((*n)->duration() > 0)
820                         active_notes.push(*n);
821         }
822                 
823         // Write any trailing note offs
824         while ( ! active_notes.empty() ) {
825                 source->append_event_unlocked(Frames, active_notes.top()->off_event());
826                 active_notes.pop();
827         }
828
829         _edited = false;
830         
831         read_unlock();
832
833         return true;
834 }
835
836 XMLNode&
837 MidiModel::get_state()
838 {
839         XMLNode *node = new XMLNode("MidiModel");
840         return *node;
841 }
842