Fix MIDI CC record/playback crash.
[ardour.git] / libs / evoral / src / Sequence.cpp
1 /* This file is part of Evoral.
2  * Copyright (C) 2008 David 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 #include <algorithm>
20 #include <cmath>
21 #include <iostream>
22 #include <limits>
23 #include <stdexcept>
24 #include <stdint.h>
25 #include <cstdio>
26
27 #if __clang__
28 #include "evoral/Note.hpp"
29 #endif
30
31 #include "pbd/compose.h"
32 #include "pbd/error.h"
33
34 #include "evoral/Control.hpp"
35 #include "evoral/ControlList.hpp"
36 #include "evoral/ControlSet.hpp"
37 #include "evoral/EventSink.hpp"
38 #include "evoral/ParameterDescriptor.hpp"
39 #include "evoral/Sequence.hpp"
40 #include "evoral/TypeMap.hpp"
41 #include "evoral/midi_util.h"
42
43 #include "i18n.h"
44
45 using namespace std;
46 using namespace PBD;
47
48 /** Minimum time between MIDI outputs from a single interpolated controller,
49     expressed in beats.  This is to limit the rate at which MIDI messages
50     are generated.  It is only applied to interpolated controllers.
51
52     XXX: This is a hack.  The time should probably be expressed in
53     seconds rather than beats, and should be configurable etc. etc.
54 */
55 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
56
57 namespace Evoral {
58
59 // Read iterator (const_iterator)
60
61 template<typename Time>
62 Sequence<Time>::const_iterator::const_iterator()
63         : _seq(NULL)
64         , _event(boost::shared_ptr< Event<Time> >(new Event<Time>()))
65         , _active_patch_change_message (0)
66         , _type(NIL)
67         , _is_end(true)
68         , _control_iter(_control_iters.end())
69         , _force_discrete(false)
70 {
71 }
72
73 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
74 template<typename Time>
75 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq, Time t, bool force_discrete, std::set<Evoral::Parameter> const & filtered)
76         : _seq(&seq)
77         , _active_patch_change_message (0)
78         , _type(NIL)
79         , _is_end((t == DBL_MAX) || seq.empty())
80         , _note_iter(seq.notes().end())
81         , _sysex_iter(seq.sysexes().end())
82         , _patch_change_iter(seq.patch_changes().end())
83         , _control_iter(_control_iters.end())
84         , _force_discrete (force_discrete)
85 {
86         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
87
88         if (_is_end) {
89                 return;
90         }
91
92         _lock = seq.read_lock();
93
94         // Find first note which begins at or after t
95         _note_iter = seq.note_lower_bound(t);
96
97         // Find first sysex event at or after t
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         // Find first patch event at or after t
108         for (typename Sequence<Time>::PatchChanges::const_iterator i = seq.patch_changes().begin(); i != seq.patch_changes().end(); ++i) {
109                 if ((*i)->time() >= t) {
110                         _patch_change_iter = i;
111                         break;
112                 }
113         }
114         assert (_patch_change_iter == seq.patch_changes().end() || (*_patch_change_iter)->time() >= t);
115
116         // Find first control event after t
117         _control_iters.reserve(seq._controls.size());
118         bool   found                  = false;
119         size_t earliest_control_index = 0;
120         double earliest_control_x     = DBL_MAX;
121         for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
122
123                 if (filtered.find (i->first) != filtered.end()) {
124                         /* this parameter is filtered, so don't bother setting up an iterator for it */
125                         continue;
126                 }
127
128                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
129                 double x, y;
130                 bool ret;
131                 if (_force_discrete || i->second->list()->interpolation() == ControlList::Discrete) {
132                         ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t.to_double(), x, y, true);
133                 } else {
134                         ret = i->second->list()->rt_safe_earliest_event_unlocked(t.to_double(), x, y, true);
135                 }
136                 if (!ret) {
137                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
138                                                                       i->first.id(), i->second->list()->size(), t));
139                         continue;
140                 }
141
142                 assert(x >= 0);
143
144                 const ParameterDescriptor& desc = seq.type_map().descriptor(i->first);
145                 if (y < desc.lower || y > desc.upper) {
146                         cerr << "ERROR: Controller value " << y
147                              << " out of range [" << desc.lower << "," << desc.upper
148                              << "], event ignored" << endl;
149                         continue;
150                 }
151
152                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
153
154                 const ControlIterator new_iter(i->second->list(), x, y);
155                 _control_iters.push_back(new_iter);
156
157                 // Found a new earliest_control
158                 if (x < earliest_control_x) {
159                         earliest_control_x     = x;
160                         earliest_control_index = _control_iters.size() - 1;
161                         found                  = true;
162                 }
163         }
164
165         if (found) {
166                 _control_iter = _control_iters.begin() + earliest_control_index;
167                 assert(_control_iter != _control_iters.end());
168                 assert(_control_iter->list);
169         } else {
170                 _control_iter = _control_iters.end();
171         }
172
173         // Choose the earliest event overall to point to
174         choose_next(t);
175
176         // Allocate a new event for storing the current event in MIDI format
177         _event = boost::shared_ptr< Event<Time> >(
178                 new Event<Time>(0, Time(), 4, NULL, true));
179
180         // Set event from chosen sub-iterator
181         set_event();
182
183         if (_is_end) {
184                 DEBUG_TRACE(DEBUG::Sequence,
185                             string_compose("Starting at end @ %1\n", t));
186         } else {
187                 DEBUG_TRACE(DEBUG::Sequence,
188                             string_compose("Starting at type 0x%1 : 0x%2 @ %3\n",
189                                            (int)_event->event_type(),
190                                            (int)((MIDIEvent<Time>*)_event.get())->type(),
191                                            _event->time()));
192         }
193 }
194
195 template<typename Time>
196 Sequence<Time>::const_iterator::~const_iterator()
197 {
198 }
199
200 template<typename Time>
201 void
202 Sequence<Time>::const_iterator::invalidate()
203 {
204         while (!_active_notes.empty()) {
205                 _active_notes.pop();
206         }
207         _type = NIL;
208         _is_end = true;
209         if (_seq) {
210                 _note_iter = _seq->notes().end();
211                 _sysex_iter = _seq->sysexes().end();
212                 _patch_change_iter = _seq->patch_changes().end();
213                 _active_patch_change_message = 0;
214         }
215         _control_iters.clear();
216         _control_iter = _control_iters.end();
217         _lock.reset();
218 }
219
220 template<typename Time>
221 Time
222 Sequence<Time>::const_iterator::choose_next(Time earliest_t)
223 {
224         _type = NIL;
225
226         // Next earliest note on
227         if (_note_iter != _seq->notes().end()) {
228                 _type      = NOTE_ON;
229                 earliest_t = (*_note_iter)->time();
230         }
231
232         // Use the next note off iff it's earlier or the same time as the note on
233         if ((!_active_notes.empty())) {
234                 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
235                         _type      = NOTE_OFF;
236                         earliest_t = _active_notes.top()->end_time();
237                 }
238         }
239
240         // Use the next earliest controller iff it's earlier than the note event
241         if (_control_iter != _control_iters.end() &&
242             _control_iter->list && _control_iter->x != DBL_MAX) {
243                 if (_type == NIL || _control_iter->x < earliest_t.to_double()) {
244                         _type      = CONTROL;
245                         earliest_t = Time(_control_iter->x);
246                 }
247         }
248
249         // Use the next earliest SysEx iff it's earlier than the controller
250         if (_sysex_iter != _seq->sysexes().end()) {
251                 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
252                         _type      = SYSEX;
253                         earliest_t = (*_sysex_iter)->time();
254                 }
255         }
256
257         // Use the next earliest patch change iff it's earlier than the SysEx
258         if (_patch_change_iter != _seq->patch_changes().end()) {
259                 if (_type == NIL || (*_patch_change_iter)->time() < earliest_t) {
260                         _type      = PATCH_CHANGE;
261                         earliest_t = (*_patch_change_iter)->time();
262                 }
263         }
264         return earliest_t;
265 }
266
267 template<typename Time>
268 void
269 Sequence<Time>::const_iterator::set_event()
270 {
271         switch (_type) {
272         case NOTE_ON:
273                 DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
274                 *_event = (*_note_iter)->on_event();
275                 _active_notes.push(*_note_iter);
276                 break;
277         case NOTE_OFF:
278                 DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
279                 assert(!_active_notes.empty());
280                 *_event = _active_notes.top()->off_event();
281                 _active_notes.pop();
282                 break;
283         case SYSEX:
284                 DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
285                 *_event = *(*_sysex_iter);
286                 break;
287         case CONTROL:
288                 DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
289                 _seq->control_to_midi_event(_event, *_control_iter);
290                 break;
291         case PATCH_CHANGE:
292                 DEBUG_TRACE(DEBUG::Sequence, "iterator = program change\n");
293                 *_event = (*_patch_change_iter)->message (_active_patch_change_message);
294                 break;
295         default:
296                 _is_end = true;
297                 break;
298         }
299
300         if (_type == NIL || !_event || _event->size() == 0) {
301                 DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
302                 _type   = NIL;
303                 _is_end = true;
304         } else {
305                 assert(midi_event_is_valid(_event->buffer(), _event->size()));
306         }
307 }
308
309 template<typename Time>
310 const typename Sequence<Time>::const_iterator&
311 Sequence<Time>::const_iterator::operator++()
312 {
313         if (_is_end) {
314                 throw std::logic_error("Attempt to iterate past end of Sequence");
315         }
316
317         assert(_event && _event->buffer() && _event->size() > 0);
318
319         const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
320
321         if (!(     ev.is_note()
322                    || ev.is_cc()
323                    || ev.is_pgm_change()
324                    || ev.is_pitch_bender()
325                    || ev.is_channel_pressure()
326                    || ev.is_sysex()) ) {
327                 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
328                      << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
329         }
330
331         double x   = 0.0;
332         double y   = 0.0;
333         bool   ret = false;
334
335         // Increment past current event
336         switch (_type) {
337         case NOTE_ON:
338                 ++_note_iter;
339                 break;
340         case NOTE_OFF:
341                 break;
342         case CONTROL:
343                 // Increment current controller iterator
344                 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
345                         ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
346                                 _control_iter->x, x, y, false);
347                 } else {
348                         ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
349                                 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false);
350                 }
351                 assert(!ret || x > _control_iter->x);
352                 if (ret) {
353                         _control_iter->x = x;
354                         _control_iter->y = y;
355                 } else {
356                         _control_iter->list.reset();
357                         _control_iter->x = DBL_MAX;
358                         _control_iter->y = DBL_MAX;
359                 }
360
361                 // Find the controller with the next earliest event time
362                 _control_iter = _control_iters.begin();
363                 for (ControlIterators::iterator i = _control_iters.begin();
364                      i != _control_iters.end(); ++i) {
365                         if (i->x < _control_iter->x) {
366                                 _control_iter = i;
367                         }
368                 }
369                 break;
370         case SYSEX:
371                 ++_sysex_iter;
372                 break;
373         case PATCH_CHANGE:
374                 ++_active_patch_change_message;
375                 if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
376                         ++_patch_change_iter;
377                         _active_patch_change_message = 0;
378                 }
379                 break;
380         default:
381                 assert(false);
382         }
383
384         // Choose the earliest event overall to point to
385         choose_next(std::numeric_limits<Time>::max());
386
387         // Set event from chosen sub-iterator
388         set_event();
389
390         assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
391
392         return *this;
393 }
394
395 template<typename Time>
396 bool
397 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
398 {
399         if (_seq != other._seq) {
400                 return false;
401         } else if (_is_end || other._is_end) {
402                 return (_is_end == other._is_end);
403         } else if (_type != other._type) {
404                 return false;
405         } else {
406                 return (_event == other._event);
407         }
408 }
409
410 template<typename Time>
411 typename Sequence<Time>::const_iterator&
412 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
413 {
414         _seq           = other._seq;
415         _event         = other._event;
416         _active_notes  = other._active_notes;
417         _type          = other._type;
418         _is_end        = other._is_end;
419         _note_iter     = other._note_iter;
420         _sysex_iter    = other._sysex_iter;
421         _patch_change_iter = other._patch_change_iter;
422         _control_iters = other._control_iters;
423         _force_discrete = other._force_discrete;
424         _active_patch_change_message = other._active_patch_change_message;
425
426         if (other._lock) {
427                 _lock = _seq->read_lock();
428         } else {
429                 _lock.reset();
430         }
431
432         if (other._control_iter == other._control_iters.end()) {
433                 _control_iter = _control_iters.end();
434         } else {
435                 const size_t index = other._control_iter - other._control_iters.begin();
436                 _control_iter  = _control_iters.begin() + index;
437         }
438
439         return *this;
440 }
441
442 // Sequence
443
444 template<typename Time>
445 Sequence<Time>::Sequence(const TypeMap& type_map)
446         : _edited(false)
447         , _overlapping_pitches_accepted (true)
448         , _overlap_pitch_resolution (FirstOnFirstOff)
449         , _writing(false)
450         , _type_map(type_map)
451         , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
452         , _percussive(false)
453         , _lowest_note(127)
454         , _highest_note(0)
455 {
456         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
457         assert(_end_iter._is_end);
458         assert( ! _end_iter._lock);
459
460         for (int i = 0; i < 16; ++i) {
461                 _bank[i] = 0;
462         }
463 }
464
465 template<typename Time>
466 Sequence<Time>::Sequence(const Sequence<Time>& other)
467         : ControlSet (other)
468         , _edited(false)
469         , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
470         , _overlap_pitch_resolution (other._overlap_pitch_resolution)
471         , _writing(false)
472         , _type_map(other._type_map)
473         , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
474         , _percussive(other._percussive)
475         , _lowest_note(other._lowest_note)
476         , _highest_note(other._highest_note)
477 {
478         for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
479                 NotePtr n (new Note<Time> (**i));
480                 _notes.insert (n);
481         }
482
483         for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
484                 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
485                 _sysexes.insert (n);
486         }
487
488         for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
489                 PatchChangePtr n (new PatchChange<Time> (**i));
490                 _patch_changes.insert (n);
491         }
492
493         for (int i = 0; i < 16; ++i) {
494                 _bank[i] = other._bank[i];
495         }
496
497         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
498         assert(_end_iter._is_end);
499         assert(! _end_iter._lock);
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(
510         boost::shared_ptr< Event<Time> >& ev,
511         const ControlIterator&            iter) const
512 {
513         assert(iter.list.get());
514         const uint32_t event_type = iter.list->parameter().type();
515
516         // initialize the event pointer with a new event, if necessary
517         if (!ev) {
518                 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, Time(), 3, NULL, true));
519         }
520
521         uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
522         ev->set_event_type(_type_map.midi_event_type(midi_type));
523         switch (midi_type) {
524         case MIDI_CMD_CONTROL:
525                 assert(iter.list.get());
526                 assert(iter.list->parameter().channel() < 16);
527                 assert(iter.list->parameter().id() <= INT8_MAX);
528                 assert(iter.y <= INT8_MAX);
529
530                 ev->set_time(Time(iter.x));
531                 ev->realloc(3);
532                 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
533                 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
534                 ev->buffer()[2] = (uint8_t)iter.y;
535                 break;
536
537         case MIDI_CMD_PGM_CHANGE:
538                 assert(iter.list.get());
539                 assert(iter.list->parameter().channel() < 16);
540                 assert(iter.y <= INT8_MAX);
541
542                 ev->set_time(Time(iter.x));
543                 ev->realloc(2);
544                 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
545                 ev->buffer()[1] = (uint8_t)iter.y;
546                 break;
547
548         case MIDI_CMD_BENDER:
549                 assert(iter.list.get());
550                 assert(iter.list->parameter().channel() < 16);
551                 assert(iter.y < (1<<14));
552
553                 ev->set_time(Time(iter.x));
554                 ev->realloc(3);
555                 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
556                 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
557                 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
558                 break;
559
560         case MIDI_CMD_CHANNEL_PRESSURE:
561                 assert(iter.list.get());
562                 assert(iter.list->parameter().channel() < 16);
563                 assert(iter.y <= INT8_MAX);
564
565                 ev->set_time(Time(iter.x));
566                 ev->realloc(2);
567                 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
568                 ev->buffer()[1] = (uint8_t)iter.y;
569                 break;
570
571         default:
572                 return false;
573         }
574
575         return true;
576 }
577
578 /** Clear all events from the model.
579  */
580 template<typename Time>
581 void
582 Sequence<Time>::clear()
583 {
584         WriteLock lock(write_lock());
585         _notes.clear();
586         for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
587                 li->second->list()->clear();
588 }
589
590 /** Begin a write of events to the model.
591  *
592  * If \a mode is Sustained, complete notes with length are constructed as note
593  * on/off events are received.  Otherwise (Percussive), only note on events are
594  * stored; note off events are discarded entirely and all contained notes will
595  * have length 0.
596  */
597 template<typename Time>
598 void
599 Sequence<Time>::start_write()
600 {
601         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
602         WriteLock lock(write_lock());
603         _writing = true;
604         for (int i = 0; i < 16; ++i) {
605                 _write_notes[i].clear();
606         }
607 }
608
609 /** Finish a write of events to the model.
610  *
611  * If \a delete_stuck is true and the current mode is Sustained, note on events
612  * that were never resolved with a corresonding note off will be deleted.
613  * Otherwise they will remain as notes with length 0.
614  */
615 template<typename Time>
616 void
617 Sequence<Time>::end_write (StuckNoteOption option, Time when)
618 {
619         WriteLock lock(write_lock());
620
621         if (!_writing) {
622                 return;
623         }
624
625         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
626
627         #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
628         if (!_percussive) {
629         #endif
630                 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
631                         typename Notes::iterator next = n;
632                         ++next;
633
634                         if (!(*n)->length()) {
635                                 switch (option) {
636                                 case Relax:
637                                         break;
638                                 case DeleteStuckNotes:
639                                         cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
640                                         _notes.erase(n);
641                                         break;
642                                 case ResolveStuckNotes:
643                                         if (when <= (*n)->time()) {
644                                                 cerr << "WARNING: Stuck note resolution - end time @ "
645                                                      << when << " is before note on: " << (**n) << endl;
646                                                 _notes.erase (*n);
647                                         } else {
648                                                 (*n)->set_length (when - (*n)->time());
649                                                 cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
650                                         }
651                                         break;
652                                 }
653                         }
654
655                         n = next;
656                 }
657         #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
658         }
659         #endif
660
661         for (int i = 0; i < 16; ++i) {
662                 _write_notes[i].clear();
663         }
664
665         _writing = false;
666 }
667
668
669 template<typename Time>
670 bool
671 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
672 {
673         /* This is the core method to add notes to a Sequence
674          */
675
676         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
677
678         if (resolve_overlaps_unlocked (note, arg)) {
679                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
680                 return false;
681         }
682
683         if (note->id() < 0) {
684                 note->set_id (Evoral::next_event_id());
685         }
686
687         if (note->note() < _lowest_note)
688                 _lowest_note = note->note();
689         if (note->note() > _highest_note)
690                 _highest_note = note->note();
691
692         _notes.insert (note);
693         _pitches[note->channel()].insert (note);
694
695         _edited = true;
696
697         return true;
698 }
699
700 template<typename Time>
701 void
702 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
703 {
704         bool erased = false;
705         bool id_matched = false;
706
707         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
708
709         /* first try searching for the note using the time index, which is
710          * faster since the container is "indexed" by time. (technically, this
711          * means that lower_bound() can do a binary search rather than linear)
712          *
713          * this may not work, for reasons explained below.
714          */
715
716         typename Sequence<Time>::Notes::iterator i;
717                 
718         for (i = note_lower_bound(note->time()); i != _notes.end() && (*i)->time() == note->time(); ++i) {
719
720                 if (*i == note) {
721
722                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
723                         _notes.erase (i);
724
725                         if (note->note() == _lowest_note || note->note() == _highest_note) {
726
727                                 _lowest_note = 127;
728                                 _highest_note = 0;
729
730                                 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
731                                         if ((*ii)->note() < _lowest_note)
732                                                 _lowest_note = (*ii)->note();
733                                         if ((*ii)->note() > _highest_note)
734                                                 _highest_note = (*ii)->note();
735                                 }
736                         }
737
738                         erased = true;
739                         break;
740                 }
741         }
742
743         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\ttime-based lookup did not find note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
744
745         if (!erased) {
746
747                 /* if the note's time property was changed in tandem with some
748                  * other property as the next operation after it was added to
749                  * the sequence, then at the point where we call this to undo
750                  * the add, the note we are targetting currently has a
751                  * different time property than the one we we passed via
752                  * the argument.
753                  *
754                  * in this scenario, we have no choice other than to linear
755                  * search the list of notes and find the note by ID.
756                  */
757                 
758                 for (i = _notes.begin(); i != _notes.end(); ++i) {
759
760                         if ((*i)->id() == note->id()) {
761                                 
762                                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\tID-based pass, erasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
763                                 _notes.erase (i);
764                                 
765                                 if (note->note() == _lowest_note || note->note() == _highest_note) {
766                                         
767                                         _lowest_note = 127;
768                                         _highest_note = 0;
769                                         
770                                         for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
771                                                 if ((*ii)->note() < _lowest_note)
772                                                         _lowest_note = (*ii)->note();
773                                                 if ((*ii)->note() > _highest_note)
774                                                         _highest_note = (*ii)->note();
775                                         }
776                                 }
777                                 
778                                 erased = true;
779                                 id_matched = true;
780                                 break;
781                         }
782                 }
783         }
784         
785         if (erased) {
786
787                 Pitches& p (pitches (note->channel()));
788                 
789                 typename Pitches::iterator j;
790
791                 /* if we had to ID-match above, we can't expect to find it in
792                  * pitches via note comparison either. so do another linear
793                  * search to locate it. otherwise, we can use the note index
794                  * to potentially speed things up.
795                  */
796
797                 if (id_matched) {
798
799                         for (j = p.begin(); j != p.end(); ++j) {
800                                 if ((*j)->id() == note->id()) {
801                                         p.erase (j);
802                                         break;
803                                 }
804                         }
805
806                 } else {
807
808                         /* Now find the same note in the "pitches" list (which indexes
809                          * notes by channel+time. We care only about its note number
810                          * so the search_note has all other properties unset.
811                          */
812                         
813                         NotePtr search_note (new Note<Time>(0, Time(), Time(), note->note(), 0));
814
815                         for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
816                                 
817                                 if ((*j) == note) {
818                                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
819                                         p.erase (j);
820                                         break;
821                                 }
822                         }
823                 }
824
825                 if (j == p.end()) {
826                         warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
827                 }
828
829                 _edited = true;
830         
831         } else {
832                 cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
833         }
834 }
835
836 template<typename Time>
837 void
838 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
839 {
840         typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
841
842         while (i != _patch_changes.end() && ((*i)->time() == p->time())) {
843
844                 typename Sequence<Time>::PatchChanges::iterator tmp = i;
845                 ++tmp;
846
847                 if (**i == *p) {
848                         _patch_changes.erase (i);
849                 }
850
851                 i = tmp;
852         }
853 }
854
855 template<typename Time>
856 void
857 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
858 {
859         typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
860         while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
861
862                 typename Sequence<Time>::SysExes::iterator tmp = i;
863                 ++tmp;
864
865                 if (*i == sysex) {
866                         _sysexes.erase (i);
867                 }
868
869                 i = tmp;
870         }
871 }
872
873 /** Append \a ev to model.  NOT realtime safe.
874  *
875  * The timestamp of event is expected to be relative to
876  * the start of this model (t=0) and MUST be monotonically increasing
877  * and MUST be >= the latest event currently in the model.
878  */
879 template<typename Time>
880 void
881 Sequence<Time>::append(const Event<Time>& event, event_id_t evid)
882 {
883         WriteLock lock(write_lock());
884
885         const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
886
887         assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
888         assert(_writing);
889
890         if (!midi_event_is_valid(ev.buffer(), ev.size())) {
891                 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
892                 return;
893         }
894
895         if (ev.is_note_on()) {
896                 NotePtr note(new Note<Time>(ev.channel(), ev.time(), Time(), ev.note(), ev.velocity()));
897                 append_note_on_unlocked (note, evid);
898         } else if (ev.is_note_off()) {
899                 NotePtr note(new Note<Time>(ev.channel(), ev.time(), Time(), ev.note(), ev.velocity()));
900                 /* XXX note: event ID is discarded because we merge the on+off events into
901                    a single note object
902                 */
903                 append_note_off_unlocked (note);
904         } else if (ev.is_sysex()) {
905                 append_sysex_unlocked(ev, evid);
906         } else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
907                 /* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
908                 if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
909                         _bank[ev.channel()] &= ~(0x7f << 7);
910                         _bank[ev.channel()] |= ev.cc_value() << 7;
911                 } else {
912                         _bank[ev.channel()] &= ~0x7f;
913                         _bank[ev.channel()] |= ev.cc_value();
914                 }
915         } else if (ev.is_cc()) {
916                 append_control_unlocked(
917                         Parameter(ev.event_type(), ev.channel(), ev.cc_number()),
918                         ev.time(), ev.cc_value(), evid);
919         } else if (ev.is_pgm_change()) {
920                 /* write a patch change with this program change and any previously set-up bank number */
921                 append_patch_change_unlocked (PatchChange<Time> (ev.time(), ev.channel(), ev.pgm_number(), _bank[ev.channel()]), evid);
922         } else if (ev.is_pitch_bender()) {
923                 append_control_unlocked(
924                         Parameter(ev.event_type(), ev.channel()),
925                         ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
926                                            | (0x7F & ev.pitch_bender_lsb())),
927                         evid);
928         } else if (ev.is_channel_pressure()) {
929                 append_control_unlocked(
930                         Parameter(ev.event_type(), ev.channel()),
931                         ev.time(), ev.channel_pressure(), evid);
932         } else if (!_type_map.type_is_midi(ev.event_type())) {
933                 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
934                 for (size_t i=0; i < ev.size(); ++i) {
935                         printf("%X ", ev.buffer()[i]);
936                 }
937                 printf("\n");
938         } else {
939                 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
940         }
941
942         _edited = true;
943 }
944
945 template<typename Time>
946 void
947 Sequence<Time>::append_note_on_unlocked (NotePtr note, event_id_t evid)
948 {
949         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
950                                                       (int) note->channel(), (int) note->note(),
951                                                       note->time(), (int) note->velocity()));
952         assert(_writing);
953
954         if (note->note() > 127) {
955                 error << string_compose (_("illegal note number (%1) used in Note on event - event will be ignored"), (int)  note->note()) << endmsg;
956                 return;
957         }
958         if (note->channel() >= 16) {
959                 error << string_compose (_("illegal channel number (%1) used in Note on event - event will be ignored"), (int) note->channel()) << endmsg;
960                 return;
961         }
962
963         if (note->id() < 0) {
964                 note->set_id (evid);
965         }
966
967         if (note->velocity() == 0) {
968                 append_note_off_unlocked (note);
969                 return;
970         }
971
972         add_note_unlocked (note);
973
974         #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
975         if (!_percussive) {
976         #endif
977
978                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sustained: Appending active note on %1 channel %2\n",
979                                                               (unsigned)(uint8_t)note->note(), note->channel()));
980                 _write_notes[note->channel()].insert (note);
981
982         #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
983         } else {
984                 DEBUG_TRACE(DEBUG::Sequence, "Percussive: NOT appending active note on\n");
985         }
986         #endif
987
988 }
989
990 template<typename Time>
991 void
992 Sequence<Time>::append_note_off_unlocked (NotePtr note)
993 {
994         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
995                                                       this, (int)note->channel(),
996                                                       (int)note->note(), note->time(), (int)note->velocity()));
997         assert(_writing);
998
999         if (note->note() > 127) {
1000                 error << string_compose (_("illegal note number (%1) used in Note off event - event will be ignored"), (int) note->note()) << endmsg;
1001                 return;
1002         }
1003         if (note->channel() >= 16) {
1004                 error << string_compose (_("illegal channel number (%1) used in Note off event - event will be ignored"), (int) note->channel()) << endmsg;
1005                 return;
1006         }
1007
1008         _edited = true;
1009
1010 #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
1011         if (_percussive) {
1012                 DEBUG_TRACE(DEBUG::Sequence, "Sequence Ignoring note off (percussive mode)\n");
1013                 return;
1014         }
1015 #endif
1016
1017         bool resolved = false;
1018
1019         /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1020            matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1021            whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1022            format.
1023         */
1024
1025         /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1026
1027         for (typename WriteNotes::iterator n = _write_notes[note->channel()].begin(); n != _write_notes[note->channel()].end(); ) {
1028
1029                 typename WriteNotes::iterator tmp = n;
1030                 ++tmp;
1031
1032                 NotePtr nn = *n;
1033                 if (note->note() == nn->note() && nn->channel() == note->channel()) {
1034                         assert(note->time() >= nn->time());
1035
1036                         nn->set_length (note->time() - nn->time());
1037                         nn->set_off_velocity (note->velocity());
1038
1039                         _write_notes[note->channel()].erase(n);
1040                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1041                         resolved = true;
1042                         break;
1043                 }
1044
1045                 n = tmp;
1046         }
1047
1048         if (!resolved) {
1049                 cerr << this << " spurious note off chan " << (int)note->channel()
1050                      << ", note " << (int)note->note() << " @ " << note->time() << endl;
1051         }
1052 }
1053
1054 template<typename Time>
1055 void
1056 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1057 {
1058         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1059                                                       this, _type_map.to_symbol(param), time, value, _controls.size()));
1060         boost::shared_ptr<Control> c = control(param, true);
1061         c->list()->add (time.to_double(), value);
1062         /* XXX control events should use IDs */
1063 }
1064
1065 template<typename Time>
1066 void
1067 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev, event_id_t /* evid */)
1068 {
1069 #ifdef DEBUG_SEQUENCE
1070         cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1071         for (size_t i=0; i < ev.size(); ++i) {
1072                 cerr << int(ev.buffer()[i]) << " ";
1073         } cerr << "]" << endl;
1074 #endif
1075
1076         boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
1077         /* XXX sysex events should use IDs */
1078         _sysexes.insert(event);
1079 }
1080
1081 template<typename Time>
1082 void
1083 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1084 {
1085         PatchChangePtr p (new PatchChange<Time> (ev));
1086
1087         if (p->id() < 0) {
1088                 p->set_id (id);
1089         }
1090
1091         _patch_changes.insert (p);
1092 }
1093
1094 template<typename Time>
1095 void
1096 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1097 {
1098         if (p->id () < 0) {
1099                 p->set_id (Evoral::next_event_id ());
1100         }
1101
1102         _patch_changes.insert (p);
1103 }
1104
1105 template<typename Time>
1106 void
1107 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1108 {
1109         if (s->id () < 0) {
1110                 s->set_id (Evoral::next_event_id ());
1111         }
1112
1113         _sysexes.insert (s);
1114 }
1115
1116 template<typename Time>
1117 bool
1118 Sequence<Time>::contains (const NotePtr& note) const
1119 {
1120         ReadLock lock (read_lock());
1121         return contains_unlocked (note);
1122 }
1123
1124 template<typename Time>
1125 bool
1126 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1127 {
1128         const Pitches& p (pitches (note->channel()));
1129         NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1130
1131         for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1132              i != p.end() && (*i)->note() == note->note(); ++i) {
1133
1134                 if (**i == *note) {
1135                         return true;
1136                 }
1137         }
1138
1139         return false;
1140 }
1141
1142 template<typename Time>
1143 bool
1144 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1145 {
1146         ReadLock lock (read_lock());
1147         return overlaps_unlocked (note, without);
1148 }
1149
1150 template<typename Time>
1151 bool
1152 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1153 {
1154         Time sa = note->time();
1155         Time ea  = note->end_time();
1156
1157         const Pitches& p (pitches (note->channel()));
1158         NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1159
1160         for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1161              i != p.end() && (*i)->note() == note->note(); ++i) {
1162
1163                 if (without && (**i) == *without) {
1164                         continue;
1165                 }
1166
1167                 Time sb = (*i)->time();
1168                 Time eb = (*i)->end_time();
1169
1170                 if (((sb > sa) && (eb <= ea)) ||
1171                     ((eb >= sa) && (eb <= ea)) ||
1172                     ((sb > sa) && (sb <= ea)) ||
1173                     ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1174                         return true;
1175                 }
1176         }
1177
1178         return false;
1179 }
1180
1181 template<typename Time>
1182 void
1183 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1184 {
1185         _notes = n;
1186 }
1187
1188 // CONST iterator implementations (x3)
1189
1190 /** Return the earliest note with time >= t */
1191 template<typename Time>
1192 typename Sequence<Time>::Notes::const_iterator
1193 Sequence<Time>::note_lower_bound (Time t) const
1194 {
1195         NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1196         typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1197         assert(i == _notes.end() || (*i)->time() >= t);
1198         return i;
1199 }
1200
1201 /** Return the earliest patch change with time >= t */
1202 template<typename Time>
1203 typename Sequence<Time>::PatchChanges::const_iterator
1204 Sequence<Time>::patch_change_lower_bound (Time t) const
1205 {
1206         PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1207         typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1208         assert (i == _patch_changes.end() || (*i)->time() >= t);
1209         return i;
1210 }
1211
1212 /** Return the earliest sysex with time >= t */
1213 template<typename Time>
1214 typename Sequence<Time>::SysExes::const_iterator
1215 Sequence<Time>::sysex_lower_bound (Time t) const
1216 {
1217         SysExPtr search (new Event<Time> (0, t));
1218         typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1219         assert (i == _sysexes.end() || (*i)->time() >= t);
1220         return i;
1221 }
1222
1223 // NON-CONST iterator implementations (x3)
1224
1225 /** Return the earliest note with time >= t */
1226 template<typename Time>
1227 typename Sequence<Time>::Notes::iterator
1228 Sequence<Time>::note_lower_bound (Time t)
1229 {
1230         NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1231         typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1232         assert(i == _notes.end() || (*i)->time() >= t);
1233         return i;
1234 }
1235
1236 /** Return the earliest patch change with time >= t */
1237 template<typename Time>
1238 typename Sequence<Time>::PatchChanges::iterator
1239 Sequence<Time>::patch_change_lower_bound (Time t)
1240 {
1241         PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1242         typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1243         assert (i == _patch_changes.end() || (*i)->time() >= t);
1244         return i;
1245 }
1246
1247 /** Return the earliest sysex with time >= t */
1248 template<typename Time>
1249 typename Sequence<Time>::SysExes::iterator
1250 Sequence<Time>::sysex_lower_bound (Time t)
1251 {
1252         SysExPtr search (new Event<Time> (0, t));
1253         typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1254         assert (i == _sysexes.end() || (*i)->time() >= t);
1255         return i;
1256 }
1257
1258 template<typename Time>
1259 void
1260 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1261 {
1262         switch (op) {
1263         case PitchEqual:
1264         case PitchLessThan:
1265         case PitchLessThanOrEqual:
1266         case PitchGreater:
1267         case PitchGreaterThanOrEqual:
1268                 get_notes_by_pitch (n, op, val, chan_mask);
1269                 break;
1270
1271         case VelocityEqual:
1272         case VelocityLessThan:
1273         case VelocityLessThanOrEqual:
1274         case VelocityGreater:
1275         case VelocityGreaterThanOrEqual:
1276                 get_notes_by_velocity (n, op, val, chan_mask);
1277                 break;
1278         }
1279 }
1280
1281 template<typename Time>
1282 void
1283 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1284 {
1285         for (uint8_t c = 0; c < 16; ++c) {
1286
1287                 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1288                         continue;
1289                 }
1290
1291                 const Pitches& p (pitches (c));
1292                 NotePtr search_note(new Note<Time>(0, Time(), Time(), val, 0));
1293                 typename Pitches::const_iterator i;
1294                 switch (op) {
1295                 case PitchEqual:
1296                         i = p.lower_bound (search_note);
1297                         while (i != p.end() && (*i)->note() == val) {
1298                                 n.insert (*i);
1299                         }
1300                         break;
1301                 case PitchLessThan:
1302                         i = p.upper_bound (search_note);
1303                         while (i != p.end() && (*i)->note() < val) {
1304                                 n.insert (*i);
1305                         }
1306                         break;
1307                 case PitchLessThanOrEqual:
1308                         i = p.upper_bound (search_note);
1309                         while (i != p.end() && (*i)->note() <= val) {
1310                                 n.insert (*i);
1311                         }
1312                         break;
1313                 case PitchGreater:
1314                         i = p.lower_bound (search_note);
1315                         while (i != p.end() && (*i)->note() > val) {
1316                                 n.insert (*i);
1317                         }
1318                         break;
1319                 case PitchGreaterThanOrEqual:
1320                         i = p.lower_bound (search_note);
1321                         while (i != p.end() && (*i)->note() >= val) {
1322                                 n.insert (*i);
1323                         }
1324                         break;
1325
1326                 default:
1327                         //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1328                         abort(); /* NOTREACHED*/
1329                 }
1330         }
1331 }
1332
1333 template<typename Time>
1334 void
1335 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1336 {
1337         ReadLock lock (read_lock());
1338
1339         for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1340
1341                 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1342                         continue;
1343                 }
1344
1345                 switch (op) {
1346                 case VelocityEqual:
1347                         if ((*i)->velocity() == val) {
1348                                 n.insert (*i);
1349                         }
1350                         break;
1351                 case VelocityLessThan:
1352                         if ((*i)->velocity() < val) {
1353                                 n.insert (*i);
1354                         }
1355                         break;
1356                 case VelocityLessThanOrEqual:
1357                         if ((*i)->velocity() <= val) {
1358                                 n.insert (*i);
1359                         }
1360                         break;
1361                 case VelocityGreater:
1362                         if ((*i)->velocity() > val) {
1363                                 n.insert (*i);
1364                         }
1365                         break;
1366                 case VelocityGreaterThanOrEqual:
1367                         if ((*i)->velocity() >= val) {
1368                                 n.insert (*i);
1369                         }
1370                         break;
1371                 default:
1372                         // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1373                         abort(); /* NOTREACHED*/
1374
1375                 }
1376         }
1377 }
1378
1379 template<typename Time>
1380 void
1381 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1382 {
1383         _overlap_pitch_resolution = opr;
1384
1385         /* XXX todo: clean up existing overlaps in source data? */
1386 }
1387
1388 template<typename Time>
1389 void
1390 Sequence<Time>::control_list_marked_dirty ()
1391 {
1392         set_edited (true);
1393 }
1394
1395 template<typename Time>
1396 void
1397 Sequence<Time>::dump (ostream& str) const
1398 {
1399         typename Sequence<Time>::const_iterator i;
1400         str << "+++ dump\n";
1401         for (i = begin(); i != end(); ++i) {
1402                 str << *i << endl;
1403         }
1404         str << "--- dump\n";
1405 }
1406
1407 template class Sequence<Evoral::MusicalTime>;
1408
1409 } // namespace Evoral