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