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