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