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 "temporal/beats.h"
36 #include "evoral/Control.hpp"
37 #include "evoral/ControlList.hpp"
38 #include "evoral/ControlSet.hpp"
39 #include "evoral/EventSink.hpp"
40 #include "evoral/ParameterDescriptor.hpp"
41 #include "evoral/Sequence.hpp"
42 #include "evoral/TypeMap.hpp"
43 #include "evoral/midi_util.h"
50 /** Minimum time between MIDI outputs from a single interpolated controller,
51 expressed in beats. This is to limit the rate at which MIDI messages
52 are generated. It is only applied to interpolated controllers.
54 XXX: This is a hack. The time should probably be expressed in
55 seconds rather than beats, and should be configurable etc. etc.
57 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
61 // Read iterator (const_iterator)
63 template<typename Time>
64 Sequence<Time>::const_iterator::const_iterator()
66 , _event(boost::shared_ptr< Event<Time> >(new Event<Time>()))
67 , _active_patch_change_message (NO_EVENT)
70 , _control_iter(_control_iters.end())
71 , _force_discrete(false)
75 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
76 template<typename Time>
77 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq,
80 const std::set<Evoral::Parameter>& filtered,
81 const std::set<WeakNotePtr>* active_notes)
83 , _active_patch_change_message (0)
85 , _is_end((t == DBL_MAX) || seq.empty())
86 , _note_iter(seq.notes().end())
87 , _sysex_iter(seq.sysexes().end())
88 , _patch_change_iter(seq.patch_changes().end())
89 , _control_iter(_control_iters.end())
90 , _force_discrete (force_discrete)
92 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
98 _lock = seq.read_lock();
100 // Add currently active notes, if given
102 for (typename std::set<WeakNotePtr>::const_iterator i = active_notes->begin();
103 i != active_notes->end(); ++i) {
104 NotePtr note = i->lock();
105 if (note && note->time() <= t && note->end_time() > t) {
106 _active_notes.push(note);
111 // Find first note which begins at or after t
112 _note_iter = seq.note_lower_bound(t);
114 // Find first sysex event at or after t
115 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
116 i != seq.sysexes().end(); ++i) {
117 if ((*i)->time() >= t) {
122 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
124 // Find first patch event at or after t
125 for (typename Sequence<Time>::PatchChanges::const_iterator i = seq.patch_changes().begin(); i != seq.patch_changes().end(); ++i) {
126 if ((*i)->time() >= t) {
127 _patch_change_iter = i;
131 assert (_patch_change_iter == seq.patch_changes().end() || (*_patch_change_iter)->time() >= t);
133 // Find first control event after t
134 _control_iters.reserve(seq._controls.size());
136 size_t earliest_control_index = 0;
137 double earliest_control_x = DBL_MAX;
138 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
140 if (filtered.find (i->first) != filtered.end()) {
141 /* this parameter is filtered, so don't bother setting up an iterator for it */
145 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
148 if (_force_discrete || i->second->list()->interpolation() == ControlList::Discrete) {
149 ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t.to_double(), x, y, true);
151 ret = i->second->list()->rt_safe_earliest_event_unlocked(t.to_double(), x, y, true);
154 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
155 i->first.id(), i->second->list()->size(), t));
161 const ParameterDescriptor& desc = seq.type_map().descriptor(i->first);
162 if (y < desc.lower || y > desc.upper) {
163 cerr << "ERROR: Controller value " << y
164 << " out of range [" << desc.lower << "," << desc.upper
165 << "], event ignored" << endl;
169 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
171 const ControlIterator new_iter(i->second->list(), x, y);
172 _control_iters.push_back(new_iter);
174 // Found a new earliest_control
175 if (x < earliest_control_x) {
176 earliest_control_x = x;
177 earliest_control_index = _control_iters.size() - 1;
183 _control_iter = _control_iters.begin() + earliest_control_index;
184 assert(_control_iter != _control_iters.end());
185 assert(_control_iter->list);
187 _control_iter = _control_iters.end();
190 // Choose the earliest event overall to point to
193 // Allocate a new event for storing the current event in MIDI format
194 _event = boost::shared_ptr< Event<Time> >(
195 new Event<Time>(NO_EVENT, Time(), 4, NULL, true));
197 // Set event from chosen sub-iterator
201 DEBUG_TRACE(DEBUG::Sequence,
202 string_compose("Starting at end @ %1\n", t));
204 DEBUG_TRACE(DEBUG::Sequence,
205 string_compose("Starting at type 0x%1 : 0x%2 @ %3\n",
206 (int)_event->event_type(),
207 (int)_event->buffer()[0],
212 template<typename Time>
214 Sequence<Time>::const_iterator::invalidate(std::set< boost::weak_ptr< Note<Time> > >* notes)
216 while (!_active_notes.empty()) {
218 notes->insert(_active_notes.top());
225 _note_iter = _seq->notes().end();
226 _sysex_iter = _seq->sysexes().end();
227 _patch_change_iter = _seq->patch_changes().end();
228 _active_patch_change_message = 0;
230 _control_iters.clear();
231 _control_iter = _control_iters.end();
235 template<typename Time>
237 Sequence<Time>::const_iterator::choose_next(Time earliest_t)
241 // Next earliest note on
242 if (_note_iter != _seq->notes().end()) {
244 earliest_t = (*_note_iter)->time();
247 // Use the next note off iff it's earlier or the same time as the note on
248 if ((!_active_notes.empty())) {
249 if (_type == NIL || _active_notes.top()->end_time().to_double() <= earliest_t.to_double()) {
251 earliest_t = _active_notes.top()->end_time();
255 // Use the next earliest controller iff it's earlier than the note event
256 if (_control_iter != _control_iters.end() &&
257 _control_iter->list && _control_iter->x != DBL_MAX) {
258 if (_type == NIL || _control_iter->x < earliest_t.to_double()) {
260 earliest_t = Time(_control_iter->x);
264 // Use the next earliest SysEx iff it's earlier than the controller
265 if (_sysex_iter != _seq->sysexes().end()) {
266 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
268 earliest_t = (*_sysex_iter)->time();
272 // Use the next earliest patch change iff it's earlier than the SysEx
273 if (_patch_change_iter != _seq->patch_changes().end()) {
274 if (_type == NIL || (*_patch_change_iter)->time() < earliest_t) {
275 _type = PATCH_CHANGE;
276 earliest_t = (*_patch_change_iter)->time();
282 template<typename Time>
284 Sequence<Time>::const_iterator::set_event()
288 DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
289 _event->assign ((*_note_iter)->on_event());
290 _active_notes.push(*_note_iter);
293 DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
294 assert(!_active_notes.empty());
295 _event->assign (_active_notes.top()->off_event());
296 // We don't pop the active note until we increment past it
299 DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
300 _event->assign (*(*_sysex_iter));
303 DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
304 _seq->control_to_midi_event(_event, *_control_iter);
307 DEBUG_TRACE(DEBUG::Sequence, "iterator = program change\n");
308 _event->assign ((*_patch_change_iter)->message (_active_patch_change_message));
315 if (_type == NIL || !_event || _event->size() == 0) {
316 DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
320 assert(midi_event_is_valid(_event->buffer(), _event->size()));
324 template<typename Time>
325 const typename Sequence<Time>::const_iterator&
326 Sequence<Time>::const_iterator::operator++()
329 throw std::logic_error("Attempt to iterate past end of Sequence");
332 assert(_event && _event->buffer() && _event->size() > 0);
334 const Event<Time>& ev = *_event.get();
338 || ev.is_pgm_change()
339 || ev.is_pitch_bender()
340 || ev.is_channel_pressure()
341 || ev.is_poly_pressure()
342 || ev.is_sysex()) ) {
343 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
344 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
351 // Increment past current event
360 // Increment current controller iterator
361 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
362 ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
363 _control_iter->x, x, y, false);
365 ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
366 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false);
368 assert(!ret || x > _control_iter->x);
370 _control_iter->x = x;
371 _control_iter->y = y;
373 _control_iter->list.reset();
374 _control_iter->x = DBL_MAX;
375 _control_iter->y = DBL_MAX;
378 // Find the controller with the next earliest event time
379 _control_iter = _control_iters.begin();
380 for (ControlIterators::iterator i = _control_iters.begin();
381 i != _control_iters.end(); ++i) {
382 if (i->x < _control_iter->x) {
391 ++_active_patch_change_message;
392 if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
393 ++_patch_change_iter;
394 _active_patch_change_message = 0;
401 // Choose the earliest event overall to point to
402 choose_next(std::numeric_limits<Time>::max());
404 // Set event from chosen sub-iterator
407 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
412 template<typename Time>
414 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
416 if (_seq != other._seq) {
418 } else if (_is_end || other._is_end) {
419 return (_is_end == other._is_end);
420 } else if (_type != other._type) {
423 return (_event == other._event);
427 template<typename Time>
428 typename Sequence<Time>::const_iterator&
429 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
432 _event = other._event;
433 _active_notes = other._active_notes;
435 _is_end = other._is_end;
436 _note_iter = other._note_iter;
437 _sysex_iter = other._sysex_iter;
438 _patch_change_iter = other._patch_change_iter;
439 _control_iters = other._control_iters;
440 _force_discrete = other._force_discrete;
441 _active_patch_change_message = other._active_patch_change_message;
444 _lock = _seq->read_lock();
449 if (other._control_iter == other._control_iters.end()) {
450 _control_iter = _control_iters.end();
452 const size_t index = other._control_iter - other._control_iters.begin();
453 _control_iter = _control_iters.begin() + index;
461 template<typename Time>
462 Sequence<Time>::Sequence(const TypeMap& type_map)
464 , _overlapping_pitches_accepted (true)
465 , _overlap_pitch_resolution (FirstOnFirstOff)
467 , _type_map(type_map)
468 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
473 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
474 assert(_end_iter._is_end);
475 assert( ! _end_iter._lock);
477 for (int i = 0; i < 16; ++i) {
482 template<typename Time>
483 Sequence<Time>::Sequence(const Sequence<Time>& other)
486 , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
487 , _overlap_pitch_resolution (other._overlap_pitch_resolution)
489 , _type_map(other._type_map)
490 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
491 , _percussive(other._percussive)
492 , _lowest_note(other._lowest_note)
493 , _highest_note(other._highest_note)
495 for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
496 NotePtr n (new Note<Time> (**i));
500 for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
501 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
505 for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
506 PatchChangePtr n (new PatchChange<Time> (**i));
507 _patch_changes.insert (n);
510 for (int i = 0; i < 16; ++i) {
511 _bank[i] = other._bank[i];
514 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
515 assert(_end_iter._is_end);
516 assert(! _end_iter._lock);
519 /** Write the controller event pointed to by `iter` to `ev`.
520 * The buffer of `ev` will be allocated or resized as necessary.
521 * \return true on success
523 template<typename Time>
525 Sequence<Time>::control_to_midi_event(
526 boost::shared_ptr< Event<Time> >& ev,
527 const ControlIterator& iter) const
529 assert(iter.list.get());
531 // initialize the event pointer with a new event, if necessary
533 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(NO_EVENT, Time(), 3, NULL, true));
536 const uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
537 ev->set_event_type(MIDI_EVENT);
540 case MIDI_CMD_CONTROL:
541 assert(iter.list.get());
542 assert(iter.list->parameter().channel() < 16);
543 assert(iter.list->parameter().id() <= INT8_MAX);
544 assert(iter.y <= INT8_MAX);
546 ev->set_time(Time(iter.x));
548 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
549 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
550 ev->buffer()[2] = (uint8_t)iter.y;
553 case MIDI_CMD_PGM_CHANGE:
554 assert(iter.list.get());
555 assert(iter.list->parameter().channel() < 16);
556 assert(iter.y <= INT8_MAX);
558 ev->set_time(Time(iter.x));
560 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
561 ev->buffer()[1] = (uint8_t)iter.y;
564 case MIDI_CMD_BENDER:
565 assert(iter.list.get());
566 assert(iter.list->parameter().channel() < 16);
567 assert(iter.y < (1<<14));
569 ev->set_time(Time(iter.x));
571 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
572 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
573 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
576 case MIDI_CMD_NOTE_PRESSURE:
577 assert(iter.list.get());
578 assert(iter.list->parameter().channel() < 16);
579 assert(iter.list->parameter().id() <= INT8_MAX);
580 assert(iter.y <= INT8_MAX);
582 ev->set_time(Time(iter.x));
584 ev->buffer()[0] = MIDI_CMD_NOTE_PRESSURE + iter.list->parameter().channel();
585 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
586 ev->buffer()[2] = (uint8_t)iter.y;
589 case MIDI_CMD_CHANNEL_PRESSURE:
590 assert(iter.list.get());
591 assert(iter.list->parameter().channel() < 16);
592 assert(iter.y <= INT8_MAX);
594 ev->set_time(Time(iter.x));
596 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
597 ev->buffer()[1] = (uint8_t)iter.y;
607 /** Clear all events from the model.
609 template<typename Time>
611 Sequence<Time>::clear()
613 WriteLock lock(write_lock());
615 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
616 li->second->list()->clear();
619 /** Begin a write of events to the model.
621 * If \a mode is Sustained, complete notes with length are constructed as note
622 * on/off events are received. Otherwise (Percussive), only note on events are
623 * stored; note off events are discarded entirely and all contained notes will
626 template<typename Time>
628 Sequence<Time>::start_write()
630 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
631 WriteLock lock(write_lock());
633 for (int i = 0; i < 16; ++i) {
634 _write_notes[i].clear();
638 /** Finish a write of events to the model.
640 * If \a delete_stuck is true and the current mode is Sustained, note on events
641 * that were never resolved with a corresonding note off will be deleted.
642 * Otherwise they will remain as notes with length 0.
644 template<typename Time>
646 Sequence<Time>::end_write (StuckNoteOption option, Time when)
648 WriteLock lock(write_lock());
654 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
656 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
657 typename Notes::iterator next = n;
660 if (!(*n)->length()) {
664 case DeleteStuckNotes:
665 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
668 case ResolveStuckNotes:
669 if (when <= (*n)->time()) {
670 cerr << "WARNING: Stuck note resolution - end time @ "
671 << when << " is before note on: " << (**n) << endl;
674 (*n)->set_length (when - (*n)->time());
675 cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
684 for (int i = 0; i < 16; ++i) {
685 _write_notes[i].clear();
692 template<typename Time>
694 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
696 /* This is the core method to add notes to a Sequence
699 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
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()));
706 if (note->id() < 0) {
707 note->set_id (Evoral::next_event_id());
710 if (note->note() < _lowest_note)
711 _lowest_note = note->note();
712 if (note->note() > _highest_note)
713 _highest_note = note->note();
715 _notes.insert (note);
716 _pitches[note->channel()].insert (note);
723 template<typename Time>
725 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
728 bool id_matched = false;
730 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
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)
736 * this may not work, for reasons explained below.
739 typename Sequence<Time>::Notes::iterator i;
741 for (i = note_lower_bound(note->time()); i != _notes.end() && (*i)->time() == note->time(); ++i) {
745 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
748 if (note->note() == _lowest_note || note->note() == _highest_note) {
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();
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()));
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
777 * in this scenario, we have no choice other than to linear
778 * search the list of notes and find the note by ID.
781 for (i = _notes.begin(); i != _notes.end(); ++i) {
783 if ((*i)->id() == note->id()) {
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()));
788 if (note->note() == _lowest_note || note->note() == _highest_note) {
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();
810 Pitches& p (pitches (note->channel()));
812 typename Pitches::iterator j;
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.
822 for (j = p.begin(); j != p.end(); ++j) {
823 if ((*j)->id() == note->id()) {
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.
836 NotePtr search_note (new Note<Time>(0, Time(), Time(), note->note(), 0));
838 for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
841 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
849 warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
855 cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
859 template<typename Time>
861 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
863 typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
865 while (i != _patch_changes.end() && ((*i)->time() == p->time())) {
867 typename Sequence<Time>::PatchChanges::iterator tmp = i;
871 _patch_changes.erase (i);
878 template<typename Time>
880 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
882 typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
883 while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
885 typename Sequence<Time>::SysExes::iterator tmp = i;
896 /** Append \a ev to model. NOT realtime safe.
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.
902 template<typename Time>
904 Sequence<Time>::append(const Event<Time>& ev, event_id_t evid)
906 WriteLock lock(write_lock());
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() && ev.velocity() > 0) {
917 append_note_on_unlocked (ev, evid);
918 } else if (ev.is_note_off() || (ev.is_note_on() && ev.velocity() == 0)) {
919 /* XXX note: event ID is discarded because we merge the on+off events into
922 append_note_off_unlocked (ev);
923 } else if (ev.is_sysex()) {
924 append_sysex_unlocked(ev, evid);
925 } else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
926 /* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
927 if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
928 _bank[ev.channel()] &= ~(0x7f << 7);
929 _bank[ev.channel()] |= ev.cc_value() << 7;
931 _bank[ev.channel()] &= ~0x7f;
932 _bank[ev.channel()] |= ev.cc_value();
934 } else if (ev.is_cc()) {
935 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
936 append_control_unlocked(
937 Parameter(ptype, ev.channel(), ev.cc_number()),
938 ev.time(), ev.cc_value(), evid);
939 } else if (ev.is_pgm_change()) {
940 /* write a patch change with this program change and any previously set-up bank number */
941 append_patch_change_unlocked (
942 PatchChange<Time> (ev.time(), ev.channel(),
943 ev.pgm_number(), _bank[ev.channel()]), evid);
944 } else if (ev.is_pitch_bender()) {
945 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
946 append_control_unlocked(
947 Parameter(ptype, ev.channel()),
948 ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
949 | (0x7F & ev.pitch_bender_lsb())),
951 } else if (ev.is_poly_pressure()) {
952 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
953 append_control_unlocked (Parameter (ptype, ev.channel(), ev.poly_note()), ev.time(), ev.poly_pressure(), evid);
954 } else if (ev.is_channel_pressure()) {
955 const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
956 append_control_unlocked(
957 Parameter(ptype, ev.channel()),
958 ev.time(), ev.channel_pressure(), evid);
959 } else if (!_type_map.type_is_midi(ev.event_type())) {
960 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
961 for (size_t i=0; i < ev.size(); ++i) {
962 printf("%X ", ev.buffer()[i]);
966 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
972 template<typename Time>
974 Sequence<Time>::append_note_on_unlocked (const Event<Time>& ev, event_id_t evid)
976 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
977 (int)ev.channel(), (int)ev.note(),
978 ev.time(), (int)ev.velocity()));
981 if (ev.note() > 127) {
982 error << string_compose (_("invalid note on number (%1) ignored"), (int) ev.note()) << endmsg;
984 } else if (ev.channel() >= 16) {
985 error << string_compose (_("invalid note on channel (%1) ignored"), (int) ev.channel()) << endmsg;
987 } else if (ev.velocity() == 0) {
988 // Note on with velocity 0 handled as note off by caller
989 error << string_compose (_("invalid note on velocity (%1) ignored"), (int) ev.velocity()) << endmsg;
993 NotePtr note(new Note<Time>(ev.channel(), ev.time(), Time(), ev.note(), ev.velocity()));
996 add_note_unlocked (note);
998 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Appending active note on %1 channel %2\n",
999 (unsigned)(uint8_t)note->note(), note->channel()));
1000 _write_notes[note->channel()].insert (note);
1004 template<typename Time>
1006 Sequence<Time>::append_note_off_unlocked (const Event<Time>& ev)
1008 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
1009 this, (int)ev.channel(),
1010 (int)ev.note(), ev.time(), (int)ev.velocity()));
1013 if (ev.note() > 127) {
1014 error << string_compose (_("invalid note off number (%1) ignored"), (int) ev.note()) << endmsg;
1016 } else if (ev.channel() >= 16) {
1017 error << string_compose (_("invalid note off channel (%1) ignored"), (int) ev.channel()) << endmsg;
1023 bool resolved = false;
1025 /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1026 matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1027 whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1031 /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1033 for (typename WriteNotes::iterator n = _write_notes[ev.channel()].begin(); n != _write_notes[ev.channel()].end(); ) {
1035 typename WriteNotes::iterator tmp = n;
1039 if (ev.note() == nn->note() && nn->channel() == ev.channel()) {
1040 assert(ev.time() >= nn->time());
1042 nn->set_length (ev.time() - nn->time());
1043 nn->set_off_velocity (ev.velocity());
1045 _write_notes[ev.channel()].erase(n);
1046 DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1055 cerr << this << " spurious note off chan " << (int)ev.channel()
1056 << ", note " << (int)ev.note() << " @ " << ev.time() << endl;
1060 template<typename Time>
1062 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1064 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1065 this, _type_map.to_symbol(param), time, value, _controls.size()));
1066 boost::shared_ptr<Control> c = control(param, true);
1067 c->list()->add (time.to_double(), value, true, false);
1068 /* XXX control events should use IDs */
1071 template<typename Time>
1073 Sequence<Time>::append_sysex_unlocked(const Event<Time>& ev, event_id_t /* evid */)
1075 #ifdef DEBUG_SEQUENCE
1076 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1077 for (size_t i=0; i < ev.size(); ++i) {
1078 cerr << int(ev.buffer()[i]) << " ";
1079 } cerr << "]" << endl;
1082 boost::shared_ptr< Event<Time> > event(new Event<Time>(ev, true));
1083 /* XXX sysex events should use IDs */
1084 _sysexes.insert(event);
1087 template<typename Time>
1089 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1091 PatchChangePtr p (new PatchChange<Time> (ev));
1097 _patch_changes.insert (p);
1100 template<typename Time>
1102 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1105 p->set_id (Evoral::next_event_id ());
1108 _patch_changes.insert (p);
1111 template<typename Time>
1113 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1116 s->set_id (Evoral::next_event_id ());
1119 _sysexes.insert (s);
1122 template<typename Time>
1124 Sequence<Time>::contains (const NotePtr& note) const
1126 ReadLock lock (read_lock());
1127 return contains_unlocked (note);
1130 template<typename Time>
1132 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1134 const Pitches& p (pitches (note->channel()));
1135 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1137 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1138 i != p.end() && (*i)->note() == note->note(); ++i) {
1148 template<typename Time>
1150 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1152 ReadLock lock (read_lock());
1153 return overlaps_unlocked (note, without);
1156 template<typename Time>
1158 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1160 Time sa = note->time();
1161 Time ea = note->end_time();
1163 const Pitches& p (pitches (note->channel()));
1164 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1166 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1167 i != p.end() && (*i)->note() == note->note(); ++i) {
1169 if (without && (**i) == *without) {
1173 Time sb = (*i)->time();
1174 Time eb = (*i)->end_time();
1176 if (((sb > sa) && (eb <= ea)) ||
1177 ((eb >= sa) && (eb <= ea)) ||
1178 ((sb > sa) && (sb <= ea)) ||
1179 ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1187 template<typename Time>
1189 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1194 // CONST iterator implementations (x3)
1196 /** Return the earliest note with time >= t */
1197 template<typename Time>
1198 typename Sequence<Time>::Notes::const_iterator
1199 Sequence<Time>::note_lower_bound (Time t) const
1201 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1202 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1203 assert(i == _notes.end() || (*i)->time() >= t);
1207 /** Return the earliest patch change with time >= t */
1208 template<typename Time>
1209 typename Sequence<Time>::PatchChanges::const_iterator
1210 Sequence<Time>::patch_change_lower_bound (Time t) const
1212 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1213 typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1214 assert (i == _patch_changes.end() || (*i)->time() >= t);
1218 /** Return the earliest sysex with time >= t */
1219 template<typename Time>
1220 typename Sequence<Time>::SysExes::const_iterator
1221 Sequence<Time>::sysex_lower_bound (Time t) const
1223 SysExPtr search (new Event<Time> (NO_EVENT, t));
1224 typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1225 assert (i == _sysexes.end() || (*i)->time() >= t);
1229 // NON-CONST iterator implementations (x3)
1231 /** Return the earliest note with time >= t */
1232 template<typename Time>
1233 typename Sequence<Time>::Notes::iterator
1234 Sequence<Time>::note_lower_bound (Time t)
1236 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1237 typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1238 assert(i == _notes.end() || (*i)->time() >= t);
1242 /** Return the earliest patch change with time >= t */
1243 template<typename Time>
1244 typename Sequence<Time>::PatchChanges::iterator
1245 Sequence<Time>::patch_change_lower_bound (Time t)
1247 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1248 typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1249 assert (i == _patch_changes.end() || (*i)->time() >= t);
1253 /** Return the earliest sysex with time >= t */
1254 template<typename Time>
1255 typename Sequence<Time>::SysExes::iterator
1256 Sequence<Time>::sysex_lower_bound (Time t)
1258 SysExPtr search (new Event<Time> (NO_EVENT, t));
1259 typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1260 assert (i == _sysexes.end() || (*i)->time() >= t);
1264 template<typename Time>
1266 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1271 case PitchLessThanOrEqual:
1273 case PitchGreaterThanOrEqual:
1274 get_notes_by_pitch (n, op, val, chan_mask);
1278 case VelocityLessThan:
1279 case VelocityLessThanOrEqual:
1280 case VelocityGreater:
1281 case VelocityGreaterThanOrEqual:
1282 get_notes_by_velocity (n, op, val, chan_mask);
1287 template<typename Time>
1289 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1291 for (uint8_t c = 0; c < 16; ++c) {
1293 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1297 const Pitches& p (pitches (c));
1298 NotePtr search_note(new Note<Time>(0, Time(), Time(), val, 0));
1299 typename Pitches::const_iterator i;
1302 i = p.lower_bound (search_note);
1303 while (i != p.end() && (*i)->note() == val) {
1308 i = p.upper_bound (search_note);
1309 while (i != p.end() && (*i)->note() < val) {
1313 case PitchLessThanOrEqual:
1314 i = p.upper_bound (search_note);
1315 while (i != p.end() && (*i)->note() <= val) {
1320 i = p.lower_bound (search_note);
1321 while (i != p.end() && (*i)->note() > val) {
1325 case PitchGreaterThanOrEqual:
1326 i = p.lower_bound (search_note);
1327 while (i != p.end() && (*i)->note() >= val) {
1333 //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1334 abort(); /* NOTREACHED*/
1339 template<typename Time>
1341 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1343 ReadLock lock (read_lock());
1345 for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1347 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1353 if ((*i)->velocity() == val) {
1357 case VelocityLessThan:
1358 if ((*i)->velocity() < val) {
1362 case VelocityLessThanOrEqual:
1363 if ((*i)->velocity() <= val) {
1367 case VelocityGreater:
1368 if ((*i)->velocity() > val) {
1372 case VelocityGreaterThanOrEqual:
1373 if ((*i)->velocity() >= val) {
1378 // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1379 abort(); /* NOTREACHED*/
1385 template<typename Time>
1387 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1389 _overlap_pitch_resolution = opr;
1391 /* XXX todo: clean up existing overlaps in source data? */
1394 template<typename Time>
1396 Sequence<Time>::control_list_marked_dirty ()
1401 template<typename Time>
1403 Sequence<Time>::dump (ostream& str) const
1405 typename Sequence<Time>::const_iterator i;
1406 str << "+++ dump\n";
1407 for (i = begin(); i != end(); ++i) {
1410 str << "--- dump\n";
1413 template class Sequence<Temporal::Beats>;
1415 } // namespace Evoral