Tidy up MIDI debugging output.
[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 void MidiModel::write_lock() {
39         _lock.writer_lock();
40         _automation_lock.lock();
41 }
42
43 void MidiModel::write_unlock() {
44         _lock.writer_unlock();
45         _automation_lock.unlock();
46 }
47
48 void MidiModel::read_lock() const {
49         _lock.reader_lock();
50         /*_automation_lock.lock();*/
51 }
52
53 void MidiModel::read_unlock() const {
54         _lock.reader_unlock();
55         /*_automation_lock.unlock();*/
56 }
57
58 // Read iterator (const_iterator)
59
60 MidiModel::const_iterator::const_iterator(const MidiModel& model, double t)
61         : _model(&model)
62         , _is_end( (t == DBL_MAX) || model.empty())
63         , _locked( !_is_end)
64 {
65         //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl;
66
67         if (_is_end)
68                 return;
69
70         model.read_lock();
71
72         _note_iter = model.notes().end();
73         // find first note which begins after t
74         for (MidiModel::Notes::const_iterator i = model.notes().begin(); i != model.notes().end(); ++i) {
75                 if ((*i)->time() >= t) {
76                         _note_iter = i;
77                         break;
78                 }
79         }
80
81         MidiControlIterator earliest_control(boost::shared_ptr<AutomationList>(), DBL_MAX, 0.0);
82
83         _control_iters.reserve(model.controls().size());
84         
85         // find the earliest control event available
86         for (Automatable::Controls::const_iterator i = model.controls().begin();
87                         i != model.controls().end(); ++i) {
88
89                 assert(
90                         i->first.type() == MidiCCAutomation ||
91                         i->first.type() == MidiPgmChangeAutomation ||
92                         i->first.type() == MidiPitchBenderAutomation ||
93                         i->first.type() == MidiChannelAftertouchAutomation);
94
95                 double x, y;
96                 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
97                 if (!ret) {
98                         //cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
99                         //      << ") has no events past " << t << endl;
100                         continue;
101                 }
102
103                 assert(x >= 0);
104
105                 if (y >= i->first.min() || y <= i->first.max()) {
106                         cerr << "ERROR: Controller (" << i->first.to_string() << ") value '" << y
107                                 << "' out of range [" << i->first.min() << "," << i->first.max()
108                                 << "], event ignored" << endl;
109                         continue;
110                 }
111
112                 const MidiControlIterator new_iter(i->second->list(), x, y);
113
114                 //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
115                 _control_iters.push_back(new_iter);
116
117                 // if the x of the current control is less than earliest_control
118                 // we have a new earliest_control
119                 if (x < earliest_control.x) {
120                         earliest_control = new_iter;
121                         _control_iter = _control_iters.end();
122                         --_control_iter;
123                         // now _control_iter points to the last Element in _control_iters
124                 }
125         }
126
127         if (_note_iter != model.notes().end()) {
128                 _event = boost::shared_ptr<MIDI::Event>(new MIDI::Event((*_note_iter)->on_event(), true));
129         }
130
131         double time = DBL_MAX;
132         // in case we have no notes in the region, we still want to get controller messages
133         if (_event.get()) {
134                 time = _event->time();
135                 // if the note is going to make it this turn, advance _note_iter
136                 if (earliest_control.x > time) {
137                         _active_notes.push(*_note_iter);
138                         ++_note_iter;
139                 }
140         }
141         
142         // <=, because we probably would want to send control events first 
143         if (earliest_control.automation_list.get() && earliest_control.x <= time) {
144                 model.control_to_midi_event(_event, earliest_control);
145         } else {
146                 _control_iter = _control_iters.end();
147         }
148
149         if ( (! _event.get()) || _event->size() == 0) {
150                 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
151                 _is_end = true;
152
153                 // eliminate possible race condition here (ugly)
154                 static Glib::Mutex mutex;
155                 Glib::Mutex::Lock lock(mutex);
156                 if (_locked) {
157                         _model->read_unlock();
158                         _locked = false;
159                 }
160         } else {
161                 //printf("New MIDI Iterator = %X @ %lf\n", _event->type(), _event->time());
162         }
163
164         assert(_is_end || (_event->buffer() && _event->buffer()[0] != '\0'));
165 }
166
167 MidiModel::const_iterator::~const_iterator()
168 {
169         if (_locked) {
170                 _model->read_unlock();
171         }
172 }
173
174 const MidiModel::const_iterator& MidiModel::const_iterator::operator++()
175 {
176         if (_is_end) {
177                 throw std::logic_error("Attempt to iterate past end of MidiModel");
178         }
179         
180         assert(_event->buffer() && _event->buffer()[0] != '\0');
181
182         /*cerr << "const_iterator::operator++: _event type:" << hex << "0x" << int(_event->type()) 
183          << "   buffer: 0x" << int(_event->buffer()[0]) << " 0x" << int(_event->buffer()[1]) 
184          << " 0x" << int(_event->buffer()[2]) << endl;*/
185
186         if (! (_event->is_note() || _event->is_cc() || _event->is_pgm_change() || _event->is_pitch_bender() || _event->is_channel_aftertouch()) ) {
187                 cerr << "FAILED event buffer: " << hex << int(_event->buffer()[0]) << int(_event->buffer()[1]) << int(_event->buffer()[2]) << endl;
188         }
189         assert((_event->is_note() || _event->is_cc() || _event->is_pgm_change() || _event->is_pitch_bender() || _event->is_channel_aftertouch()));
190
191         // Increment past current control event
192         if (!_event->is_note() && _control_iter != _control_iters.end() && _control_iter->automation_list.get()) {
193                 double x = 0.0, y = 0.0;
194                 const bool ret = _control_iter->automation_list->rt_safe_earliest_event_unlocked(
195                                 _control_iter->x, DBL_MAX, x, y, false);
196                 //cerr << "control_iter x:" << _control_iter->x << " y:" << _control_iter->y << endl;
197
198                 if (ret) {
199                         //cerr << "Incremented " << _control_iter->automation_list->parameter().id() << " to " << x << endl;
200                         _control_iter->x = x;
201                         _control_iter->y = y;
202                 } else {
203                         cerr << "Hit end of " << _control_iter->automation_list->parameter().id() << endl;
204                         _control_iter->automation_list.reset();
205                         _control_iter->x = DBL_MAX;
206                 }
207         }
208
209         const std::vector<MidiControlIterator>::iterator old_control_iter = _control_iter;
210         _control_iter = _control_iters.begin();
211
212         // find the _control_iter with the earliest event time
213         for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
214                         i != _control_iters.end(); ++i) {
215                 if (i->x < _control_iter->x) {
216                         _control_iter = i;
217                 }
218         }
219
220         enum Type {NIL, NOTE_ON, NOTE_OFF, AUTOMATION};
221
222         Type type = NIL;
223         double t = 0;
224
225         // Next earliest note on
226         if (_note_iter != _model->notes().end()) {
227                 type = NOTE_ON;
228                 t = (*_note_iter)->time();
229         }
230
231         // Use the next earliest note off iff it's earlier than the note on
232         if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
233                 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
234                         type = NOTE_OFF;
235                         t = _active_notes.top()->end_time();
236                 }
237         }
238
239         // Use the next earliest controller iff it's earlier than the note event
240         if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX /*&& _control_iter != old_control_iter */) {
241                 if (type == NIL || _control_iter->x < t) {
242                         type = AUTOMATION;
243                 }
244         }
245
246         if (type == NOTE_ON) {
247                 //cerr << "********** MIDI Iterator = note on" << endl;
248                 *_event = (*_note_iter)->on_event();
249                 _active_notes.push(*_note_iter);
250                 ++_note_iter;
251         } else if (type == NOTE_OFF) {
252                 //cerr << "********** MIDI Iterator = note off" << endl;
253                 *_event = _active_notes.top()->off_event();
254                 _active_notes.pop();
255         } else if (type == AUTOMATION) {
256                 //cerr << "********** MIDI Iterator = Automation" << endl;
257                 _model->control_to_midi_event(_event, *_control_iter);
258         } else {
259                 //cerr << "********** MIDI Iterator = End" << endl;
260                 _is_end = true;
261         }
262
263         assert(_is_end || _event->size() > 0);
264
265         return *this;
266 }
267
268 bool MidiModel::const_iterator::operator==(const const_iterator& other) const
269 {
270         if (_is_end || other._is_end) {
271                 return (_is_end == other._is_end);
272         } else {
273                 return (_event == other._event);
274         }
275 }
276
277 MidiModel::const_iterator& MidiModel::const_iterator::operator=(const const_iterator& other)
278 {
279         if (_locked && _model != other._model) {
280                 _model->read_unlock();
281         }
282
283         _model         = other._model;
284         _active_notes  = other._active_notes;
285         _is_end        = other._is_end;
286         _locked        = other._locked;
287         _note_iter     = other._note_iter;
288         _control_iters = other._control_iters;
289         size_t index   = other._control_iter - other._control_iters.begin();
290         _control_iter  = _control_iters.begin() + index;
291         
292         if (!_is_end)
293                 _event =  boost::shared_ptr<MIDI::Event>(new MIDI::Event(*other._event, true));
294
295         return *this;
296 }
297
298 // MidiModel
299
300 MidiModel::MidiModel(MidiSource *s, size_t size)
301         : Automatable(s->session(), "midi model")
302         , _notes(size)
303         , _note_mode(Sustained)
304         , _writing(false)
305         , _edited(false)
306         , _end_iter(*this, DBL_MAX)
307         , _next_read(UINT32_MAX)
308         , _read_iter(*this, DBL_MAX)
309         , _midi_source(s)
310 {
311         assert(_end_iter._is_end);
312         assert( ! _end_iter._locked);
313 }
314
315 /** Read events in frame range \a start .. \a start+cnt into \a dst,
316  * adding \a stamp_offset to each event's timestamp.
317  * \return number of events written to \a dst
318  */
319 size_t MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes,
320                 nframes_t stamp_offset, nframes_t negative_stamp_offset) const
321 {
322         //cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
323         //cerr << this << " MM # notes: " << n_notes() << endl;
324
325         size_t read_events = 0;
326
327         if (start != _next_read) {
328                 _read_iter = const_iterator(*this, (double)start);
329                 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
330         } else {
331                 //cerr << "Using cached iterator at " << _next_read << endl;
332         }
333
334         _next_read = start + nframes;
335
336         while (_read_iter != end() && _read_iter->time() < start + nframes) {
337                 assert(_read_iter->size() > 0);
338                 assert(_read_iter->buffer());
339                 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset,
340                           _read_iter->size(), 
341                           _read_iter->buffer());
342                 
343                  //cerr << this << " MidiModel::read event @ " << _read_iter->time()  
344                  //<< " type: " << hex << int(_read_iter->type()) << dec 
345                  //<< " note: " << int(_read_iter->note()) 
346                  //<< " velocity: " << int(_read_iter->velocity()) 
347                  //<< endl;
348                 
349                 ++_read_iter;
350                 ++read_events;
351         }
352
353         return read_events;
354 }
355
356 /** Write the controller event pointed to by \a iter to \a ev.
357  * The buffer of \a ev will be allocated or resized as necessary.
358  * \return true on success
359  */
360 bool
361 MidiModel::control_to_midi_event(boost::shared_ptr<MIDI::Event> ev, const MidiControlIterator& iter) const
362 {
363         assert(iter.automation_list.get());
364         if (!ev)
365                 ev = boost::shared_ptr<MIDI::Event>(new MIDI::Event(0, 3, NULL, true));
366         
367         switch (iter.automation_list->parameter().type()) {
368         case MidiCCAutomation:
369                 assert(iter.automation_list.get());
370                 assert(iter.automation_list->parameter().channel() < 16);
371                 assert(iter.automation_list->parameter().id() <= INT8_MAX);
372                 assert(iter.y <= INT8_MAX);
373                 
374                 ev->time() = iter.x;
375                 ev->realloc(3);
376                 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.automation_list->parameter().channel();
377                 ev->buffer()[1] = (Byte)iter.automation_list->parameter().id();
378                 ev->buffer()[2] = (Byte)iter.y;
379                 break;
380
381         case MidiPgmChangeAutomation:
382                 assert(iter.automation_list.get());
383                 assert(iter.automation_list->parameter().channel() < 16);
384                 assert(iter.automation_list->parameter().id() == 0);
385                 assert(iter.y <= INT8_MAX);
386                 
387                 ev->time() = iter.x;
388                 ev->realloc(2);
389                 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.automation_list->parameter().channel();
390                 ev->buffer()[1] = (Byte)iter.y;
391                 break;
392
393         case MidiPitchBenderAutomation:
394                 assert(iter.automation_list.get());
395                 assert(iter.automation_list->parameter().channel() < 16);
396                 assert(iter.automation_list->parameter().id() == 0);
397                 assert(iter.y < (1<<14));
398                 
399                 ev->time() = iter.x;
400                 ev->realloc(3);
401                 ev->buffer()[0] = MIDI_CMD_BENDER + iter.automation_list->parameter().channel();
402                 ev->buffer()[1] = ((Byte)iter.y) & 0x7F; // LSB
403                 ev->buffer()[2] = (((Byte)iter.y) >> 7) & 0x7F; // MSB
404                 break;
405
406         case MidiChannelAftertouchAutomation:
407                 assert(iter.automation_list.get());
408                 assert(iter.automation_list->parameter().channel() < 16);
409                 assert(iter.automation_list->parameter().id() == 0);
410                 assert(iter.y <= INT8_MAX);
411
412                 ev->time() = iter.x;
413                 ev->realloc(2);
414                 ev->buffer()[0]
415                                 = MIDI_CMD_CHANNEL_PRESSURE + iter.automation_list->parameter().channel();
416                 ev->buffer()[1] = (Byte)iter.y;
417                 break;
418
419         default:
420                 return false;
421         }
422
423         return true;
424 }
425
426
427 /** Clear all events from the model.
428  */
429 void MidiModel::clear()
430 {
431         _lock.writer_lock();
432         _notes.clear();
433         clear_automation();
434         _next_read = 0;
435         _read_iter = end();
436         _lock.writer_unlock();
437 }
438
439
440 /** Begin a write of events to the model.
441  *
442  * If \a mode is Sustained, complete notes with duration are constructed as note
443  * on/off events are received.  Otherwise (Percussive), only note on events are
444  * stored; note off events are discarded entirely and all contained notes will
445  * have duration 0.
446  */
447 void MidiModel::start_write()
448 {
449         //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
450         write_lock();
451         _writing = true;
452         for (int i = 0; i < 16; ++i)
453                 _write_notes[i].clear();
454         
455         _dirty_automations.clear();
456         write_unlock();
457 }
458
459 /** Finish a write of events to the model.
460  *
461  * If \a delete_stuck is true and the current mode is Sustained, note on events
462  * that were never resolved with a corresonding note off will be deleted.
463  * Otherwise they will remain as notes with duration 0.
464  */
465 void MidiModel::end_write(bool delete_stuck)
466 {
467         write_lock();
468         assert(_writing);
469
470         //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
471
472         if (_note_mode == Sustained && delete_stuck) {
473                 for (Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
474                         if ((*n)->duration() == 0) {
475                                 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
476                                 n = _notes.erase(n);
477                                 // we have to break here because erase invalidates the iterator
478                                 break;
479                         } else {
480                                 ++n;
481                         }
482                 }
483         }
484
485         for (int i = 0; i < 16; ++i) {
486                 if (!_write_notes[i].empty()) {
487                         cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
488                                         << _write_notes[i].size() << " stuck notes" << endl;
489                 }
490                 _write_notes[i].clear();
491         }
492
493         for (AutomationLists::const_iterator i = _dirty_automations.begin(); i != _dirty_automations.end(); ++i) {
494                 (*i)->Dirty.emit();
495                 (*i)->lookup_cache().left = -1;
496                 (*i)->search_cache().left = -1;
497         }
498         
499         _writing = false;
500         write_unlock();
501 }
502
503 /** Append \a in_event to model.  NOT realtime safe.
504  *
505  * Timestamps of events in \a buf are expected to be relative to
506  * the start of this model (t=0) and MUST be monotonically increasing
507  * and MUST be >= the latest event currently in the model.
508  */
509 void MidiModel::append(const MIDI::Event& ev)
510 {
511         write_lock();
512         _edited = true;
513
514         assert(_notes.empty() || ev.time() >= _notes.back()->time());
515         assert(_writing);
516
517         if (ev.is_note_on()) {
518                 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(),
519                                 ev.velocity());
520         } else if (ev.is_note_off()) {
521                 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
522         } else if (ev.is_cc()) {
523                 append_automation_event_unlocked(MidiCCAutomation, ev.channel(),
524                                 ev.time(), ev.cc_number(), ev.cc_value());
525         } else if (ev.is_pgm_change()) {
526                 append_automation_event_unlocked(MidiPgmChangeAutomation, ev.channel(),
527                                 ev.time(), ev.pgm_number(), 0);
528         } else if (ev.is_pitch_bender()) {
529                 append_automation_event_unlocked(MidiPitchBenderAutomation,
530                                 ev.channel(), ev.time(), ev.pitch_bender_lsb(),
531                                 ev.pitch_bender_msb());
532         } else if (ev.is_channel_aftertouch()) {
533                 append_automation_event_unlocked(MidiChannelAftertouchAutomation,
534                                 ev.channel(), ev.time(), ev.channel_aftertouch(), 0);
535         } else {
536                 printf("WARNING: MidiModel: Unknown event type %X\n", ev.type());
537         }
538
539         write_unlock();
540 }
541
542 void MidiModel::append_note_on_unlocked(uint8_t chan, double time,
543                 uint8_t note_num, uint8_t velocity)
544 {
545         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
546          " note " << (int)note_num << " on @ " << time << endl;*/
547
548         assert(chan < 16);
549         assert(_writing);
550         _edited = true;
551
552         boost::shared_ptr<Note> new_note(new Note(chan, time, 0, note_num, velocity));
553         _notes.push_back(new_note);
554         if (_note_mode == Sustained) {
555                 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
556                 _write_notes[chan].push_back(_notes.size() - 1);
557         }/* else {
558          cerr << "MM Percussive: NOT appending active note on" << endl;
559          }*/
560 }
561
562 void MidiModel::append_note_off_unlocked(uint8_t chan, double time,
563                 uint8_t note_num)
564 {
565         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
566          " note " << (int)note_num << " off @ " << time << endl;*/
567
568         assert(chan < 16);
569         assert(_writing);
570         _edited = true;
571
572         if (_note_mode == Percussive) {
573                 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
574                 return;
575         }
576
577         /* FIXME: make _write_notes fixed size (127 noted) for speed */
578
579         /* FIXME: note off velocity for that one guy out there who actually has
580          * keys that send it */
581
582         bool resolved = false;
583
584         for (WriteNotes::iterator n = _write_notes[chan].begin(); n
585                         != _write_notes[chan].end(); ++n) {
586                 Note& note = *_notes[*n].get();
587                 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
588                 if (note.note() == note_num) {
589                         assert(time >= note.time());
590                         note.set_duration(time - note.time());
591                         _write_notes[chan].erase(n);
592                         //cerr << "MM resolved note, duration: " << note.duration() << endl;
593                         resolved = true;
594                         break;
595                 }
596         }
597
598         if (!resolved) {
599                 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
600                                 << ", note " << (int)note_num << " @ " << time << endl;
601         }
602 }
603
604 void MidiModel::append_automation_event_unlocked(AutomationType type,
605                 uint8_t chan, double time, uint8_t first_byte, uint8_t second_byte)
606 {
607         //cerr << "MidiModel " << this << " chan " << (int)chan <<
608         //              " CC " << (int)number << " = " << (int)value << " @ " << time << endl;
609
610         assert(chan < 16);
611         assert(_writing);
612         _edited = true;
613         double value;
614
615         uint32_t id = 0;
616
617         switch (type) {
618         case MidiCCAutomation:
619                 id = first_byte;
620                 value = double(second_byte);
621                 break;
622         case MidiChannelAftertouchAutomation:
623         case MidiPgmChangeAutomation:
624                 id = 0;
625                 value = double(first_byte);
626                 break;
627         case MidiPitchBenderAutomation:
628                 id = 0;
629                 value = double((0x7F & second_byte) << 7 | (0x7F & first_byte));
630                 break;
631         default:
632                 assert(false);
633         }
634
635         Parameter param(type, id, chan);
636         boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
637         control->list()->rt_add(time, value);
638 }
639
640 void MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
641 {
642         //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
643         _edited = true;
644         Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
645                         note_time_comparator);
646         _notes.insert(i, note);
647 }
648
649 void MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
650 {
651         _edited = true;
652         //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
653         for (Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
654                 Note& _n = *(*n);
655                 const Note& _note = *note;
656                 // TODO: There is still the issue, that after restarting ardour
657                 // persisted undo does not work, because of rounding errors in the
658                 // event times after saving/restoring to/from MIDI files
659                 cerr << "======================================= " << endl;
660                 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.duration()) << "-- #" << int(_n.velocity()) << endl;
661                 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.duration()) << "-- #" << int(_note.velocity()) << endl;
662                 cerr << "Equal: " << bool(_n == _note) << endl;
663                 cerr << endl << endl;
664                 if (_n == _note) {
665                         _notes.erase(n);
666                         // we have to break here, because erase invalidates all iterators, ie. n itself
667                         break;
668                 }
669         }
670 }
671
672 /** Slow!  for debugging only. */
673 #ifndef NDEBUG
674 bool MidiModel::is_sorted() const {
675         bool t = 0;
676         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
677                 if ((*n)->time() < t)
678                         return false;
679                 else
680                         t = (*n)->time();
681
682         return true;
683 }
684 #endif
685
686 /** Start a new command.
687  *
688  * This has no side-effects on the model or Session, the returned command
689  * can be held on to for as long as the caller wishes, or discarded without
690  * formality, until apply_command is called and ownership is taken.
691  */
692 MidiModel::DeltaCommand* MidiModel::new_delta_command(const string name)
693 {
694         DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
695         return cmd;
696 }
697
698 /** Apply a command.
699  *
700  * Ownership of cmd is taken, it must not be deleted by the caller.
701  * The command will constitute one item on the undo stack.
702  */
703 void MidiModel::apply_command(Command* cmd)
704 {
705         _session.begin_reversible_command(cmd->name());
706         (*cmd)();
707         assert(is_sorted());
708         _session.commit_reversible_command(cmd);
709         _edited = true;
710 }
711
712 // MidiEditCommand
713
714 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
715                 const std::string& name)
716         : Command(name)
717         , _model(m)
718         , _name(name)
719 {
720 }
721
722 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
723                 const XMLNode& node)
724         : _model(m)
725 {
726         set_state(node);
727 }
728
729 void MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
730 {
731         //cerr << "MEC: apply" << endl;
732         _removed_notes.remove(note);
733         _added_notes.push_back(note);
734 }
735
736 void MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
737 {
738         //cerr << "MEC: remove" << endl;
739         _added_notes.remove(note);
740         _removed_notes.push_back(note);
741 }
742
743 void MidiModel::DeltaCommand::operator()()
744 {
745         // This could be made much faster by using a priority_queue for added and
746         // removed notes (or sort here), and doing a single iteration over _model
747
748         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
749         const bool reset_iter = (_model->_read_iter.locked());
750         double iter_time = -1.0;
751
752         if (reset_iter) {
753                 if (_model->_read_iter.get_event_pointer().get()) {
754                         iter_time = _model->_read_iter->time();
755                 } else {
756                         cerr << "MidiModel::DeltaCommand::operator(): WARNING: _read_iter points to no event" << endl;
757                 }
758                 _model->_read_iter = _model->end(); // drop read lock
759         }
760
761         assert( ! _model->_read_iter.locked());
762
763         _model->write_lock();
764
765         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
766                 _model->add_note_unlocked(*i);
767
768         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
769                 _model->remove_note_unlocked(*i);
770
771         _model->write_unlock();
772
773         if (reset_iter && iter_time != -1.0) {
774                 _model->_read_iter = const_iterator(*_model.get(), iter_time);
775         }
776
777         _model->ContentsChanged(); /* EMIT SIGNAL */
778 }
779
780 void MidiModel::DeltaCommand::undo()
781 {
782         // This could be made much faster by using a priority_queue for added and
783         // removed notes (or sort here), and doing a single iteration over _model
784
785         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
786         const bool reset_iter = (_model->_read_iter.locked());
787         double iter_time = -1.0;
788
789         if (reset_iter) {
790                 if (_model->_read_iter.get_event_pointer().get()) {
791                         iter_time = _model->_read_iter->time();
792                 } else {
793                         cerr << "MidiModel::DeltaCommand::undo(): WARNING: _read_iter points to no event" << endl;
794                 }
795                 _model->_read_iter = _model->end(); // drop read lock
796         }
797
798         assert( ! _model->_read_iter.locked());
799
800         _model->write_lock();
801
802         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i
803                         != _added_notes.end(); ++i)
804                 _model->remove_note_unlocked(*i);
805
806         for (std::list< boost::shared_ptr<Note> >::iterator i =
807                         _removed_notes.begin(); i != _removed_notes.end(); ++i)
808                 _model->add_note_unlocked(*i);
809
810         _model->write_unlock();
811
812         if (reset_iter && iter_time != -1.0) {
813                 _model->_read_iter = const_iterator(*_model.get(), iter_time);
814         }
815
816         _model->ContentsChanged(); /* EMIT SIGNAL */
817 }
818
819 XMLNode & MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Note> note)
820 {
821         XMLNode *xml_note = new XMLNode("note");
822         ostringstream note_str(ios::ate);
823         note_str << int(note->note());
824         xml_note->add_property("note", note_str.str());
825
826         ostringstream channel_str(ios::ate);
827         channel_str << int(note->channel());
828         xml_note->add_property("channel", channel_str.str());
829
830         ostringstream time_str(ios::ate);
831         time_str << int(note->time());
832         xml_note->add_property("time", time_str.str());
833
834         ostringstream duration_str(ios::ate);
835         duration_str <<(unsigned int) note->duration();
836         xml_note->add_property("duration", duration_str.str());
837
838         ostringstream velocity_str(ios::ate);
839         velocity_str << (unsigned int) note->velocity();
840         xml_note->add_property("velocity", velocity_str.str());
841
842         return *xml_note;
843 }
844
845 boost::shared_ptr<Note> MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
846 {
847         unsigned int note;
848         istringstream note_str(xml_note->property("note")->value());
849         note_str >> note;
850
851         unsigned int channel;
852         istringstream channel_str(xml_note->property("channel")->value());
853         channel_str >> channel;
854
855         unsigned int time;
856         istringstream time_str(xml_note->property("time")->value());
857         time_str >> time;
858
859         unsigned int duration;
860         istringstream duration_str(xml_note->property("duration")->value());
861         duration_str >> duration;
862
863         unsigned int velocity;
864         istringstream velocity_str(xml_note->property("velocity")->value());
865         velocity_str >> velocity;
866
867         boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
868         return note_ptr;
869 }
870
871 #define ADDED_NOTES_ELEMENT "added_notes"
872 #define REMOVED_NOTES_ELEMENT "removed_notes"
873 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
874
875 int MidiModel::DeltaCommand::set_state(const XMLNode& delta_command)
876 {
877         if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
878                 return 1;
879         }
880
881         _added_notes.clear();
882         XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
883         XMLNodeList notes = added_notes->children();
884         transform(notes.begin(), notes.end(), back_inserter(_added_notes),
885                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
886
887         _removed_notes.clear();
888         XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
889         notes = removed_notes->children();
890         transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
891                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
892
893         return 0;
894 }
895
896 XMLNode& MidiModel::DeltaCommand::get_state()
897 {
898         XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
899         delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
900
901         XMLNode *added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
902         for_each(_added_notes.begin(), _added_notes.end(), sigc::compose(
903                         sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
904                         sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
905
906         XMLNode *removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
907         for_each(_removed_notes.begin(), _removed_notes.end(), sigc::compose(
908                         sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
909                         sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
910
911         return *delta_command;
912 }
913
914 struct EventTimeComparator {
915         typedef const MIDI::Event* value_type;
916         inline bool operator()(const MIDI::Event& a, const MIDI::Event& b) const {
917                 return a.time() >= b.time();
918         }
919 };
920
921 /** Write the model to a MidiSource (i.e. save the model).
922  * This is different from manually using read to write to a source in that
923  * note off events are written regardless of the track mode.  This is so the
924  * user can switch a recorded track (with note durations from some instrument)
925  * to percussive, save, reload, then switch it back to sustained without
926  * destroying the original note durations.
927  */
928 bool MidiModel::write_to(boost::shared_ptr<MidiSource> source)
929 {
930         read_lock();
931
932         const NoteMode old_note_mode = _note_mode;
933         _note_mode = Sustained;
934         
935         for (const_iterator i = begin(); i != end(); ++i) {
936                 source->append_event_unlocked(Frames, *i);
937         }
938                 
939         _note_mode = old_note_mode;
940         
941         read_unlock();
942         _edited = false;
943
944         return true;
945 }
946
947 XMLNode& MidiModel::get_state()
948 {
949         XMLNode *node = new XMLNode("MidiModel");
950         return *node;
951 }
952