* Added a couple of guards to prevent MIDI::Events with NULL buffers to enter into...
[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
151 const MidiModel::const_iterator& MidiModel::const_iterator::operator++()
152 {
153         if (_is_end) {
154                 throw std::logic_error("Attempt to iterate past end of MidiModel");
155         }
156
157         /*cerr << "const_iterator::operator++: _event type:" << hex << "0x" << int(_event.type()) 
158          << "   buffer: 0x" << int(_event.buffer()[0]) << " 0x" << int(_event.buffer()[1]) 
159          << " 0x" << int(_event.buffer()[2]) << endl;*/
160
161         if (! (_event.is_note() || _event.is_cc() || _event.is_pgm_change() || _event.is_pitch_bender() || _event.is_channel_aftertouch()) ) {
162                 cerr << "FAILED event buffer: " << hex << int(_event.buffer()[0]) << int(_event.buffer()[1]) << int(_event.buffer()[2]) << endl;
163         }
164         assert((_event.is_note() || _event.is_cc() || _event.is_pgm_change() || _event.is_pitch_bender() || _event.is_channel_aftertouch()));
165
166         // Increment past current control event
167         if (!_event.is_note() && _control_iter != _control_iters.end() && _control_iter->automation_list.get()) {
168                 double x = 0.0, y = 0.0;
169                 const bool ret = _control_iter->automation_list->rt_safe_earliest_event_unlocked(
170                                 _control_iter->x, DBL_MAX, x, y, false);
171                 //cerr << "control_iter x:" << _control_iter->x << " y:" << _control_iter->y << endl;
172
173                 if (ret) {
174                         //cerr << "Incremented " << _control_iter->automation_list->parameter().id() << " to " << x << endl;
175                         _control_iter->x = x;
176                         _control_iter->y = y;
177                 } else {
178                         cerr << "Hit end of " << _control_iter->automation_list->parameter().id() << endl;
179                         _control_iter->automation_list.reset();
180                         _control_iter->x = DBL_MAX;
181                 }
182         }
183
184         // Now find and point at the earliest event
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
253 MidiModel::const_iterator& MidiModel::const_iterator::operator=(const const_iterator& other)
254 {
255         if (_locked && _model != other._model)
256                 _model->read_unlock();
257
258         assert( ! other._event.owns_buffer());
259
260         _model = other._model;
261         _event = other._event;
262         _active_notes = other._active_notes;
263         _is_end = other._is_end;
264         _locked = other._locked;
265         _note_iter = other._note_iter;
266         _control_iters = other._control_iters;
267         size_t index = other._control_iter - other._control_iters.begin();
268         _control_iter = _control_iters.begin() + index;
269
270         assert( !_event.owns_buffer() );
271
272         return *this;
273 }
274
275 // MidiModel
276
277 MidiModel::MidiModel(MidiSource *s, size_t size)
278         : Automatable(s->session(), "midi model")
279         , _notes(size)
280         , _note_mode(Sustained)
281         , _writing(false)
282         , _edited(false)
283         , _end_iter(*this, DBL_MAX)
284         , _next_read(UINT32_MAX)
285         , _read_iter(*this, DBL_MAX)
286         , _midi_source(s)
287 {
288         assert(_end_iter._is_end);
289         assert( ! _end_iter._locked);
290 }
291
292 /** Read events in frame range \a start .. \a start+cnt into \a dst,
293  * adding \a stamp_offset to each event's timestamp.
294  * \return number of events written to \a dst
295  */
296 size_t MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes,
297                 nframes_t stamp_offset, nframes_t negative_stamp_offset) const
298 {
299         //cerr << this << " MM::read @ " << start << " frames: " << nframes << " -> " << stamp_offset << endl;
300         //cerr << this << " MM # notes: " << n_notes() << endl;
301
302         size_t read_events = 0;
303
304         if (start != _next_read) {
305                 _read_iter = const_iterator(*this, (double)start);
306                 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
307         } else {
308                 //cerr << "Using cached iterator at " << _next_read << endl;
309         }
310
311         _next_read = start + nframes;
312
313         while (_read_iter != end() && _read_iter->time() < start + nframes) {
314                 assert(_read_iter->size()> 0);
315                 assert(_read_iter->buffer());
316                 dst.write(_read_iter->time() + stamp_offset - negative_stamp_offset,
317                                 _read_iter->size(), _read_iter->buffer());
318
319                 
320                  cerr << this << " MidiModel::read event @ " << _read_iter->time()  
321                  << " type: " << hex << int(_read_iter->type()) << dec 
322                  //<< " note: " << int(_read_iter->note()) 
323                  //<< " velocity: " << int(_read_iter->velocity()) 
324                  << endl;
325                  
326
327                 ++_read_iter;
328                 ++read_events;
329         }
330
331         return read_events;
332 }
333
334 bool MidiModel::control_to_midi_event(MIDI::Event& ev,
335                 const MidiControlIterator& iter) const
336 {
337         assert(iter.automation_list.get() != 0);
338         
339         switch (iter.automation_list->parameter().type()) {
340         case MidiCCAutomation:
341                 if (ev.size() < 3) {
342                         ev.set_buffer((Byte*)malloc(3), true);
343                 }
344
345                 assert(iter.automation_list);
346                 assert(iter.automation_list->parameter().channel() < 16);
347                 assert(iter.automation_list->parameter().id() <= INT8_MAX);
348                 assert(iter.y <= INT8_MAX);
349                 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.automation_list->parameter().channel();
350                 ev.buffer()[1] = (Byte)iter.automation_list->parameter().id();
351                 ev.buffer()[2] = (Byte)iter.y;
352                 ev.time() = iter.x;
353                 ev.size() = 3;
354                 return true;
355
356         case MidiPgmChangeAutomation:
357                 if (ev.size() < 2) {
358                         ev.set_buffer((Byte*)malloc(2), true);
359                 }
360
361                 assert(iter.automation_list);
362                 assert(iter.automation_list->parameter().channel() < 16);
363                 assert(iter.automation_list->parameter().id() == 0);
364                 assert(iter.y <= INT8_MAX);
365                 ev.buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.automation_list->parameter().channel();
366                 ev.buffer()[1] = (Byte)iter.y;
367                 ev.time() = iter.x;
368                 ev.size() = 3;
369                 return true;
370
371         case MidiPitchBenderAutomation:
372                 if (ev.size() < 3) {
373                         ev.set_buffer((Byte*)malloc(3), true);
374                 }
375
376                 assert(iter.automation_list);
377                 assert(iter.automation_list->parameter().channel() < 16);
378                 assert(iter.automation_list->parameter().id() == 0);
379                 assert(iter.y < (1<<14));
380                 ev.buffer()[0] = MIDI_CMD_BENDER + iter.automation_list->parameter().channel();
381                 ev.buffer()[1] = ((Byte)iter.y) & 0x7F; // LSB
382                 ev.buffer()[2] = (((Byte)iter.y) >> 7) & 0x7F; // MSB
383                 ev.time() = iter.x;
384                 ev.size() = 3;
385                 return true;
386
387         case MidiChannelAftertouchAutomation:
388                 if (ev.size() < 2) {
389                         ev.set_buffer((Byte*)malloc(2), true);
390                 }
391
392                 assert(iter.automation_list);
393                 assert(iter.automation_list->parameter().channel() < 16);
394                 assert(iter.automation_list->parameter().id() == 0);
395                 assert(iter.y <= INT8_MAX);
396                 ev.buffer()[0]
397                                 = MIDI_CMD_CHANNEL_PRESSURE + iter.automation_list->parameter().channel();
398                 ev.buffer()[1] = (Byte)iter.y;
399                 ev.time() = iter.x;
400                 ev.size() = 3;
401                 return true;
402
403         default:
404                 return false;
405         }
406 }
407
408
409 /** Clear all events from the model.
410  */
411 void MidiModel::clear()
412 {
413         _lock.writer_lock();
414         _notes.clear();
415         clear_automation();
416         _next_read = 0;
417         _read_iter = end();
418         _lock.writer_unlock();
419 }
420
421
422 /** Begin a write of events to the model.
423  *
424  * If \a mode is Sustained, complete notes with duration are constructed as note
425  * on/off events are received.  Otherwise (Percussive), only note on events are
426  * stored; note off events are discarded entirely and all contained notes will
427  * have duration 0.
428  */
429 void MidiModel::start_write()
430 {
431         //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
432         write_lock();
433         _writing = true;
434         for (int i = 0; i < 16; ++i)
435                 _write_notes[i].clear();
436         
437         _dirty_automations.clear();
438         write_unlock();
439 }
440
441 /** Finish a write of events to the model.
442  *
443  * If \a delete_stuck is true and the current mode is Sustained, note on events
444  * that were never resolved with a corresonding note off will be deleted.
445  * Otherwise they will remain as notes with duration 0.
446  */
447 void MidiModel::end_write(bool delete_stuck)
448 {
449         write_lock();
450         assert(_writing);
451
452         //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
453
454         if (_note_mode == Sustained && delete_stuck) {
455                 for (Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
456                         if ((*n)->duration() == 0) {
457                                 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
458                                 n = _notes.erase(n);
459                                 // we have to break here because erase invalidates the iterator
460                                 break;
461                         } else {
462                                 ++n;
463                         }
464                 }
465         }
466
467         for (int i = 0; i < 16; ++i) {
468                 if (!_write_notes[i].empty()) {
469                         cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
470                                         << _write_notes[i].size() << " stuck notes" << endl;
471                 }
472                 _write_notes[i].clear();
473         }
474
475         for (AutomationLists::const_iterator i = _dirty_automations.begin(); i != _dirty_automations.end(); ++i) {
476                 (*i)->Dirty.emit();
477                 (*i)->lookup_cache().left = -1;
478                 (*i)->search_cache().left = -1;
479         }
480         
481         _writing = false;
482         write_unlock();
483 }
484
485 /** Append \a in_event to model.  NOT realtime safe.
486  *
487  * Timestamps of events in \a buf are expected to be relative to
488  * the start of this model (t=0) and MUST be monotonically increasing
489  * and MUST be >= the latest event currently in the model.
490  */
491 void MidiModel::append(const MIDI::Event& ev)
492 {
493         write_lock();
494         _edited = true;
495
496         cerr << "MidiModel append event type: "
497                 << hex << "0x" << (int)ev.type() << endl;
498
499         assert(_notes.empty() || ev.time() >= _notes.back()->time());
500         assert(_writing);
501
502         if (ev.is_note_on()) {
503                 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(),
504                                 ev.velocity());
505         } else if (ev.is_note_off()) {
506                 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
507         } else if (ev.is_cc()) {
508                 append_automation_event_unlocked(MidiCCAutomation, ev.channel(),
509                                 ev.time(), ev.cc_number(), ev.cc_value());
510         } else if (ev.is_pgm_change()) {
511                 append_automation_event_unlocked(MidiPgmChangeAutomation, ev.channel(),
512                                 ev.time(), ev.pgm_number(), 0);
513         } else if (ev.is_pitch_bender()) {
514                 append_automation_event_unlocked(MidiPitchBenderAutomation,
515                                 ev.channel(), ev.time(), ev.pitch_bender_lsb(),
516                                 ev.pitch_bender_msb());
517         } else if (ev.is_channel_aftertouch()) {
518                 append_automation_event_unlocked(MidiChannelAftertouchAutomation,
519                                 ev.channel(), ev.time(), ev.channel_aftertouch(), 0);
520         } else {
521                 printf("WARNING: MidiModel: Unknown event type %X\n", ev.type());
522         }
523
524         write_unlock();
525 }
526
527 void MidiModel::append_note_on_unlocked(uint8_t chan, double time,
528                 uint8_t note_num, uint8_t velocity)
529 {
530         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
531          " note " << (int)note_num << " on @ " << time << endl;*/
532
533         assert(chan < 16);
534         assert(_writing);
535         _edited = true;
536
537         boost::shared_ptr<Note> new_note(new Note(chan, time, 0, note_num, velocity));
538         _notes.push_back(new_note);
539         if (_note_mode == Sustained) {
540                 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
541                 _write_notes[chan].push_back(_notes.size() - 1);
542         }/* else {
543          cerr << "MM Percussive: NOT appending active note on" << endl;
544          }*/
545 }
546
547 void MidiModel::append_note_off_unlocked(uint8_t chan, double time,
548                 uint8_t note_num)
549 {
550         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
551          " note " << (int)note_num << " off @ " << time << endl;*/
552
553         assert(chan < 16);
554         assert(_writing);
555         _edited = true;
556
557         if (_note_mode == Percussive) {
558                 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
559                 return;
560         }
561
562         /* FIXME: make _write_notes fixed size (127 noted) for speed */
563
564         /* FIXME: note off velocity for that one guy out there who actually has
565          * keys that send it */
566
567         bool resolved = false;
568
569         for (WriteNotes::iterator n = _write_notes[chan].begin(); n
570                         != _write_notes[chan].end(); ++n) {
571                 Note& note = *_notes[*n].get();
572                 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
573                 if (note.note() == note_num) {
574                         assert(time >= note.time());
575                         note.set_duration(time - note.time());
576                         _write_notes[chan].erase(n);
577                         //cerr << "MM resolved note, duration: " << note.duration() << endl;
578                         resolved = true;
579                         break;
580                 }
581         }
582
583         if (!resolved) {
584                 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
585                                 << ", note " << (int)note_num << " @ " << time << endl;
586         }
587 }
588
589 void MidiModel::append_automation_event_unlocked(AutomationType type,
590                 uint8_t chan, double time, uint8_t first_byte, uint8_t second_byte)
591 {
592         //cerr << "MidiModel " << this << " chan " << (int)chan <<
593         //              " CC " << (int)number << " = " << (int)value << " @ " << time << endl;
594
595         assert(chan < 16);
596         assert(_writing);
597         _edited = true;
598         double value;
599
600         uint32_t id = 0;
601
602         switch (type) {
603         case MidiCCAutomation:
604                 id = first_byte;
605                 value = double(second_byte);
606                 break;
607         case MidiChannelAftertouchAutomation:
608         case MidiPgmChangeAutomation:
609                 id = 0;
610                 value = double(first_byte);
611                 break;
612         case MidiPitchBenderAutomation:
613                 id = 0;
614                 value = double((0x7F & second_byte) << 7 | (0x7F & first_byte));
615                 break;
616         default:
617                 assert(false);
618         }
619
620         Parameter param(type, id, chan);
621         boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
622         control->list()->rt_add(time, value);
623         /*cerr << "control list size after fast simple add: " << control->list()->size() << endl;*/
624 }
625
626 void MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
627 {
628         //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
629         _edited = true;
630         Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
631                         note_time_comparator);
632         _notes.insert(i, note);
633 }
634
635 void MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
636 {
637         _edited = true;
638         //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
639         for (Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
640                 Note& _n = *(*n);
641                 const Note& _note = *note;
642                 // TODO: There is still the issue, that after restarting ardour
643                 // persisted undo does not work, because of rounding errors in the
644                 // event times after saving/restoring to/from MIDI files
645                 cerr << "======================================= " << endl;
646                 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.duration()) << "-- #" << int(_n.velocity()) << endl;
647                 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.duration()) << "-- #" << int(_note.velocity()) << endl;
648                 cerr << "Equal: " << bool(_n == _note) << endl;
649                 cerr << endl << endl;
650                 if (_n == _note) {
651                         _notes.erase(n);
652                         // we have to break here, because erase invalidates all iterators, ie. n itself
653                         break;
654                 }
655         }
656 }
657
658 /** Slow!  for debugging only. */
659 #ifndef NDEBUG
660 bool MidiModel::is_sorted() const {
661         bool t = 0;
662         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
663                 if ((*n)->time() < t)
664                         return false;
665                 else
666                         t = (*n)->time();
667
668         return true;
669 }
670 #endif
671
672 /** Start a new command.
673  *
674  * This has no side-effects on the model or Session, the returned command
675  * can be held on to for as long as the caller wishes, or discarded without
676  * formality, until apply_command is called and ownership is taken.
677  */
678 MidiModel::DeltaCommand* MidiModel::new_delta_command(const string name)
679 {
680         DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
681         return cmd;
682 }
683
684 /** Apply a command.
685  *
686  * Ownership of cmd is taken, it must not be deleted by the caller.
687  * The command will constitute one item on the undo stack.
688  */
689 void MidiModel::apply_command(Command* cmd)
690 {
691         _session.begin_reversible_command(cmd->name());
692         (*cmd)();
693         assert(is_sorted());
694         _session.commit_reversible_command(cmd);
695         _edited = true;
696 }
697
698 // MidiEditCommand
699
700 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
701                 const std::string& name)
702         : Command(name)
703         , _model(m)
704         , _name(name)
705 {
706 }
707
708 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
709                 const XMLNode& node)
710         : _model(m)
711 {
712         set_state(node);
713 }
714
715 void MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
716 {
717         //cerr << "MEC: apply" << endl;
718         _removed_notes.remove(note);
719         _added_notes.push_back(note);
720 }
721
722 void MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
723 {
724         //cerr << "MEC: remove" << endl;
725         _added_notes.remove(note);
726         _removed_notes.push_back(note);
727 }
728
729 void MidiModel::DeltaCommand::operator()()
730 {
731         // This could be made much faster by using a priority_queue for added and
732         // removed notes (or sort here), and doing a single iteration over _model
733
734         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
735         const bool reset_iter = (_model->_read_iter.locked());
736         const double iter_time = _model->_read_iter->time();
737
738         if (reset_iter)
739                 _model->_read_iter = _model->end(); // drop read lock
740
741         assert( ! _model->_read_iter.locked());
742
743         _model->write_lock();
744
745         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
746                 _model->add_note_unlocked(*i);
747
748         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
749                 _model->remove_note_unlocked(*i);
750
751         _model->write_unlock();
752
753         if (reset_iter)
754         _model->_read_iter = const_iterator(*_model.get(), iter_time);
755
756         _model->ContentsChanged(); /* EMIT SIGNAL */
757 }
758
759 void MidiModel::DeltaCommand::undo()
760 {
761         // This could be made much faster by using a priority_queue for added and
762         // removed notes (or sort here), and doing a single iteration over _model
763
764         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
765         const bool reset_iter = (_model->_read_iter.locked());
766         const double iter_time = _model->_read_iter->time();
767
768         if (reset_iter)
769                 _model->_read_iter = _model->end(); // drop read lock
770
771         assert( ! _model->_read_iter.locked());
772
773         _model->write_lock();
774
775         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i
776                         != _added_notes.end(); ++i)
777                 _model->remove_note_unlocked(*i);
778
779         for (std::list< boost::shared_ptr<Note> >::iterator i =
780                         _removed_notes.begin(); i != _removed_notes.end(); ++i)
781                 _model->add_note_unlocked(*i);
782
783         _model->write_unlock();
784
785         if (reset_iter)
786                 _model->_read_iter = const_iterator(*_model.get(), iter_time);
787
788         _model->ContentsChanged(); /* EMIT SIGNAL */
789 }
790
791 XMLNode & MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Note> note)
792 {
793         XMLNode *xml_note = new XMLNode("note");
794         ostringstream note_str(ios::ate);
795         note_str << int(note->note());
796         xml_note->add_property("note", note_str.str());
797
798         ostringstream channel_str(ios::ate);
799         channel_str << int(note->channel());
800         xml_note->add_property("channel", channel_str.str());
801
802         ostringstream time_str(ios::ate);
803         time_str << int(note->time());
804         xml_note->add_property("time", time_str.str());
805
806         ostringstream duration_str(ios::ate);
807         duration_str <<(unsigned int) note->duration();
808         xml_note->add_property("duration", duration_str.str());
809
810         ostringstream velocity_str(ios::ate);
811         velocity_str << (unsigned int) note->velocity();
812         xml_note->add_property("velocity", velocity_str.str());
813
814         return *xml_note;
815 }
816
817 boost::shared_ptr<Note> MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
818 {
819         unsigned int note;
820         istringstream note_str(xml_note->property("note")->value());
821         note_str >> note;
822
823         unsigned int channel;
824         istringstream channel_str(xml_note->property("channel")->value());
825         channel_str >> channel;
826
827         unsigned int time;
828         istringstream time_str(xml_note->property("time")->value());
829         time_str >> time;
830
831         unsigned int duration;
832         istringstream duration_str(xml_note->property("duration")->value());
833         duration_str >> duration;
834
835         unsigned int velocity;
836         istringstream velocity_str(xml_note->property("velocity")->value());
837         velocity_str >> velocity;
838
839         boost::shared_ptr<Note> note_ptr(new Note(channel, time, duration, note, velocity));
840         return note_ptr;
841 }
842
843 #define ADDED_NOTES_ELEMENT "added_notes"
844 #define REMOVED_NOTES_ELEMENT "removed_notes"
845 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
846
847 int MidiModel::DeltaCommand::set_state(const XMLNode& delta_command)
848 {
849         if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
850                 return 1;
851         }
852
853         _added_notes.clear();
854         XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
855         XMLNodeList notes = added_notes->children();
856         transform(notes.begin(), notes.end(), back_inserter(_added_notes),
857                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
858
859         _removed_notes.clear();
860         XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
861         notes = removed_notes->children();
862         transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
863                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
864
865         return 0;
866 }
867
868 XMLNode& 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(), sigc::compose(
875                         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(), sigc::compose(
880                         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 struct EventTimeComparator {
887         typedef const MIDI::Event* value_type;
888         inline bool operator()(const MIDI::Event* a, const MIDI::Event* b) const {
889                 return a->time() >= b->time();
890         }
891 };
892
893 /** Write the model to a MidiSource (i.e. save the model).
894  * This is different from manually using read to write to a source in that
895  * note off events are written regardless of the track mode.  This is so the
896  * user can switch a recorded track (with note durations from some instrument)
897  * to percussive, save, reload, then switch it back to sustained without
898  * destroying the original note durations.
899  */
900 bool MidiModel::write_to(boost::shared_ptr<MidiSource> source)
901 {
902         read_lock();
903
904         const NoteMode old_note_mode = _note_mode;
905         _note_mode = Sustained;
906         
907         for (const_iterator i = begin(); i != end(); ++i) {
908                 source->append_event_unlocked(Frames, *i);
909         }
910                 
911         _note_mode = old_note_mode;
912         
913         read_unlock();
914         _edited = false;
915
916         return true;
917 }
918
919 XMLNode& MidiModel::get_state()
920 {
921         XMLNode *node = new XMLNode("MidiModel");
922         return *node;
923 }
924