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