1 /* This file is part of Evoral.
2 * Copyright (C) 2008 David Robillard <http://drobilla.net>
3 * Copyright (C) 2000-2008 Paul Davis
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
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.
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
28 #include "evoral/Note.hpp"
31 #include "pbd/compose.h"
32 #include "pbd/error.h"
34 #include "evoral/Control.hpp"
35 #include "evoral/ControlList.hpp"
36 #include "evoral/ControlSet.hpp"
37 #include "evoral/EventSink.hpp"
38 #include "evoral/MIDIParameters.hpp"
39 #include "evoral/Sequence.hpp"
40 #include "evoral/TypeMap.hpp"
41 #include "evoral/midi_util.h"
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.
52 XXX: This is a hack. The time should probably be expressed in
53 seconds rather than beats, and should be configurable etc. etc.
55 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
59 // Read iterator (const_iterator)
61 template<typename Time>
62 Sequence<Time>::const_iterator::const_iterator()
65 , _control_iter(_control_iters.end())
67 _event = boost::shared_ptr< Event<Time> >(new Event<Time>());
70 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
71 template<typename Time>
72 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq, Time t, bool force_discrete, std::set<Evoral::Parameter> const & filtered)
74 , _active_patch_change_message (0)
76 , _is_end((t == DBL_MAX) || seq.empty())
77 , _note_iter(seq.notes().end())
78 , _sysex_iter(seq.sysexes().end())
79 , _patch_change_iter(seq.patch_changes().end())
80 , _control_iter(_control_iters.end())
81 , _force_discrete (force_discrete)
83 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
89 _lock = seq.read_lock();
91 // Find first note which begins at or after t
92 _note_iter = seq.note_lower_bound(t);
94 // Find first sysex event at or after t
95 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
96 i != seq.sysexes().end(); ++i) {
97 if ((*i)->time() >= t) {
102 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
104 // Find first patch event at or after t
105 for (typename Sequence<Time>::PatchChanges::const_iterator i = seq.patch_changes().begin(); i != seq.patch_changes().end(); ++i) {
106 if ((*i)->time() >= t) {
107 _patch_change_iter = i;
111 assert (_patch_change_iter == seq.patch_changes().end() || (*_patch_change_iter)->time() >= t);
113 // Find first control event after t
114 ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
115 _control_iters.reserve(seq._controls.size());
117 size_t earliest_control_index = 0;
118 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
120 if (filtered.find (i->first) != filtered.end()) {
121 /* this parameter is filtered, so don't bother setting up an iterator for it */
125 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
128 if (_force_discrete) {
129 ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t, x, y, true);
131 ret = i->second->list()->rt_safe_earliest_event_unlocked(t, x, y, true);
134 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
135 i->first.id(), i->second->list()->size(), t));
141 if (y < i->first.min() || y > i->first.max()) {
142 cerr << "ERROR: Controller value " << y
143 << " out of range [" << i->first.min() << "," << i->first.max()
144 << "], event ignored" << endl;
148 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
150 const ControlIterator new_iter(i->second->list(), x, y);
151 _control_iters.push_back(new_iter);
153 // Found a new earliest_control
154 if (x < earliest_control.x) {
155 earliest_control = new_iter;
156 earliest_control_index = _control_iters.size() - 1;
162 _control_iter = _control_iters.begin() + earliest_control_index;
163 assert(_control_iter != _control_iters.end());
165 _control_iter = _control_iters.end();
168 // Now find the earliest event overall and point to it
171 if (_note_iter != seq.notes().end()) {
173 earliest_t = (*_note_iter)->time();
176 if (_sysex_iter != seq.sysexes().end()
177 && ((*_sysex_iter)->time() < earliest_t || _type == NIL)) {
179 earliest_t = (*_sysex_iter)->time();
182 if (_patch_change_iter != seq.patch_changes().end() && ((*_patch_change_iter)->time() < earliest_t || _type == NIL)) {
183 _type = PATCH_CHANGE;
184 earliest_t = (*_patch_change_iter)->time ();
187 if (_control_iter != _control_iters.end()
188 && earliest_control.list && earliest_control.x >= t
189 && (earliest_control.x < earliest_t || _type == NIL)) {
191 earliest_t = earliest_control.x;
196 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at note on event @ %1\n", earliest_t));
197 _event = boost::shared_ptr<Event<Time> > (new Event<Time> ((*_note_iter)->on_event(), true));
198 _active_notes.push(*_note_iter);
201 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at sysex event @ %1\n", earliest_t));
202 _event = boost::shared_ptr< Event<Time> >(
203 new Event<Time>(*(*_sysex_iter), true));
206 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at control event @ %1\n", earliest_t));
207 seq.control_to_midi_event(_event, earliest_control);
210 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at patch change event @ %1\n", earliest_t));
211 _event = boost::shared_ptr<Event<Time> > (new Event<Time> ((*_patch_change_iter)->message (_active_patch_change_message), true));
217 if (_type == NIL || !_event || _event->size() == 0) {
218 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at end @ %1\n", t));
222 DEBUG_TRACE (DEBUG::Sequence, string_compose ("New iterator = 0x%1 : 0x%2 @ %3\n",
223 (int)_event->event_type(),
224 (int)((MIDIEvent<Time>*)_event.get())->type(),
227 assert(midi_event_is_valid(_event->buffer(), _event->size()));
232 template<typename Time>
233 Sequence<Time>::const_iterator::~const_iterator()
237 template<typename Time>
239 Sequence<Time>::const_iterator::invalidate()
241 while (!_active_notes.empty()) {
247 _note_iter = _seq->notes().end();
248 _sysex_iter = _seq->sysexes().end();
249 _patch_change_iter = _seq->patch_changes().end();
250 _active_patch_change_message = 0;
252 _control_iter = _control_iters.end();
256 template<typename Time>
257 const typename Sequence<Time>::const_iterator&
258 Sequence<Time>::const_iterator::operator++()
261 throw std::logic_error("Attempt to iterate past end of Sequence");
264 assert(_event && _event->buffer() && _event->size() > 0);
266 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
270 || ev.is_pgm_change()
271 || ev.is_pitch_bender()
272 || ev.is_channel_pressure()
273 || ev.is_sysex()) ) {
274 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
275 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
282 // Increment past current event
290 // Increment current controller iterator
291 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
292 ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
293 _control_iter->x, x, y, false
296 ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
297 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false
300 assert(!ret || x > _control_iter->x);
302 _control_iter->x = x;
303 _control_iter->y = y;
305 _control_iter->list.reset();
306 _control_iter->x = DBL_MAX;
307 _control_iter->y = DBL_MAX;
310 // Find the controller with the next earliest event time
311 _control_iter = _control_iters.begin();
312 for (ControlIterators::iterator i = _control_iters.begin();
313 i != _control_iters.end(); ++i) {
314 if (i->x < _control_iter->x) {
323 ++_active_patch_change_message;
324 if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
325 ++_patch_change_iter;
326 _active_patch_change_message = 0;
333 // Now find the earliest event overall and point to it
335 Time earliest_t = std::numeric_limits<Time>::max();
337 // Next earliest note on
338 if (_note_iter != _seq->notes().end()) {
340 earliest_t = (*_note_iter)->time();
343 // Use the next note off iff it's earlier or the same time as the note on
344 #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
345 // issue 0005121 When in Percussive mode, all note offs go missing, which jams all MIDI instruments that they stop playing
346 // remove this code since it drowns MIDI instruments by stealing all voices and crashes LinuxSampler
347 if (!_seq->percussive() && (!_active_notes.empty())) {
349 if ((!_active_notes.empty())) {
351 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
353 earliest_t = _active_notes.top()->end_time();
357 // Use the next earliest controller iff it's earlier than the note event
358 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
359 if (_type == NIL || _control_iter->x < earliest_t) {
361 earliest_t = _control_iter->x;
365 // Use the next earliest SysEx iff it's earlier than the controller
366 if (_sysex_iter != _seq->sysexes().end()) {
367 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
369 earliest_t = (*_sysex_iter)->time();
373 // Use the next earliest patch change iff it's earlier than the SysEx
374 if (_patch_change_iter != _seq->patch_changes().end()) {
375 if (_type == NIL || (*_patch_change_iter)->time() < earliest_t) {
376 _type = PATCH_CHANGE;
377 earliest_t = (*_patch_change_iter)->time();
381 // Set event to reflect new position
384 // DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
385 *_event = (*_note_iter)->on_event();
386 _active_notes.push(*_note_iter);
389 // DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
390 assert(!_active_notes.empty());
391 *_event = _active_notes.top()->off_event();
395 //DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
396 _seq->control_to_midi_event(_event, *_control_iter);
399 //DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
400 *_event = *(*_sysex_iter);
403 //DEBUG_TRACE(DEBUG::Sequence, "iterator = patch change\n");
404 *_event = (*_patch_change_iter)->message (_active_patch_change_message);
407 //DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
411 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
416 template<typename Time>
418 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
420 if (_seq != other._seq) {
422 } else if (_is_end || other._is_end) {
423 return (_is_end == other._is_end);
424 } else if (_type != other._type) {
427 return (_event == other._event);
431 template<typename Time>
432 typename Sequence<Time>::const_iterator&
433 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
436 _event = other._event;
437 _active_notes = other._active_notes;
439 _is_end = other._is_end;
440 _note_iter = other._note_iter;
441 _sysex_iter = other._sysex_iter;
442 _patch_change_iter = other._patch_change_iter;
443 _control_iters = other._control_iters;
444 _force_discrete = other._force_discrete;
445 _active_patch_change_message = other._active_patch_change_message;
448 _lock = _seq->read_lock();
453 if (other._control_iter == other._control_iters.end()) {
454 _control_iter = _control_iters.end();
456 const size_t index = other._control_iter - other._control_iters.begin();
457 _control_iter = _control_iters.begin() + index;
465 template<typename Time>
466 Sequence<Time>::Sequence(const TypeMap& type_map)
468 , _overlapping_pitches_accepted (true)
469 , _overlap_pitch_resolution (FirstOnFirstOff)
471 , _type_map(type_map)
472 , _end_iter(*this, DBL_MAX, false, std::set<Evoral::Parameter> ())
477 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
478 assert(_end_iter._is_end);
479 assert( ! _end_iter._lock);
481 for (int i = 0; i < 16; ++i) {
486 template<typename Time>
487 Sequence<Time>::Sequence(const Sequence<Time>& other)
490 , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
491 , _overlap_pitch_resolution (other._overlap_pitch_resolution)
493 , _type_map(other._type_map)
494 , _end_iter(*this, DBL_MAX, false, std::set<Evoral::Parameter> ())
495 , _percussive(other._percussive)
496 , _lowest_note(other._lowest_note)
497 , _highest_note(other._highest_note)
499 for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
500 NotePtr n (new Note<Time> (**i));
504 for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
505 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
509 for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
510 PatchChangePtr n (new PatchChange<Time> (**i));
511 _patch_changes.insert (n);
514 for (int i = 0; i < 16; ++i) {
515 _bank[i] = other._bank[i];
518 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
519 assert(_end_iter._is_end);
520 assert(! _end_iter._lock);
523 /** Write the controller event pointed to by \a iter to \a ev.
524 * The buffer of \a ev will be allocated or resized as necessary.
525 * The event_type of \a ev should be set to the expected output type.
526 * \return true on success
528 template<typename Time>
530 Sequence<Time>::control_to_midi_event(
531 boost::shared_ptr< Event<Time> >& ev,
532 const ControlIterator& iter) const
534 assert(iter.list.get());
535 const uint32_t event_type = iter.list->parameter().type();
537 // initialize the event pointer with a new event, if necessary
539 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
542 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
543 ev->set_event_type(_type_map.midi_event_type(midi_type));
545 case MIDI_CMD_CONTROL:
546 assert(iter.list.get());
547 assert(iter.list->parameter().channel() < 16);
548 assert(iter.list->parameter().id() <= INT8_MAX);
549 assert(iter.y <= INT8_MAX);
551 ev->set_time(iter.x);
553 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
554 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
555 ev->buffer()[2] = (uint8_t)iter.y;
558 case MIDI_CMD_PGM_CHANGE:
559 assert(iter.list.get());
560 assert(iter.list->parameter().channel() < 16);
561 assert(iter.y <= INT8_MAX);
563 ev->set_time(iter.x);
565 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
566 ev->buffer()[1] = (uint8_t)iter.y;
569 case MIDI_CMD_BENDER:
570 assert(iter.list.get());
571 assert(iter.list->parameter().channel() < 16);
572 assert(iter.y < (1<<14));
574 ev->set_time(iter.x);
576 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
577 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
578 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
581 case MIDI_CMD_CHANNEL_PRESSURE:
582 assert(iter.list.get());
583 assert(iter.list->parameter().channel() < 16);
584 assert(iter.y <= INT8_MAX);
586 ev->set_time(iter.x);
588 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
589 ev->buffer()[1] = (uint8_t)iter.y;
599 /** Clear all events from the model.
601 template<typename Time>
603 Sequence<Time>::clear()
605 WriteLock lock(write_lock());
607 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
608 li->second->list()->clear();
611 /** Begin a write of events to the model.
613 * If \a mode is Sustained, complete notes with length are constructed as note
614 * on/off events are received. Otherwise (Percussive), only note on events are
615 * stored; note off events are discarded entirely and all contained notes will
618 template<typename Time>
620 Sequence<Time>::start_write()
622 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
623 WriteLock lock(write_lock());
625 for (int i = 0; i < 16; ++i) {
626 _write_notes[i].clear();
630 /** Finish a write of events to the model.
632 * If \a delete_stuck is true and the current mode is Sustained, note on events
633 * that were never resolved with a corresonding note off will be deleted.
634 * Otherwise they will remain as notes with length 0.
636 template<typename Time>
638 Sequence<Time>::end_write (StuckNoteOption option, Time when)
640 WriteLock lock(write_lock());
646 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
648 #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
651 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
652 typename Notes::iterator next = n;
655 if ((*n)->length() == 0) {
659 case DeleteStuckNotes:
660 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
663 case ResolveStuckNotes:
664 if (when <= (*n)->time()) {
665 cerr << "WARNING: Stuck note resolution - end time @ "
666 << when << " is before note on: " << (**n) << endl;
669 (*n)->set_length (when - (*n)->time());
670 cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
678 #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
682 for (int i = 0; i < 16; ++i) {
683 _write_notes[i].clear();
690 template<typename Time>
692 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
694 /* This is the core method to add notes to a Sequence
697 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
699 if (resolve_overlaps_unlocked (note, arg)) {
700 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
704 if (note->id() < 0) {
705 note->set_id (Evoral::next_event_id());
708 if (note->note() < _lowest_note)
709 _lowest_note = note->note();
710 if (note->note() > _highest_note)
711 _highest_note = note->note();
713 _notes.insert (note);
714 _pitches[note->channel()].insert (note);
721 template<typename Time>
723 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
726 bool id_matched = false;
728 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
730 /* first try searching for the note using the time index, which is
731 * faster since the container is "indexed" by time. (technically, this
732 * means that lower_bound() can do a binary search rather than linear)
734 * this may not work, for reasons explained below.
737 typename Sequence<Time>::Notes::iterator i;
739 for (i = note_lower_bound(note->time()); i != _notes.end() && musical_time_equal ((*i)->time(), note->time()); ++i) {
743 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
746 if (note->note() == _lowest_note || note->note() == _highest_note) {
751 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
752 if ((*ii)->note() < _lowest_note)
753 _lowest_note = (*ii)->note();
754 if ((*ii)->note() > _highest_note)
755 _highest_note = (*ii)->note();
764 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\ttime-based lookup did not find note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
768 /* if the note's time property was changed in tandem with some
769 * other property as the next operation after it was added to
770 * the sequence, then at the point where we call this to undo
771 * the add, the note we are targetting currently has a
772 * different time property than the one we we passed via
775 * in this scenario, we have no choice other than to linear
776 * search the list of notes and find the note by ID.
779 for (i = _notes.begin(); i != _notes.end(); ++i) {
781 if ((*i)->id() == note->id()) {
783 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\tID-based pass, erasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
786 if (note->note() == _lowest_note || note->note() == _highest_note) {
791 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
792 if ((*ii)->note() < _lowest_note)
793 _lowest_note = (*ii)->note();
794 if ((*ii)->note() > _highest_note)
795 _highest_note = (*ii)->note();
808 Pitches& p (pitches (note->channel()));
810 typename Pitches::iterator j;
812 /* if we had to ID-match above, we can't expect to find it in
813 * pitches via note comparison either. so do another linear
814 * search to locate it. otherwise, we can use the note index
815 * to potentially speed things up.
820 for (j = p.begin(); j != p.end(); ++j) {
821 if ((*j)->id() == note->id()) {
829 /* Now find the same note in the "pitches" list (which indexes
830 * notes by channel+time. We care only about its note number
831 * so the search_note has all other properties unset.
834 NotePtr search_note (new Note<Time>(0, 0, 0, note->note(), 0));
836 for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
839 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
847 warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
853 cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
857 template<typename Time>
859 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
861 typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
863 while (i != _patch_changes.end() && (musical_time_equal ((*i)->time(), p->time()))) {
865 typename Sequence<Time>::PatchChanges::iterator tmp = i;
869 _patch_changes.erase (i);
876 template<typename Time>
878 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
880 typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
881 while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
883 typename Sequence<Time>::SysExes::iterator tmp = i;
894 /** Append \a ev to model. NOT realtime safe.
896 * The timestamp of event is expected to be relative to
897 * the start of this model (t=0) and MUST be monotonically increasing
898 * and MUST be >= the latest event currently in the model.
900 template<typename Time>
902 Sequence<Time>::append(const Event<Time>& event, event_id_t evid)
904 WriteLock lock(write_lock());
906 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
908 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
911 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
912 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
916 if (ev.is_note_on()) {
917 NotePtr note(new Note<Time>(ev.channel(), ev.time(), 0, ev.note(), ev.velocity()));
918 append_note_on_unlocked (note, evid);
919 } else if (ev.is_note_off()) {
920 NotePtr note(new Note<Time>(ev.channel(), ev.time(), 0, ev.note(), ev.velocity()));
921 /* XXX note: event ID is discarded because we merge the on+off events into
924 append_note_off_unlocked (note);
925 } else if (ev.is_sysex()) {
926 append_sysex_unlocked(ev, evid);
927 } else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
928 /* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
929 if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
930 _bank[ev.channel()] &= ~(0x7f << 7);
931 _bank[ev.channel()] |= ev.cc_value() << 7;
933 _bank[ev.channel()] &= ~0x7f;
934 _bank[ev.channel()] |= ev.cc_value();
936 } else if (ev.is_cc()) {
937 append_control_unlocked(
938 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
939 ev.time(), ev.cc_value(), evid);
940 } else if (ev.is_pgm_change()) {
941 /* write a patch change with this program change and any previously set-up bank number */
942 append_patch_change_unlocked (PatchChange<Time> (ev.time(), ev.channel(), ev.pgm_number(), _bank[ev.channel()]), evid);
943 } else if (ev.is_pitch_bender()) {
944 append_control_unlocked(
945 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
946 ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
947 | (0x7F & ev.pitch_bender_lsb())),
949 } else if (ev.is_channel_pressure()) {
950 append_control_unlocked(
951 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
952 ev.time(), ev.channel_pressure(), evid);
953 } else if (!_type_map.type_is_midi(ev.event_type())) {
954 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
955 for (size_t i=0; i < ev.size(); ++i) {
956 printf("%X ", ev.buffer()[i]);
960 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
966 template<typename Time>
968 Sequence<Time>::append_note_on_unlocked (NotePtr note, event_id_t evid)
970 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
971 (int) note->channel(), (int) note->note(),
972 note->time(), (int) note->velocity()));
975 if (note->note() > 127) {
976 error << string_compose (_("illegal note number (%1) used in Note on event - event will be ignored"), (int) note->note()) << endmsg;
979 if (note->channel() >= 16) {
980 error << string_compose (_("illegal channel number (%1) used in Note on event - event will be ignored"), (int) note->channel()) << endmsg;
984 if (note->id() < 0) {
988 if (note->velocity() == 0) {
989 append_note_off_unlocked (note);
993 add_note_unlocked (note);
995 #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
999 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sustained: Appending active note on %1 channel %2\n",
1000 (unsigned)(uint8_t)note->note(), note->channel()));
1001 _write_notes[note->channel()].insert (note);
1003 #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
1005 DEBUG_TRACE(DEBUG::Sequence, "Percussive: NOT appending active note on\n");
1011 template<typename Time>
1013 Sequence<Time>::append_note_off_unlocked (NotePtr note)
1015 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
1016 this, (int)note->channel(),
1017 (int)note->note(), note->time(), (int)note->velocity()));
1020 if (note->note() > 127) {
1021 error << string_compose (_("illegal note number (%1) used in Note off event - event will be ignored"), (int) note->note()) << endmsg;
1024 if (note->channel() >= 16) {
1025 error << string_compose (_("illegal channel number (%1) used in Note off event - event will be ignored"), (int) note->channel()) << endmsg;
1031 #ifdef PERCUSSIVE_IGNORE_NOTE_OFFS
1033 DEBUG_TRACE(DEBUG::Sequence, "Sequence Ignoring note off (percussive mode)\n");
1038 bool resolved = false;
1040 /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1041 matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1042 whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1046 /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1048 for (typename WriteNotes::iterator n = _write_notes[note->channel()].begin(); n != _write_notes[note->channel()].end(); ) {
1050 typename WriteNotes::iterator tmp = n;
1054 if (note->note() == nn->note() && nn->channel() == note->channel()) {
1055 assert(note->time() >= nn->time());
1057 nn->set_length (note->time() - nn->time());
1058 nn->set_off_velocity (note->velocity());
1060 _write_notes[note->channel()].erase(n);
1061 DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1070 cerr << this << " spurious note off chan " << (int)note->channel()
1071 << ", note " << (int)note->note() << " @ " << note->time() << endl;
1075 template<typename Time>
1077 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1079 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1080 this, _type_map.to_symbol(param), time, value, _controls.size()));
1081 boost::shared_ptr<Control> c = control(param, true);
1082 c->list()->add (time, value);
1083 /* XXX control events should use IDs */
1086 template<typename Time>
1088 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev, event_id_t /* evid */)
1090 #ifdef DEBUG_SEQUENCE
1091 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1092 for (size_t i=0; i < ev.size(); ++i) {
1093 cerr << int(ev.buffer()[i]) << " ";
1094 } cerr << "]" << endl;
1097 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
1098 /* XXX sysex events should use IDs */
1099 _sysexes.insert(event);
1102 template<typename Time>
1104 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1106 PatchChangePtr p (new PatchChange<Time> (ev));
1112 _patch_changes.insert (p);
1115 template<typename Time>
1117 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1120 p->set_id (Evoral::next_event_id ());
1123 _patch_changes.insert (p);
1126 template<typename Time>
1128 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1131 s->set_id (Evoral::next_event_id ());
1134 _sysexes.insert (s);
1137 template<typename Time>
1139 Sequence<Time>::contains (const NotePtr& note) const
1141 ReadLock lock (read_lock());
1142 return contains_unlocked (note);
1145 template<typename Time>
1147 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1149 const Pitches& p (pitches (note->channel()));
1150 NotePtr search_note(new Note<Time>(0, 0, 0, note->note()));
1152 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1153 i != p.end() && (*i)->note() == note->note(); ++i) {
1163 template<typename Time>
1165 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1167 ReadLock lock (read_lock());
1168 return overlaps_unlocked (note, without);
1171 template<typename Time>
1173 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1175 Time sa = note->time();
1176 Time ea = note->end_time();
1178 const Pitches& p (pitches (note->channel()));
1179 NotePtr search_note(new Note<Time>(0, 0, 0, note->note()));
1181 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1182 i != p.end() && (*i)->note() == note->note(); ++i) {
1184 if (without && (**i) == *without) {
1188 Time sb = (*i)->time();
1189 Time eb = (*i)->end_time();
1191 if (((sb > sa) && (eb <= ea)) ||
1192 ((eb >= sa) && (eb <= ea)) ||
1193 ((sb > sa) && (sb <= ea)) ||
1194 ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1202 template<typename Time>
1204 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1209 // CONST iterator implementations (x3)
1211 /** Return the earliest note with time >= t */
1212 template<typename Time>
1213 typename Sequence<Time>::Notes::const_iterator
1214 Sequence<Time>::note_lower_bound (Time t) const
1216 NotePtr search_note(new Note<Time>(0, t, 0, 0, 0));
1217 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1218 assert(i == _notes.end() || (*i)->time() >= t);
1222 /** Return the earliest patch change with time >= t */
1223 template<typename Time>
1224 typename Sequence<Time>::PatchChanges::const_iterator
1225 Sequence<Time>::patch_change_lower_bound (Time t) const
1227 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1228 typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1229 assert (i == _patch_changes.end() || musical_time_greater_or_equal_to ((*i)->time(), t));
1233 /** Return the earliest sysex with time >= t */
1234 template<typename Time>
1235 typename Sequence<Time>::SysExes::const_iterator
1236 Sequence<Time>::sysex_lower_bound (Time t) const
1238 SysExPtr search (new Event<Time> (0, t));
1239 typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1240 assert (i == _sysexes.end() || (*i)->time() >= t);
1244 // NON-CONST iterator implementations (x3)
1246 /** Return the earliest note with time >= t */
1247 template<typename Time>
1248 typename Sequence<Time>::Notes::iterator
1249 Sequence<Time>::note_lower_bound (Time t)
1251 NotePtr search_note(new Note<Time>(0, t, 0, 0, 0));
1252 typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1253 assert(i == _notes.end() || (*i)->time() >= t);
1257 /** Return the earliest patch change with time >= t */
1258 template<typename Time>
1259 typename Sequence<Time>::PatchChanges::iterator
1260 Sequence<Time>::patch_change_lower_bound (Time t)
1262 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1263 typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1264 assert (i == _patch_changes.end() || musical_time_greater_or_equal_to ((*i)->time(), t));
1268 /** Return the earliest sysex with time >= t */
1269 template<typename Time>
1270 typename Sequence<Time>::SysExes::iterator
1271 Sequence<Time>::sysex_lower_bound (Time t)
1273 SysExPtr search (new Event<Time> (0, t));
1274 typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1275 assert (i == _sysexes.end() || (*i)->time() >= t);
1279 template<typename Time>
1281 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1286 case PitchLessThanOrEqual:
1288 case PitchGreaterThanOrEqual:
1289 get_notes_by_pitch (n, op, val, chan_mask);
1293 case VelocityLessThan:
1294 case VelocityLessThanOrEqual:
1295 case VelocityGreater:
1296 case VelocityGreaterThanOrEqual:
1297 get_notes_by_velocity (n, op, val, chan_mask);
1302 template<typename Time>
1304 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1306 for (uint8_t c = 0; c < 16; ++c) {
1308 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1312 const Pitches& p (pitches (c));
1313 NotePtr search_note(new Note<Time>(0, 0, 0, val, 0));
1314 typename Pitches::const_iterator i;
1317 i = p.lower_bound (search_note);
1318 while (i != p.end() && (*i)->note() == val) {
1323 i = p.upper_bound (search_note);
1324 while (i != p.end() && (*i)->note() < val) {
1328 case PitchLessThanOrEqual:
1329 i = p.upper_bound (search_note);
1330 while (i != p.end() && (*i)->note() <= val) {
1335 i = p.lower_bound (search_note);
1336 while (i != p.end() && (*i)->note() > val) {
1340 case PitchGreaterThanOrEqual:
1341 i = p.lower_bound (search_note);
1342 while (i != p.end() && (*i)->note() >= val) {
1348 //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1355 template<typename Time>
1357 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1359 ReadLock lock (read_lock());
1361 for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1363 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1369 if ((*i)->velocity() == val) {
1373 case VelocityLessThan:
1374 if ((*i)->velocity() < val) {
1378 case VelocityLessThanOrEqual:
1379 if ((*i)->velocity() <= val) {
1383 case VelocityGreater:
1384 if ((*i)->velocity() > val) {
1388 case VelocityGreaterThanOrEqual:
1389 if ((*i)->velocity() >= val) {
1394 // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1402 template<typename Time>
1404 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1406 _overlap_pitch_resolution = opr;
1408 /* XXX todo: clean up existing overlaps in source data? */
1411 template<typename Time>
1413 Sequence<Time>::control_list_marked_dirty ()
1418 template<typename Time>
1420 Sequence<Time>::dump (ostream& str) const
1422 typename Sequence<Time>::const_iterator i;
1423 str << "+++ dump\n";
1424 for (i = begin(); i != end(); ++i) {
1427 str << "--- dump\n";
1430 template class Sequence<Evoral::MusicalTime>;
1432 } // namespace Evoral