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