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