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