* Add SysEx Support to MidiModel / SMF
[ardour.git] / libs / evoral / src / Sequence.cpp
1 /* This file is part of Evoral.
2  * Copyright (C) 2008 Dave Robillard <http://drobilla.net>
3  * Copyright (C) 2000-2008 Paul Davis
4  * 
5  * Evoral is free software; you can redistribute it and/or modify it under the
6  * terms of the GNU General Public License as published by the Free Software
7  * Foundation; either version 2 of the License, or (at your option) any later
8  * version.
9  * 
10  * Evoral is distributed in the hope that it will be useful, but WITHOUT ANY
11  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
13  * 
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #define __STDC_LIMIT_MACROS 1
20
21 #include <iostream>
22 #include <cmath>
23 #include <algorithm>
24 #include <stdexcept>
25 #include <stdint.h>
26 #include "evoral/Sequence.hpp"
27 #include "evoral/ControlList.hpp"
28 #include "evoral/Control.hpp"
29 #include "evoral/ControlSet.hpp"
30 #include "evoral/EventSink.hpp"
31 #include "evoral/MIDIParameters.hpp"
32 #include "evoral/TypeMap.hpp"
33
34 using namespace std;
35
36 namespace Evoral {
37
38 template<typename T>
39 void Sequence<T>::write_lock() {
40         _lock.writer_lock();
41         _control_lock.lock();
42 }
43
44 template<typename T>
45 void Sequence<T>::write_unlock() {
46         _lock.writer_unlock();
47         _control_lock.unlock();
48 }
49
50 template<typename T>
51 void Sequence<T>::read_lock() const {
52         _lock.reader_lock();
53 }
54
55 template<typename T>
56 void Sequence<T>::read_unlock() const {
57         _lock.reader_unlock();
58 }
59
60 struct null_ostream : public std::ostream {
61         null_ostream(): std::ios(0), std::ostream(0) {}
62 };
63 static null_ostream nullout;
64
65 static ostream& debugout = cout;
66 //static ostream& debugout = nullout;
67 static ostream& errorout = cerr;
68
69 // Read iterator (const_iterator)
70
71 template<typename T>
72 Sequence<T>::const_iterator::const_iterator(const Sequence<T>& seq, T t)
73         : _seq(&seq)
74         , _is_end( (t == DBL_MAX) || seq.empty() )
75         , _locked( !_is_end )
76 {
77         debugout << "Created Iterator @ " << t << " (is end: " << _is_end << ")" << endl;
78
79         if (_is_end) {
80                 return;
81         }
82
83         seq.read_lock();
84
85         // find first note which begins after t
86         _note_iter = seq.notes().end();
87         for (typename Sequence<T>::Notes::const_iterator i = seq.notes().begin();
88                         i != seq.notes().end(); ++i) {
89                 if ((*i)->time() >= t) {
90                         _note_iter = i;
91                         break;
92                 }
93         }
94         assert(_note_iter == seq.notes().end() || (*_note_iter)->time() >= t);
95         
96         // find first sysex which begins after t
97         _sysex_iter = seq.sysexes().end();
98         for (typename Sequence<T>::SysExes::const_iterator i = seq.sysexes().begin();
99                         i != seq.sysexes().end(); ++i) {
100                 if ((*i)->time() >= t) {
101                         _sysex_iter = i;
102                         break;
103                 }
104         }
105         assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
106
107         ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
108
109         _control_iters.reserve(seq._controls.size());
110         
111         // find the earliest control event available
112         for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
113                 debugout << "Iterator: control: " << seq._type_map.to_symbol(i->first) << endl;
114                 double x, y;
115                 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
116                 if (!ret) {
117                         debugout << "Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
118                                 << ") has no events past " << t << endl;
119                         continue;
120                 }
121
122                 assert(x >= 0);
123
124                 /*if (y < i->first.min() || y > i->first.max()) {
125                         errorout << "ERROR: Controller " << i->first.symbol() << " value " << y
126                                 << " out of range [" << i->first.min() << "," << i->first.max()
127                                 << "], event ignored" << endl;
128                         continue;
129                 }*/
130
131                 const ControlIterator new_iter(i->second->list(), x, y);
132
133                 debugout << "Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
134                 _control_iters.push_back(new_iter);
135
136                 // if the x of the current control is less than earliest_control
137                 // we have a new earliest_control
138                 if (x < earliest_control.x) {
139                         earliest_control = new_iter;
140                         _control_iter = _control_iters.end();
141                         --_control_iter;
142                         // now _control_iter points to the last Element in _control_iters
143                 }
144         }
145         
146 #define MAKE_SURE_ADDING_SYSEXES_PRESERVES_OLD_SEMANTICS 1
147 #if MAKE_SURE_ADDING_SYSEXES_PRESERVES_OLD_SEMANTICS
148         MIDIMessageType original_type       = NIL;
149         assert (!earliest_control.list || earliest_control.x >= t);
150         
151                if (_note_iter != seq.notes().end()
152                                && (*_note_iter)->on_event().time() >= t
153                                && (!earliest_control.list
154                                        || (*_note_iter)->on_event().time() < earliest_control.x)) {
155                    original_type = NOTE_ON;
156                } else {
157                    original_type = CONTROL;
158                }
159 #endif
160         
161         MIDIMessageType type       = NIL;
162         T       earliest_t = t;
163
164         // if the note comes before anything else set the iterator to the note
165         if (_note_iter != seq.notes().end() && (*_note_iter)->on_event().time() >= t) {
166                 type = NOTE_ON;
167                 earliest_t = (*_note_iter)->on_event().time();
168         }
169              
170         if (earliest_control.list && 
171             earliest_control.x >= t &&
172             earliest_control.x <= earliest_t) {
173                 type = CONTROL;
174                 earliest_t = earliest_control.x;
175         }
176         
177         if (_sysex_iter != seq.sysexes().end() &&
178             (*_sysex_iter)->time() >= t &&
179             (*_sysex_iter)->time() <= earliest_t) {
180                 type = SYSEX;
181                 earliest_t = (*_sysex_iter)->time();
182         }
183         
184 #if MAKE_SURE_ADDING_SYSEXES_PRESERVES_OLD_SEMANTICS
185         assert (type == original_type || type == SYSEX);
186 #endif
187         
188         if (type == NOTE_ON) {
189                 debugout << "Reading note on event @ " << earliest_t << endl;
190                 // initialize the event pointer with a new event
191                 _event = boost::shared_ptr< Event<T> >(new Event<T>((*_note_iter)->on_event(), true));          
192                 _active_notes.push(*_note_iter);
193                 ++_note_iter;
194                 _control_iter = _control_iters.end();
195         } else if (type == CONTROL) {
196                 debugout << "Reading control event @ " << earliest_t << endl;
197                 seq.control_to_midi_event(_event, earliest_control);
198         } else if (type == SYSEX) {
199                 debugout << "Reading system exclusive event @ " << earliest_t << endl;
200                 // initialize the event pointer with a new event
201                 _event = boost::shared_ptr< Event<T> >(new Event<T>(*(*_sysex_iter), true));
202                 ++_sysex_iter;
203                 _control_iter = _control_iters.end();           
204         }
205
206         if ( (! _event.get()) || _event->size() == 0) {
207                 debugout << "New iterator @ " << t << " is at end." << endl;
208                 _is_end = true;
209
210                 // eliminate possible race condition here (ugly)
211                 static Glib::Mutex mutex;
212                 Glib::Mutex::Lock lock(mutex);
213                 if (_locked) {
214                         _seq->read_unlock();
215                         _locked = false;
216                 }
217         } else {
218                 debugout << "New Iterator = " << _event->event_type();
219                 debugout << " : " << hex << (int)((MIDIEvent<T>*)_event.get())->type();
220                 debugout << " @ " <<  _event->time() << endl;
221         }
222
223         //assert(_is_end || (_event->buffer() && _event->buffer()[0] != '\0'));
224 }
225
226 template<typename T>
227 Sequence<T>::const_iterator::~const_iterator()
228 {
229         if (_locked) {
230                 _seq->read_unlock();
231         }
232 }
233
234 template<typename T>
235 const typename Sequence<T>::const_iterator&
236 Sequence<T>::const_iterator::operator++()
237 {
238         if (_is_end) {
239                 throw std::logic_error("Attempt to iterate past end of Sequence");
240         }
241         
242         debugout << "Iterator ++" << endl;
243         assert(_event->buffer() && _event->size() > 0);
244         
245         const MIDIEvent<T>& ev = *((MIDIEvent<T>*)_event.get());
246
247         //debugout << "const_iterator::operator++: " << _event->to_string() << endl;
248
249         if (! (ev.is_note() || ev.is_cc() || ev.is_pgm_change()
250                                 || ev.is_pitch_bender() || ev.is_channel_pressure() || ev.is_sysex()) ) {
251                 errorout << "Unknown event type: " << hex << int(ev.buffer()[0])
252                         << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
253         }
254         
255         assert((
256                 ev.is_note() || 
257                 ev.is_cc() || 
258                 ev.is_pgm_change() || 
259                 ev.is_pitch_bender() || 
260                 ev.is_channel_pressure() ||
261                 ev.is_sysex()
262               ));
263
264         // Increment past current control event
265         if (!ev.is_note() && _control_iter != _control_iters.end() && _control_iter->list.get()) {
266                 double x = 0.0, y = 0.0;
267                 const bool ret = _control_iter->list->rt_safe_earliest_event_unlocked(
268                                 _control_iter->x, DBL_MAX, x, y, false);
269
270                 assert(!ret || x > _control_iter->x);
271
272                 if (ret) {
273                         _control_iter->x = x;
274                         _control_iter->y = y;
275                 } else {
276                         _control_iter->list.reset();
277                         _control_iter->x = DBL_MAX;
278                         _control_iter->y = DBL_MAX;
279                 }
280         }
281
282         _control_iter = _control_iters.begin();
283
284         // find the _control_iter with the earliest event time
285         for (ControlIterators::iterator i = _control_iters.begin(); i != _control_iters.end(); ++i) {
286                 if (i->x < _control_iter->x) {
287                         _control_iter = i;
288                 }
289         }
290
291         MIDIMessageType type       = NIL;
292         T       earliest_t = 0;
293
294         // Next earliest note on
295         if (_note_iter != _seq->notes().end()) {
296                 type = NOTE_ON;
297                 earliest_t = (*_note_iter)->time();
298         }
299
300         // Use the next earliest note off iff it's earlier than the note on
301         if (!_seq->percussive() && (! _active_notes.empty())) {
302                 if (type == NIL || _active_notes.top()->end_time() <= earliest_t) {
303                         type = NOTE_OFF;
304                         earliest_t = _active_notes.top()->end_time();
305                 }
306         }
307
308         // Use the next earliest controller iff it's earlier than the note event
309         if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
310                 if (type == NIL || _control_iter->x <= earliest_t) {
311                         type = CONTROL;
312                         earliest_t = _control_iter->x;
313                 }
314         }
315         
316         // Use the next earliest SysEx iff it's earlier than the controller
317         if (_sysex_iter != _seq->sysexes().end()) {
318                 if (type == NIL || (*_sysex_iter)->time() <= earliest_t) {
319                         type = SYSEX;
320                         earliest_t = (*_sysex_iter)->time();
321                 }
322         }
323
324         if (type == NOTE_ON) {
325                 debugout << "Iterator = note on" << endl;
326                 *_event = (*_note_iter)->on_event();
327                 _active_notes.push(*_note_iter);
328                 ++_note_iter;
329         } else if (type == NOTE_OFF) {
330                 debugout << "Iterator = note off" << endl;
331                 *_event = _active_notes.top()->off_event();
332                 _active_notes.pop();
333         } else if (type == CONTROL) {
334                 debugout << "Iterator = control" << endl;
335                 _seq->control_to_midi_event(_event, *_control_iter);
336         } else if (type == SYSEX) {
337                 debugout << "Iterator = SysEx" << endl;
338                 *_event =*(*_sysex_iter);
339                 ++_sysex_iter;
340         } else {
341                 debugout << "Iterator = End" << endl;
342                 _is_end = true;
343         }
344
345         assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
346
347         return *this;
348 }
349
350 template<typename T>
351 bool
352 Sequence<T>::const_iterator::operator==(const const_iterator& other) const
353 {
354         if (_is_end || other._is_end) {
355                 return (_is_end == other._is_end);
356         } else {
357                 return (_event == other._event);
358         }
359 }
360
361 template<typename T>
362 typename Sequence<T>::const_iterator&
363 Sequence<T>::const_iterator::operator=(const const_iterator& other)
364 {
365         if (_locked && _seq != other._seq) {
366                 _seq->read_unlock();
367         }
368
369         _seq           = other._seq;
370         _active_notes  = other._active_notes;
371         _is_end        = other._is_end;
372         _locked        = other._locked;
373         _note_iter     = other._note_iter;
374         _sysex_iter    = other._sysex_iter;
375         _control_iters = other._control_iters;
376         size_t index   = other._control_iter - other._control_iters.begin();
377         _control_iter  = _control_iters.begin() + index;
378         
379         if (!_is_end && other._event) {
380                 if (_event) {
381                         *_event = *other._event.get();
382                 } else {
383                         _event = boost::shared_ptr< Event<T> >(new Event<T>(*other._event, true));
384                 }
385         } else {
386                 if (_event) {
387                         _event->clear();
388                 }
389         }
390
391         return *this;
392 }
393
394 // Sequence
395
396 template<typename T>
397 Sequence<T>::Sequence(const TypeMap& type_map, size_t size)
398         : _read_iter(*this, DBL_MAX)
399         , _edited(false)
400         , _type_map(type_map)
401         , _notes(size)
402         , _writing(false)
403         , _end_iter(*this, DBL_MAX)
404         , _next_read(UINT32_MAX)
405         , _percussive(false)
406         , _lowest_note(127)
407         , _highest_note(0)
408 {
409         debugout << "Sequence (size " << size << ") constructed: " << this << endl;
410         assert(_end_iter._is_end);
411         assert( ! _end_iter._locked);
412 }
413
414 /** Read events in frame range \a start .. \a start+cnt into \a dst,
415  * adding \a offset to each event's timestamp.
416  * \return number of events written to \a dst
417  */
418 template<typename T>
419 size_t
420 Sequence<T>::read(EventSink<T>& dst, timestamp_t start, timedur_t nframes, timestamp_t offset) const
421 {
422         debugout << this << " read @ " << start << " * " << nframes << " + " << offset << endl;
423         debugout << this << " # notes: " << n_notes() << endl;
424         debugout << this << " # controls: " << _controls.size() << endl;
425
426         size_t read_events = 0;
427
428         if (start != _next_read) {
429                 debugout << "Repositioning iterator from " << _next_read << " to " << start << endl;
430                 _read_iter = const_iterator(*this, (double)start);
431         } else {
432                 debugout << "Using cached iterator at " << _next_read << endl;
433         }
434
435         _next_read = (FrameTime) floor (start + nframes);
436
437         while (_read_iter != end() && _read_iter->time() < start + nframes) {
438                 assert(_read_iter->size() > 0);
439                 assert(_read_iter->buffer());
440                 dst.write(_read_iter->time() + offset,
441                           _read_iter->event_type(),
442                           _read_iter->size(), 
443                           _read_iter->buffer());
444                 
445                  debugout << this << " read event type " << _read_iter->event_type()
446                          << " @ " << _read_iter->time() << " : ";
447                  for (size_t i = 0; i < _read_iter->size(); ++i)
448                          debugout << hex << (int)_read_iter->buffer()[i];
449                  debugout << endl;
450                 
451                 ++_read_iter;
452                 ++read_events;
453         }
454
455         return read_events;
456 }
457
458 /** Write the controller event pointed to by \a iter to \a ev.
459  * The buffer of \a ev will be allocated or resized as necessary.
460  * The event_type of \a ev should be set to the expected output type.
461  * \return true on success
462  */
463 template<typename T>
464 bool
465 Sequence<T>::control_to_midi_event(boost::shared_ptr< Event<T> >& ev, const ControlIterator& iter) const
466 {
467         assert(iter.list.get());
468         const uint32_t event_type = iter.list->parameter().type();
469         
470         // initialize the event pointer with a new event, if necessary
471         if (!ev) {
472                 ev = boost::shared_ptr< Event<T> >(new Event<T>(event_type, 0, 3, NULL, true));
473         }
474         
475         uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
476         ev->set_event_type(_type_map.midi_event_type(midi_type));
477         switch (midi_type) {
478         case MIDI_CMD_CONTROL:
479                 assert(iter.list.get());
480                 assert(iter.list->parameter().channel() < 16);
481                 assert(iter.list->parameter().id() <= INT8_MAX);
482                 assert(iter.y <= INT8_MAX);
483                 
484                 ev->time() = iter.x;
485                 ev->realloc(3);
486                 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
487                 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
488                 ev->buffer()[2] = (uint8_t)iter.y;
489                 break;
490
491         case MIDI_CMD_PGM_CHANGE:
492                 assert(iter.list.get());
493                 assert(iter.list->parameter().channel() < 16);
494                 assert(iter.y <= INT8_MAX);
495                 
496                 ev->time() = iter.x;
497                 ev->realloc(2);
498                 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
499                 ev->buffer()[1] = (uint8_t)iter.y;
500                 break;
501
502         case MIDI_CMD_BENDER:
503                 assert(iter.list.get());
504                 assert(iter.list->parameter().channel() < 16);
505                 assert(iter.y < (1<<14));
506                 
507                 ev->time() = iter.x;
508                 ev->realloc(3);
509                 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
510                 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
511                 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
512                 break;
513
514         case MIDI_CMD_CHANNEL_PRESSURE:
515                 assert(iter.list.get());
516                 assert(iter.list->parameter().channel() < 16);
517                 assert(iter.y <= INT8_MAX);
518
519                 ev->time() = iter.x;
520                 ev->realloc(2);
521                 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
522                 ev->buffer()[1] = (uint8_t)iter.y;
523                 break;
524
525         default:
526                 return false;
527         }
528
529         return true;
530 }
531
532 /** Clear all events from the model.
533  */
534 template<typename T>
535 void
536 Sequence<T>::clear()
537 {
538         _lock.writer_lock();
539         _notes.clear();
540         for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
541                 li->second->list()->clear();
542         _next_read = 0;
543         _read_iter = end();
544         _lock.writer_unlock();
545 }
546
547 /** Begin a write of events to the model.
548  *
549  * If \a mode is Sustained, complete notes with length are constructed as note
550  * on/off events are received.  Otherwise (Percussive), only note on events are
551  * stored; note off events are discarded entirely and all contained notes will
552  * have length 0.
553  */
554 template<typename T>
555 void
556 Sequence<T>::start_write()
557 {
558         debugout << this << " START WRITE, PERCUSSIVE = " << _percussive << endl;
559         write_lock();
560         _writing = true;
561         for (int i = 0; i < 16; ++i)
562                 _write_notes[i].clear();
563         
564         _dirty_controls.clear();
565         write_unlock();
566 }
567
568 /** Finish a write of events to the model.
569  *
570  * If \a delete_stuck is true and the current mode is Sustained, note on events
571  * that were never resolved with a corresonding note off will be deleted.
572  * Otherwise they will remain as notes with length 0.
573  */
574 template<typename T>
575 void
576 Sequence<T>::end_write(bool delete_stuck)
577 {
578         write_lock();
579         assert(_writing);
580
581         debugout << this << " END WRITE: " << _notes.size() << " NOTES\n";
582
583         if (!_percussive && delete_stuck) {
584                 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
585                         if ((*n)->length() == 0) {
586                                 errorout << "WARNING: Stuck note lost: " << (*n)->note() << endl;
587                                 n = _notes.erase(n);
588                                 // we have to break here because erase invalidates the iterator
589                                 break;
590                         } else {
591                                 ++n;
592                         }
593                 }
594         }
595
596         for (int i = 0; i < 16; ++i) {
597                 if (!_write_notes[i].empty()) {
598                         errorout << "WARNING: Sequence<T>::end_write: Channel " << i << " has "
599                                         << _write_notes[i].size() << " stuck notes" << endl;
600                 }
601                 _write_notes[i].clear();
602         }
603
604         for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
605                 (*i)->mark_dirty();
606         }
607         
608         _writing = false;
609         write_unlock();
610 }
611
612 /** Append \a ev to model.  NOT realtime safe.
613  *
614  * Timestamps of events in \a buf are expected to be relative to
615  * the start of this model (t=0) and MUST be monotonically increasing
616  * and MUST be >= the latest event currently in the model.
617  */
618 template<typename T>
619 void
620 Sequence<T>::append(const Event<T>& event)
621 {
622         write_lock();
623         _edited = true;
624         
625         const MIDIEvent<T>& ev = (const MIDIEvent<T>&)event;
626
627         assert(_notes.empty() || ev.time() >= _notes.back()->time());
628         assert(_writing);
629
630         if (ev.is_note_on()) {
631                 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(),
632                                 ev.velocity());
633         } else if (ev.is_note_off()) {
634                 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
635         } else if (ev.is_sysex()) {
636                 append_sysex_unlocked(ev);
637         } else if (!_type_map.type_is_midi(ev.event_type())) {
638                 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
639                 for (size_t i=0; i < ev.size(); ++i) {
640                         printf("%X ", ev.buffer()[i]);
641                 }
642                 printf("\n");
643         } else if (ev.is_cc()) {
644                 append_control_unlocked(
645                                 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
646                                 ev.time(), ev.cc_value());
647         } else if (ev.is_pgm_change()) {
648                 append_control_unlocked(
649                                 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
650                                 ev.time(), ev.pgm_number());
651         } else if (ev.is_pitch_bender()) {
652                 append_control_unlocked(
653                                 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
654                                 ev.time(), double(  (0x7F & ev.pitch_bender_msb()) << 7
655                                         | (0x7F & ev.pitch_bender_lsb()) ));
656         } else if (ev.is_channel_pressure()) {
657                 append_control_unlocked(
658                                 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
659                                 ev.time(), ev.channel_pressure());
660         } else {
661                 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
662         }
663
664         write_unlock();
665 }
666
667 template<typename T>
668 void
669 Sequence<T>::append_note_on_unlocked(uint8_t chan, T time, uint8_t note_num, uint8_t velocity)
670 {
671         debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
672         assert(note_num <= 127);
673         assert(chan < 16);
674         assert(_writing);
675         _edited = true;
676
677         if (note_num < _lowest_note)
678                 _lowest_note = note_num;
679         if (note_num > _highest_note)
680                 _highest_note = note_num;
681
682         boost::shared_ptr< Note<T> > new_note(new Note<T>(chan, time, 0, note_num, velocity));
683         _notes.push_back(new_note);
684         if (!_percussive) {
685                 debugout << "Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
686                 _write_notes[chan].push_back(_notes.size() - 1);
687         } else {
688                 debugout << "Percussive: NOT appending active note on" << endl;
689          }
690 }
691
692 template<typename T>
693 void
694 Sequence<T>::append_note_off_unlocked(uint8_t chan, T time, uint8_t note_num)
695 {
696         debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
697         assert(note_num <= 127);
698         assert(chan < 16);
699         assert(_writing);
700         _edited = true;
701
702         if (_percussive) {
703                 debugout << "Sequence Ignoring note off (percussive mode)" << endl;
704                 return;
705         }
706
707         /* FIXME: make _write_notes fixed size (127 noted) for speed */
708
709         /* FIXME: note off velocity for that one guy out there who actually has
710          * keys that send it */
711
712         bool resolved = false;
713
714         for (WriteNotes::iterator n = _write_notes[chan].begin(); n
715                         != _write_notes[chan].end(); ++n) {
716                 Note<T>& note = *_notes[*n].get();
717                 if (note.note() == note_num) {
718                         assert(time >= note.time());
719                         note.set_length(time - note.time());
720                         _write_notes[chan].erase(n);
721                         debugout << "resolved note, length: " << note.length() << endl;
722                         resolved = true;
723                         break;
724                 }
725         }
726
727         if (!resolved) {
728                 errorout << this << " spurious note off chan " << (int)chan
729                                 << ", note " << (int)note_num << " @ " << time << endl;
730         }
731 }
732
733 template<typename T>
734 void
735 Sequence<T>::append_control_unlocked(const Parameter& param, T time, double value)
736 {
737         debugout << this << " " << _type_map.to_symbol(param) << " @ " << time << " \t= \t" << value
738                         << " # controls: " << _controls.size() << endl;
739         boost::shared_ptr<Control> c = control(param, true);
740         c->list()->rt_add(time, value);
741 }
742
743 template<typename T>
744 void
745 Sequence<T>::append_sysex_unlocked(const MIDIEvent<T>& ev)
746 {
747         debugout << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
748         for (size_t i=0; i < ev.size(); ++i) {
749                 debugout << int(ev.buffer()[i]) << " ";
750         }
751         debugout << "]" << endl;
752
753         boost::shared_ptr<MIDIEvent<T> > event(new MIDIEvent<T>(ev, true));
754         _sysexes.push_back(event);
755 }
756
757 template<typename T>
758 void
759 Sequence<T>::add_note_unlocked(const boost::shared_ptr< Note<T> > note)
760 {
761         debugout << this << " add note " << (int)note->note() << " @ " << note->time() << endl;
762         _edited = true;
763         typename Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
764                         note_time_comparator);
765         _notes.insert(i, note);
766 }
767
768 template<typename T>
769 void
770 Sequence<T>::remove_note_unlocked(const boost::shared_ptr< const Note<T> > note)
771 {
772         _edited = true;
773         debugout << this << " remove note " << (int)note->note() << " @ " << note->time() << endl;
774         for (typename Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
775                 Note<T>& _n = *(*n);
776                 const Note<T>& _note = *note;
777                 // TODO: There is still the issue, that after restarting ardour
778                 // persisted undo does not work, because of rounding errors in the
779                 // event times after saving/restoring to/from MIDI files
780                 /*cerr << "======================================= " << endl;
781                 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.length()) << "-- #" << int(_n.velocity()) << endl;
782                 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.length()) << "-- #" << int(_note.velocity()) << endl;
783                 cerr << "Equal: " << bool(_n == _note) << endl;
784                 cerr << endl << endl;*/
785                 if (_n == _note) {
786                         _notes.erase(n);
787                         // we have to break here, because erase invalidates all iterators, ie. n itself
788                         break;
789                 }
790         }
791 }
792
793 /** Slow!  for debugging only. */
794 #ifndef NDEBUG
795 template<typename T>
796 bool
797 Sequence<T>::is_sorted() const {
798         bool t = 0;
799         for (typename Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
800                 if ((*n)->time() < t)
801                         return false;
802                 else
803                         t = (*n)->time();
804
805         return true;
806 }
807 #endif
808
809 template class Sequence<double>;
810
811 } // namespace Evoral
812