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