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