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