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