2 * Copyright (C) 2008-2012 Hans Baier <hansfbaier@googlemail.com>
3 * Copyright (C) 2008-2016 David Robillard <d@drobilla.net>
4 * Copyright (C) 2008-2017 Paul Davis <paul@linuxaudiosystems.com>
5 * Copyright (C) 2009-2011 Carl Hetherington <carl@carlh.net>
6 * Copyright (C) 2014-2019 Robin Gareus <robin@gareus.org>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
32 #include "evoral/Note.h"
35 #include "pbd/compose.h"
36 #include "pbd/error.h"
38 #include "temporal/beats.h"
40 #include "evoral/Control.h"
41 #include "evoral/ControlList.h"
42 #include "evoral/ControlSet.h"
43 #include "evoral/EventSink.h"
44 #include "evoral/ParameterDescriptor.h"
45 #include "evoral/Sequence.h"
46 #include "evoral/TypeMap.h"
47 #include "evoral/midi_util.h"
54 /** Minimum time between MIDI outputs from a single interpolated controller,
55 expressed in beats. This is to limit the rate at which MIDI messages
56 are generated. It is only applied to interpolated controllers.
58 XXX: This is a hack. The time should probably be expressed in
59 seconds rather than beats, and should be configurable etc. etc.
61 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
65 // Read iterator (const_iterator)
67 template<typename Time>
68 Sequence<Time>::const_iterator::const_iterator()
70 , _event(boost::shared_ptr< Event<Time> >(new Event<Time>()))
71 , _active_patch_change_message (NO_EVENT)
74 , _control_iter(_control_iters.end())
75 , _force_discrete(false)
79 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
80 template<typename Time>
81 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq,
84 const std::set<Evoral::Parameter>& filtered,
85 const std::set<WeakNotePtr>* active_notes)
87 , _active_patch_change_message (0)
89 , _is_end((t == DBL_MAX) || seq.empty())
90 , _note_iter(seq.notes().end())
91 , _sysex_iter(seq.sysexes().end())
92 , _patch_change_iter(seq.patch_changes().end())
93 , _control_iter(_control_iters.end())
94 , _force_discrete (force_discrete)
96 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
102 _lock = seq.read_lock();
104 // Add currently active notes, if given
106 for (typename std::set<WeakNotePtr>::const_iterator i = active_notes->begin();
107 i != active_notes->end(); ++i) {
108 NotePtr note = i->lock();
109 if (note && note->time() <= t && note->end_time() > t) {
110 _active_notes.push(note);
115 // Find first note which begins at or after t
116 _note_iter = seq.note_lower_bound(t);
118 // Find first sysex event at or after t
119 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
120 i != seq.sysexes().end(); ++i) {
121 if ((*i)->time() >= t) {
126 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
128 // Find first patch event at or after t
129 for (typename Sequence<Time>::PatchChanges::const_iterator i = seq.patch_changes().begin(); i != seq.patch_changes().end(); ++i) {
130 if ((*i)->time() >= t) {
131 _patch_change_iter = i;
135 assert (_patch_change_iter == seq.patch_changes().end() || (*_patch_change_iter)->time() >= t);
137 // Find first control event after t
138 _control_iters.reserve(seq._controls.size());
140 size_t earliest_control_index = 0;
141 double earliest_control_x = DBL_MAX;
142 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
144 if (filtered.find (i->first) != filtered.end()) {
145 /* this parameter is filtered, so don't bother setting up an iterator for it */
149 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
152 if (_force_discrete || i->second->list()->interpolation() == ControlList::Discrete) {
153 ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t.to_double(), x, y, true);
155 ret = i->second->list()->rt_safe_earliest_event_unlocked(t.to_double(), x, y, true);
158 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
159 i->first.id(), i->second->list()->size(), t));
165 const ParameterDescriptor& desc = seq.type_map().descriptor(i->first);
166 if (y < desc.lower || y > desc.upper) {
167 cerr << "ERROR: Controller value " << y
168 << " out of range [" << desc.lower << "," << desc.upper
169 << "], event ignored" << endl;
173 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
175 const ControlIterator new_iter(i->second->list(), x, y);
176 _control_iters.push_back(new_iter);
178 // Found a new earliest_control
179 if (x < earliest_control_x) {
180 earliest_control_x = x;
181 earliest_control_index = _control_iters.size() - 1;
187 _control_iter = _control_iters.begin() + earliest_control_index;
188 assert(_control_iter != _control_iters.end());
189 assert(_control_iter->list);
191 _control_iter = _control_iters.end();
194 // Choose the earliest event overall to point to
197 // Allocate a new event for storing the current event in MIDI format
198 _event = boost::shared_ptr< Event<Time> >(
199 new Event<Time>(NO_EVENT, Time(), 4, NULL, true));
201 // Set event from chosen sub-iterator
205 DEBUG_TRACE(DEBUG::Sequence,
206 string_compose("Starting at end @ %1\n", t));
208 DEBUG_TRACE(DEBUG::Sequence,
209 string_compose("Starting at type 0x%1 : 0x%2 @ %3\n",
210 (int)_event->event_type(),
211 (int)_event->buffer()[0],
216 template<typename Time>
218 Sequence<Time>::const_iterator::invalidate(std::set< boost::weak_ptr< Note<Time> > >* notes)
220 while (!_active_notes.empty()) {
222 notes->insert(_active_notes.top());
229 _note_iter = _seq->notes().end();
230 _sysex_iter = _seq->sysexes().end();
231 _patch_change_iter = _seq->patch_changes().end();
232 _active_patch_change_message = 0;
234 _control_iters.clear();
235 _control_iter = _control_iters.end();
239 template<typename Time>
241 Sequence<Time>::const_iterator::choose_next(Time earliest_t)
245 // Next earliest note on, if any
246 if (_note_iter != _seq->notes().end()) {
248 earliest_t = (*_note_iter)->time();
251 /* Use the next earliest patch change iff it is earlier or coincident with the note-on.
252 * A patch-change with the same time-stamp applies to the concurrent note-on */
253 if (_patch_change_iter != _seq->patch_changes().end()) {
254 if (_type == NIL || (*_patch_change_iter)->time() <= earliest_t) {
255 _type = PATCH_CHANGE;
256 earliest_t = (*_patch_change_iter)->time();
260 /* Use the next earliest controller iff it's earlier or coincident with the note-on
261 * or patch-change. Bank-select (CC0, CC32) needs to be sent before the PGM. */
262 if (_control_iter != _control_iters.end() &&
263 _control_iter->list && _control_iter->x != DBL_MAX) {
264 if (_type == NIL || _control_iter->x <= earliest_t.to_double()) {
266 earliest_t = Time(_control_iter->x);
270 /* .. but prefer to send any Note-off first */
271 if ((!_active_notes.empty())) {
272 if (_type == NIL || _active_notes.top()->end_time().to_double() <= earliest_t.to_double()) {
274 earliest_t = _active_notes.top()->end_time();
278 /* SysEx is last, always sent after any other concurrent 3 byte event */
279 if (_sysex_iter != _seq->sysexes().end()) {
280 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
282 earliest_t = (*_sysex_iter)->time();
289 template<typename Time>
291 Sequence<Time>::const_iterator::set_event()
295 DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
296 _event->assign ((*_note_iter)->on_event());
297 _active_notes.push(*_note_iter);
300 DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
301 assert(!_active_notes.empty());
302 _event->assign (_active_notes.top()->off_event());
303 // We don't pop the active note until we increment past it
306 DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
307 _event->assign (*(*_sysex_iter));
310 DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
311 _seq->control_to_midi_event(_event, *_control_iter);
314 DEBUG_TRACE(DEBUG::Sequence, "iterator = program change\n");
315 _event->assign ((*_patch_change_iter)->message (_active_patch_change_message));
322 if (_type == NIL || !_event || _event->size() == 0) {
323 DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
327 assert(midi_event_is_valid(_event->buffer(), _event->size()));
331 template<typename Time>
332 const typename Sequence<Time>::const_iterator&
333 Sequence<Time>::const_iterator::operator++()
336 throw std::logic_error("Attempt to iterate past end of Sequence");
339 assert(_event && _event->buffer() && _event->size() > 0);
341 const Event<Time>& ev = *_event.get();
345 || ev.is_pgm_change()
346 || ev.is_pitch_bender()
347 || ev.is_channel_pressure()
348 || ev.is_poly_pressure()
349 || ev.is_sysex()) ) {
350 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
351 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
358 // Increment past current event
367 // Increment current controller iterator
368 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
369 ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
370 _control_iter->x, x, y, false);
372 ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
373 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false);
375 assert(!ret || x > _control_iter->x);
377 _control_iter->x = x;
378 _control_iter->y = y;
380 _control_iter->list.reset();
381 _control_iter->x = DBL_MAX;
382 _control_iter->y = DBL_MAX;
385 // Find the controller with the next earliest event time
386 _control_iter = _control_iters.begin();
387 for (ControlIterators::iterator i = _control_iters.begin();
388 i != _control_iters.end(); ++i) {
389 if (i->x < _control_iter->x) {
398 ++_active_patch_change_message;
399 if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
400 ++_patch_change_iter;
401 _active_patch_change_message = 0;
408 // Choose the earliest event overall to point to
409 choose_next(std::numeric_limits<Time>::max());
411 // Set event from chosen sub-iterator
414 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
419 template<typename Time>
421 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
423 if (_seq != other._seq) {
425 } else if (_is_end || other._is_end) {
426 return (_is_end == other._is_end);
427 } else if (_type != other._type) {
430 return (_event == other._event);
434 template<typename Time>
435 typename Sequence<Time>::const_iterator&
436 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
439 _event = other._event;
440 _active_notes = other._active_notes;
442 _is_end = other._is_end;
443 _note_iter = other._note_iter;
444 _sysex_iter = other._sysex_iter;
445 _patch_change_iter = other._patch_change_iter;
446 _control_iters = other._control_iters;
447 _force_discrete = other._force_discrete;
448 _active_patch_change_message = other._active_patch_change_message;
451 _lock = _seq->read_lock();
456 if (other._control_iter == other._control_iters.end()) {
457 _control_iter = _control_iters.end();
459 const size_t index = other._control_iter - other._control_iters.begin();
460 _control_iter = _control_iters.begin() + index;
468 template<typename Time>
469 Sequence<Time>::Sequence(const TypeMap& type_map)
471 , _overlapping_pitches_accepted (true)
472 , _overlap_pitch_resolution (FirstOnFirstOff)
474 , _type_map(type_map)
475 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
480 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
481 assert(_end_iter._is_end);
482 assert( ! _end_iter._lock);
484 for (int i = 0; i < 16; ++i) {
489 template<typename Time>
490 Sequence<Time>::Sequence(const Sequence<Time>& other)
493 , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
494 , _overlap_pitch_resolution (other._overlap_pitch_resolution)
496 , _type_map(other._type_map)
497 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
498 , _percussive(other._percussive)
499 , _lowest_note(other._lowest_note)
500 , _highest_note(other._highest_note)
502 for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
503 NotePtr n (new Note<Time> (**i));
507 for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
508 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
512 for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
513 PatchChangePtr n (new PatchChange<Time> (**i));
514 _patch_changes.insert (n);
517 for (int i = 0; i < 16; ++i) {
518 _bank[i] = other._bank[i];
521 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
522 assert(_end_iter._is_end);
523 assert(! _end_iter._lock);
526 /** Write the controller event pointed to by `iter` to `ev`.
527 * The buffer of `ev` will be allocated or resized as necessary.
528 * \return true on success
530 template<typename Time>
532 Sequence<Time>::control_to_midi_event(
533 boost::shared_ptr< Event<Time> >& ev,
534 const ControlIterator& iter) const
536 assert(iter.list.get());
538 // initialize the event pointer with a new event, if necessary
540 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(NO_EVENT, Time(), 3, NULL, true));
543 const uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
544 ev->set_event_type(MIDI_EVENT);
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);
553 ev->set_time(Time(iter.x));
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;
560 case MIDI_CMD_PGM_CHANGE:
561 assert(iter.list.get());
562 assert(iter.list->parameter().channel() < 16);
563 assert(iter.y <= INT8_MAX);
565 ev->set_time(Time(iter.x));
567 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
568 ev->buffer()[1] = (uint8_t)iter.y;
571 case MIDI_CMD_BENDER:
572 assert(iter.list.get());
573 assert(iter.list->parameter().channel() < 16);
574 assert(iter.y < (1<<14));
576 ev->set_time(Time(iter.x));
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
583 case MIDI_CMD_NOTE_PRESSURE:
584 assert(iter.list.get());
585 assert(iter.list->parameter().channel() < 16);
586 assert(iter.list->parameter().id() <= INT8_MAX);
587 assert(iter.y <= INT8_MAX);
589 ev->set_time(Time(iter.x));
591 ev->buffer()[0] = MIDI_CMD_NOTE_PRESSURE + iter.list->parameter().channel();
592 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
593 ev->buffer()[2] = (uint8_t)iter.y;
596 case MIDI_CMD_CHANNEL_PRESSURE:
597 assert(iter.list.get());
598 assert(iter.list->parameter().channel() < 16);
599 assert(iter.y <= INT8_MAX);
601 ev->set_time(Time(iter.x));
603 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
604 ev->buffer()[1] = (uint8_t)iter.y;
614 /** Clear all events from the model.
616 template<typename Time>
618 Sequence<Time>::clear()
620 WriteLock lock(write_lock());
622 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
623 li->second->list()->clear();
626 /** Begin a write of events to the model.
628 * If \a mode is Sustained, complete notes with length are constructed as note
629 * on/off events are received. Otherwise (Percussive), only note on events are
630 * stored; note off events are discarded entirely and all contained notes will
633 template<typename Time>
635 Sequence<Time>::start_write()
637 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
638 WriteLock lock(write_lock());
640 for (int i = 0; i < 16; ++i) {
641 _write_notes[i].clear();
645 /** Finish a write of events to the model.
647 * If \a delete_stuck is true and the current mode is Sustained, note on events
648 * that were never resolved with a corresonding note off will be deleted.
649 * Otherwise they will remain as notes with length 0.
651 template<typename Time>
653 Sequence<Time>::end_write (StuckNoteOption option, Time when)
655 WriteLock lock(write_lock());
661 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
663 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
664 typename Notes::iterator next = n;
667 if (!(*n)->length()) {
671 case DeleteStuckNotes:
672 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
675 case ResolveStuckNotes:
676 if (when <= (*n)->time()) {
677 cerr << "WARNING: Stuck note resolution - end time @ "
678 << when << " is before note on: " << (**n) << endl;
681 (*n)->set_length (when - (*n)->time());
682 cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
691 for (int i = 0; i < 16; ++i) {
692 _write_notes[i].clear();
699 template<typename Time>
701 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
703 /* This is the core method to add notes to a Sequence
706 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
708 if (resolve_overlaps_unlocked (note, arg)) {
709 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
713 if (note->id() < 0) {
714 note->set_id (Evoral::next_event_id());
717 if (note->note() < _lowest_note)
718 _lowest_note = note->note();
719 if (note->note() > _highest_note)
720 _highest_note = note->note();
722 _notes.insert (note);
723 _pitches[note->channel()].insert (note);
730 template<typename Time>
732 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
735 bool id_matched = false;
737 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
739 /* first try searching for the note using the time index, which is
740 * faster since the container is "indexed" by time. (technically, this
741 * means that lower_bound() can do a binary search rather than linear)
743 * this may not work, for reasons explained below.
746 typename Sequence<Time>::Notes::iterator i;
748 for (i = note_lower_bound(note->time()); i != _notes.end() && (*i)->time() == note->time(); ++i) {
752 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
755 if (note->note() == _lowest_note || note->note() == _highest_note) {
760 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
761 if ((*ii)->note() < _lowest_note)
762 _lowest_note = (*ii)->note();
763 if ((*ii)->note() > _highest_note)
764 _highest_note = (*ii)->note();
773 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\ttime-based lookup did not find note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
777 /* if the note's time property was changed in tandem with some
778 * other property as the next operation after it was added to
779 * the sequence, then at the point where we call this to undo
780 * the add, the note we are targetting currently has a
781 * different time property than the one we we passed via
784 * in this scenario, we have no choice other than to linear
785 * search the list of notes and find the note by ID.
788 for (i = _notes.begin(); i != _notes.end(); ++i) {
790 if ((*i)->id() == note->id()) {
792 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\tID-based pass, erasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
795 if (note->note() == _lowest_note || note->note() == _highest_note) {
800 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
801 if ((*ii)->note() < _lowest_note)
802 _lowest_note = (*ii)->note();
803 if ((*ii)->note() > _highest_note)
804 _highest_note = (*ii)->note();
817 Pitches& p (pitches (note->channel()));
819 typename Pitches::iterator j;
821 /* if we had to ID-match above, we can't expect to find it in
822 * pitches via note comparison either. so do another linear
823 * search to locate it. otherwise, we can use the note index
824 * to potentially speed things up.
829 for (j = p.begin(); j != p.end(); ++j) {
830 if ((*j)->id() == note->id()) {
838 /* Now find the same note in the "pitches" list (which indexes
839 * notes by channel+time. We care only about its note number
840 * so the search_note has all other properties unset.
843 NotePtr search_note (new Note<Time>(0, Time(), Time(), note->note(), 0));
845 for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
848 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
856 warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
862 cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
866 template<typename Time>
868 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
870 typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
872 while (i != _patch_changes.end() && ((*i)->time() == p->time())) {
874 typename Sequence<Time>::PatchChanges::iterator tmp = i;
878 _patch_changes.erase (i);
885 template<typename Time>
887 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
889 typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
890 while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
892 typename Sequence<Time>::SysExes::iterator tmp = i;
903 /** Append \a ev to model. NOT realtime safe.
905 * The timestamp of event is expected to be relative to
906 * the start of this model (t=0) and MUST be monotonically increasing
907 * and MUST be >= the latest event currently in the model.
909 template<typename Time>
911 Sequence<Time>::append(const Event<Time>& ev, event_id_t evid)
913 WriteLock lock(write_lock());
915 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
918 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
919 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
923 if (ev.is_note_on() && ev.velocity() > 0) {
924 append_note_on_unlocked (ev, evid);
925 } else if (ev.is_note_off() || (ev.is_note_on() && ev.velocity() == 0)) {
926 /* XXX note: event ID is discarded because we merge the on+off events into
929 append_note_off_unlocked (ev);
930 } else if (ev.is_sysex()) {
931 append_sysex_unlocked(ev, evid);
932 } else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
933 /* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
934 if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
935 _bank[ev.channel()] &= ~(0x7f << 7);
936 _bank[ev.channel()] |= ev.cc_value() << 7;
938 _bank[ev.channel()] &= ~0x7f;
939 _bank[ev.channel()] |= ev.cc_value();
941 } else if (ev.is_cc()) {
942 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
943 append_control_unlocked(
944 Parameter(ptype, ev.channel(), ev.cc_number()),
945 ev.time(), ev.cc_value(), evid);
946 } else if (ev.is_pgm_change()) {
947 /* write a patch change with this program change and any previously set-up bank number */
948 append_patch_change_unlocked (
949 PatchChange<Time> (ev.time(), ev.channel(),
950 ev.pgm_number(), _bank[ev.channel()]), evid);
951 } else if (ev.is_pitch_bender()) {
952 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
953 append_control_unlocked(
954 Parameter(ptype, ev.channel()),
955 ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
956 | (0x7F & ev.pitch_bender_lsb())),
958 } else if (ev.is_poly_pressure()) {
959 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
960 append_control_unlocked (Parameter (ptype, ev.channel(), ev.poly_note()), ev.time(), ev.poly_pressure(), evid);
961 } else if (ev.is_channel_pressure()) {
962 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
963 append_control_unlocked(
964 Parameter(ptype, ev.channel()),
965 ev.time(), ev.channel_pressure(), evid);
966 } else if (!_type_map.type_is_midi(ev.event_type())) {
967 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
968 for (size_t i=0; i < ev.size(); ++i) {
969 printf("%X ", ev.buffer()[i]);
973 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
979 template<typename Time>
981 Sequence<Time>::append_note_on_unlocked (const Event<Time>& ev, event_id_t evid)
983 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
984 (int)ev.channel(), (int)ev.note(),
985 ev.time(), (int)ev.velocity()));
988 if (ev.note() > 127) {
989 error << string_compose (_("invalid note on number (%1) ignored"), (int) ev.note()) << endmsg;
991 } else if (ev.channel() >= 16) {
992 error << string_compose (_("invalid note on channel (%1) ignored"), (int) ev.channel()) << endmsg;
994 } else if (ev.velocity() == 0) {
995 // Note on with velocity 0 handled as note off by caller
996 error << string_compose (_("invalid note on velocity (%1) ignored"), (int) ev.velocity()) << endmsg;
1000 NotePtr note(new Note<Time>(ev.channel(), ev.time(), Time(), ev.note(), ev.velocity()));
1001 note->set_id (evid);
1003 add_note_unlocked (note);
1005 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Appending active note on %1 channel %2\n",
1006 (unsigned)(uint8_t)note->note(), note->channel()));
1007 _write_notes[note->channel()].insert (note);
1011 template<typename Time>
1013 Sequence<Time>::append_note_off_unlocked (const Event<Time>& ev)
1015 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
1016 this, (int)ev.channel(),
1017 (int)ev.note(), ev.time(), (int)ev.velocity()));
1020 if (ev.note() > 127) {
1021 error << string_compose (_("invalid note off number (%1) ignored"), (int) ev.note()) << endmsg;
1023 } else if (ev.channel() >= 16) {
1024 error << string_compose (_("invalid note off channel (%1) ignored"), (int) ev.channel()) << endmsg;
1030 bool resolved = false;
1032 /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1033 matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1034 whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1038 /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1040 for (typename WriteNotes::iterator n = _write_notes[ev.channel()].begin(); n != _write_notes[ev.channel()].end(); ) {
1042 typename WriteNotes::iterator tmp = n;
1046 if (ev.note() == nn->note() && nn->channel() == ev.channel()) {
1047 assert(ev.time() >= nn->time());
1049 nn->set_length (ev.time() - nn->time());
1050 nn->set_off_velocity (ev.velocity());
1052 _write_notes[ev.channel()].erase(n);
1053 DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1062 cerr << this << " spurious note off chan " << (int)ev.channel()
1063 << ", note " << (int)ev.note() << " @ " << ev.time() << endl;
1067 template<typename Time>
1069 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1071 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1072 this, _type_map.to_symbol(param), time, value, _controls.size()));
1073 boost::shared_ptr<Control> c = control(param, true);
1074 c->list()->add (time.to_double(), value, true, false);
1075 /* XXX control events should use IDs */
1078 template<typename Time>
1080 Sequence<Time>::append_sysex_unlocked(const Event<Time>& ev, event_id_t /* evid */)
1082 #ifdef DEBUG_SEQUENCE
1083 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1084 for (size_t i=0; i < ev.size(); ++i) {
1085 cerr << int(ev.buffer()[i]) << " ";
1086 } cerr << "]" << endl;
1089 boost::shared_ptr< Event<Time> > event(new Event<Time>(ev, true));
1090 /* XXX sysex events should use IDs */
1091 _sysexes.insert(event);
1094 template<typename Time>
1096 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1098 PatchChangePtr p (new PatchChange<Time> (ev));
1104 _patch_changes.insert (p);
1107 template<typename Time>
1109 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1112 p->set_id (Evoral::next_event_id ());
1115 _patch_changes.insert (p);
1118 template<typename Time>
1120 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1123 s->set_id (Evoral::next_event_id ());
1126 _sysexes.insert (s);
1129 template<typename Time>
1131 Sequence<Time>::contains (const NotePtr& note) const
1133 ReadLock lock (read_lock());
1134 return contains_unlocked (note);
1137 template<typename Time>
1139 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1141 const Pitches& p (pitches (note->channel()));
1142 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1144 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1145 i != p.end() && (*i)->note() == note->note(); ++i) {
1155 template<typename Time>
1157 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1159 ReadLock lock (read_lock());
1160 return overlaps_unlocked (note, without);
1163 template<typename Time>
1165 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1167 Time sa = note->time();
1168 Time ea = note->end_time();
1170 const Pitches& p (pitches (note->channel()));
1171 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1173 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1174 i != p.end() && (*i)->note() == note->note(); ++i) {
1176 if (without && (**i) == *without) {
1180 Time sb = (*i)->time();
1181 Time eb = (*i)->end_time();
1183 if (((sb > sa) && (eb <= ea)) ||
1184 ((eb >= sa) && (eb <= ea)) ||
1185 ((sb > sa) && (sb <= ea)) ||
1186 ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1194 template<typename Time>
1196 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1201 // CONST iterator implementations (x3)
1203 /** Return the earliest note with time >= t */
1204 template<typename Time>
1205 typename Sequence<Time>::Notes::const_iterator
1206 Sequence<Time>::note_lower_bound (Time t) const
1208 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1209 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1210 assert(i == _notes.end() || (*i)->time() >= t);
1214 /** Return the earliest patch change with time >= t */
1215 template<typename Time>
1216 typename Sequence<Time>::PatchChanges::const_iterator
1217 Sequence<Time>::patch_change_lower_bound (Time t) const
1219 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1220 typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1221 assert (i == _patch_changes.end() || (*i)->time() >= t);
1225 /** Return the earliest sysex with time >= t */
1226 template<typename Time>
1227 typename Sequence<Time>::SysExes::const_iterator
1228 Sequence<Time>::sysex_lower_bound (Time t) const
1230 SysExPtr search (new Event<Time> (NO_EVENT, t));
1231 typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1232 assert (i == _sysexes.end() || (*i)->time() >= t);
1236 // NON-CONST iterator implementations (x3)
1238 /** Return the earliest note with time >= t */
1239 template<typename Time>
1240 typename Sequence<Time>::Notes::iterator
1241 Sequence<Time>::note_lower_bound (Time t)
1243 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1244 typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1245 assert(i == _notes.end() || (*i)->time() >= t);
1249 /** Return the earliest patch change with time >= t */
1250 template<typename Time>
1251 typename Sequence<Time>::PatchChanges::iterator
1252 Sequence<Time>::patch_change_lower_bound (Time t)
1254 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1255 typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1256 assert (i == _patch_changes.end() || (*i)->time() >= t);
1260 /** Return the earliest sysex with time >= t */
1261 template<typename Time>
1262 typename Sequence<Time>::SysExes::iterator
1263 Sequence<Time>::sysex_lower_bound (Time t)
1265 SysExPtr search (new Event<Time> (NO_EVENT, t));
1266 typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1267 assert (i == _sysexes.end() || (*i)->time() >= t);
1271 template<typename Time>
1273 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1278 case PitchLessThanOrEqual:
1280 case PitchGreaterThanOrEqual:
1281 get_notes_by_pitch (n, op, val, chan_mask);
1285 case VelocityLessThan:
1286 case VelocityLessThanOrEqual:
1287 case VelocityGreater:
1288 case VelocityGreaterThanOrEqual:
1289 get_notes_by_velocity (n, op, val, chan_mask);
1294 template<typename Time>
1296 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1298 for (uint8_t c = 0; c < 16; ++c) {
1300 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1304 const Pitches& p (pitches (c));
1305 NotePtr search_note(new Note<Time>(0, Time(), Time(), val, 0));
1306 typename Pitches::const_iterator i;
1309 i = p.lower_bound (search_note);
1310 while (i != p.end() && (*i)->note() == val) {
1315 i = p.upper_bound (search_note);
1316 while (i != p.end() && (*i)->note() < val) {
1320 case PitchLessThanOrEqual:
1321 i = p.upper_bound (search_note);
1322 while (i != p.end() && (*i)->note() <= val) {
1327 i = p.lower_bound (search_note);
1328 while (i != p.end() && (*i)->note() > val) {
1332 case PitchGreaterThanOrEqual:
1333 i = p.lower_bound (search_note);
1334 while (i != p.end() && (*i)->note() >= val) {
1340 //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1341 abort(); /* NOTREACHED*/
1346 template<typename Time>
1348 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1350 ReadLock lock (read_lock());
1352 for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1354 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1360 if ((*i)->velocity() == val) {
1364 case VelocityLessThan:
1365 if ((*i)->velocity() < val) {
1369 case VelocityLessThanOrEqual:
1370 if ((*i)->velocity() <= val) {
1374 case VelocityGreater:
1375 if ((*i)->velocity() > val) {
1379 case VelocityGreaterThanOrEqual:
1380 if ((*i)->velocity() >= val) {
1385 // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1386 abort(); /* NOTREACHED*/
1392 template<typename Time>
1394 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1396 _overlap_pitch_resolution = opr;
1398 /* XXX todo: clean up existing overlaps in source data? */
1401 template<typename Time>
1403 Sequence<Time>::control_list_marked_dirty ()
1408 template<typename Time>
1410 Sequence<Time>::dump (ostream& str) const
1412 typename Sequence<Time>::const_iterator i;
1413 str << "+++ dump\n";
1414 for (i = begin(); i != end(); ++i) {
1417 str << "--- dump\n";
1420 template class Sequence<Temporal::Beats>;
1422 } // namespace Evoral