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