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