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