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