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