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