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