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