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