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