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/Beats.hpp"
35 #include "evoral/Control.hpp"
36 #include "evoral/ControlList.hpp"
37 #include "evoral/ControlSet.hpp"
38 #include "evoral/EventSink.hpp"
39 #include "evoral/ParameterDescriptor.hpp"
40 #include "evoral/Sequence.hpp"
41 #include "evoral/TypeMap.hpp"
42 #include "evoral/midi_util.h"
49 /** Minimum time between MIDI outputs from a single interpolated controller,
50 expressed in beats. This is to limit the rate at which MIDI messages
51 are generated. It is only applied to interpolated controllers.
53 XXX: This is a hack. The time should probably be expressed in
54 seconds rather than beats, and should be configurable etc. etc.
56 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
60 // Read iterator (const_iterator)
62 template<typename Time>
63 Sequence<Time>::const_iterator::const_iterator()
65 , _event(boost::shared_ptr< Event<Time> >(new Event<Time>()))
66 , _active_patch_change_message (0)
69 , _control_iter(_control_iters.end())
70 , _force_discrete(false)
74 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
75 template<typename Time>
76 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq,
79 const std::set<Evoral::Parameter>& filtered,
80 const std::set<WeakNotePtr>* active_notes)
82 , _active_patch_change_message (0)
84 , _is_end((t == DBL_MAX) || seq.empty())
85 , _note_iter(seq.notes().end())
86 , _sysex_iter(seq.sysexes().end())
87 , _patch_change_iter(seq.patch_changes().end())
88 , _control_iter(_control_iters.end())
89 , _force_discrete (force_discrete)
91 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
97 _lock = seq.read_lock();
99 // Add currently active notes, if given
101 for (typename std::set<WeakNotePtr>::const_iterator i = active_notes->begin();
102 i != active_notes->end(); ++i) {
103 NotePtr note = i->lock();
104 if (note && note->time() <= t && note->end_time() > t) {
105 _active_notes.push(note);
110 // Find first note which begins at or after t
111 _note_iter = seq.note_lower_bound(t);
113 // Find first sysex event at or after t
114 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
115 i != seq.sysexes().end(); ++i) {
116 if ((*i)->time() >= t) {
121 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
123 // Find first patch event at or after t
124 for (typename Sequence<Time>::PatchChanges::const_iterator i = seq.patch_changes().begin(); i != seq.patch_changes().end(); ++i) {
125 if ((*i)->time() >= t) {
126 _patch_change_iter = i;
130 assert (_patch_change_iter == seq.patch_changes().end() || (*_patch_change_iter)->time() >= t);
132 // Find first control event after t
133 _control_iters.reserve(seq._controls.size());
135 size_t earliest_control_index = 0;
136 double earliest_control_x = DBL_MAX;
137 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
139 if (filtered.find (i->first) != filtered.end()) {
140 /* this parameter is filtered, so don't bother setting up an iterator for it */
144 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
147 if (_force_discrete || i->second->list()->interpolation() == ControlList::Discrete) {
148 ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t.to_double(), x, y, true);
150 ret = i->second->list()->rt_safe_earliest_event_unlocked(t.to_double(), x, y, true);
153 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
154 i->first.id(), i->second->list()->size(), t));
160 const ParameterDescriptor& desc = seq.type_map().descriptor(i->first);
161 if (y < desc.lower || y > desc.upper) {
162 cerr << "ERROR: Controller value " << y
163 << " out of range [" << desc.lower << "," << desc.upper
164 << "], event ignored" << endl;
168 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
170 const ControlIterator new_iter(i->second->list(), x, y);
171 _control_iters.push_back(new_iter);
173 // Found a new earliest_control
174 if (x < earliest_control_x) {
175 earliest_control_x = x;
176 earliest_control_index = _control_iters.size() - 1;
182 _control_iter = _control_iters.begin() + earliest_control_index;
183 assert(_control_iter != _control_iters.end());
184 assert(_control_iter->list);
186 _control_iter = _control_iters.end();
189 // Choose the earliest event overall to point to
192 // Allocate a new event for storing the current event in MIDI format
193 _event = boost::shared_ptr< Event<Time> >(
194 new Event<Time>(0, Time(), 4, NULL, true));
196 // Set event from chosen sub-iterator
200 DEBUG_TRACE(DEBUG::Sequence,
201 string_compose("Starting at end @ %1\n", t));
203 DEBUG_TRACE(DEBUG::Sequence,
204 string_compose("Starting at type 0x%1 : 0x%2 @ %3\n",
205 (int)_event->event_type(),
206 (int)((MIDIEvent<Time>*)_event.get())->type(),
211 template<typename Time>
213 Sequence<Time>::const_iterator::invalidate(std::set< boost::weak_ptr< Note<Time> > >* notes)
215 while (!_active_notes.empty()) {
217 notes->insert(_active_notes.top());
224 _note_iter = _seq->notes().end();
225 _sysex_iter = _seq->sysexes().end();
226 _patch_change_iter = _seq->patch_changes().end();
227 _active_patch_change_message = 0;
229 _control_iters.clear();
230 _control_iter = _control_iters.end();
234 template<typename Time>
236 Sequence<Time>::const_iterator::choose_next(Time earliest_t)
240 // Next earliest note on
241 if (_note_iter != _seq->notes().end()) {
243 earliest_t = (*_note_iter)->time();
246 // Use the next note off iff it's earlier or the same time as the note on
247 if ((!_active_notes.empty())) {
248 if (_type == NIL || _active_notes.top()->end_time().to_double() <= earliest_t.to_double()) {
250 earliest_t = _active_notes.top()->end_time();
254 // Use the next earliest controller iff it's earlier than the note event
255 if (_control_iter != _control_iters.end() &&
256 _control_iter->list && _control_iter->x != DBL_MAX) {
257 if (_type == NIL || _control_iter->x < earliest_t.to_double()) {
259 earliest_t = Time(_control_iter->x);
263 // Use the next earliest SysEx iff it's earlier than the controller
264 if (_sysex_iter != _seq->sysexes().end()) {
265 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
267 earliest_t = (*_sysex_iter)->time();
271 // Use the next earliest patch change iff it's earlier than the SysEx
272 if (_patch_change_iter != _seq->patch_changes().end()) {
273 if (_type == NIL || (*_patch_change_iter)->time() < earliest_t) {
274 _type = PATCH_CHANGE;
275 earliest_t = (*_patch_change_iter)->time();
281 template<typename Time>
283 Sequence<Time>::const_iterator::set_event()
287 DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
288 _event->assign ((*_note_iter)->on_event());
289 _active_notes.push(*_note_iter);
292 DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
293 assert(!_active_notes.empty());
294 _event->assign (_active_notes.top()->off_event());
295 // We don't pop the active note until we increment past it
298 DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
299 _event->assign (*(*_sysex_iter));
302 DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
303 _seq->control_to_midi_event(_event, *_control_iter);
306 DEBUG_TRACE(DEBUG::Sequence, "iterator = program change\n");
307 _event->assign ((*_patch_change_iter)->message (_active_patch_change_message));
314 if (_type == NIL || !_event || _event->size() == 0) {
315 DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
319 assert(midi_event_is_valid(_event->buffer(), _event->size()));
323 template<typename Time>
324 const typename Sequence<Time>::const_iterator&
325 Sequence<Time>::const_iterator::operator++()
328 throw std::logic_error("Attempt to iterate past end of Sequence");
331 assert(_event && _event->buffer() && _event->size() > 0);
333 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
337 || ev.is_pgm_change()
338 || ev.is_pitch_bender()
339 || ev.is_channel_pressure()
340 || ev.is_poly_pressure()
341 || ev.is_sysex()) ) {
342 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
343 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
350 // Increment past current event
359 // Increment current controller iterator
360 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
361 ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
362 _control_iter->x, x, y, false);
364 ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
365 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false);
367 assert(!ret || x > _control_iter->x);
369 _control_iter->x = x;
370 _control_iter->y = y;
372 _control_iter->list.reset();
373 _control_iter->x = DBL_MAX;
374 _control_iter->y = DBL_MAX;
377 // Find the controller with the next earliest event time
378 _control_iter = _control_iters.begin();
379 for (ControlIterators::iterator i = _control_iters.begin();
380 i != _control_iters.end(); ++i) {
381 if (i->x < _control_iter->x) {
390 ++_active_patch_change_message;
391 if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
392 ++_patch_change_iter;
393 _active_patch_change_message = 0;
400 // Choose the earliest event overall to point to
401 choose_next(std::numeric_limits<Time>::max());
403 // Set event from chosen sub-iterator
406 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
411 template<typename Time>
413 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
415 if (_seq != other._seq) {
417 } else if (_is_end || other._is_end) {
418 return (_is_end == other._is_end);
419 } else if (_type != other._type) {
422 return (_event == other._event);
426 template<typename Time>
427 typename Sequence<Time>::const_iterator&
428 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
431 _event = other._event;
432 _active_notes = other._active_notes;
434 _is_end = other._is_end;
435 _note_iter = other._note_iter;
436 _sysex_iter = other._sysex_iter;
437 _patch_change_iter = other._patch_change_iter;
438 _control_iters = other._control_iters;
439 _force_discrete = other._force_discrete;
440 _active_patch_change_message = other._active_patch_change_message;
443 _lock = _seq->read_lock();
448 if (other._control_iter == other._control_iters.end()) {
449 _control_iter = _control_iters.end();
451 const size_t index = other._control_iter - other._control_iters.begin();
452 _control_iter = _control_iters.begin() + index;
460 template<typename Time>
461 Sequence<Time>::Sequence(const TypeMap& type_map)
463 , _overlapping_pitches_accepted (true)
464 , _overlap_pitch_resolution (FirstOnFirstOff)
466 , _type_map(type_map)
467 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
472 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
473 assert(_end_iter._is_end);
474 assert( ! _end_iter._lock);
476 for (int i = 0; i < 16; ++i) {
481 template<typename Time>
482 Sequence<Time>::Sequence(const Sequence<Time>& other)
485 , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
486 , _overlap_pitch_resolution (other._overlap_pitch_resolution)
488 , _type_map(other._type_map)
489 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
490 , _percussive(other._percussive)
491 , _lowest_note(other._lowest_note)
492 , _highest_note(other._highest_note)
494 for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
495 NotePtr n (new Note<Time> (**i));
499 for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
500 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
504 for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
505 PatchChangePtr n (new PatchChange<Time> (**i));
506 _patch_changes.insert (n);
509 for (int i = 0; i < 16; ++i) {
510 _bank[i] = other._bank[i];
513 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
514 assert(_end_iter._is_end);
515 assert(! _end_iter._lock);
518 /** Write the controller event pointed to by \a iter to \a ev.
519 * The buffer of \a ev will be allocated or resized as necessary.
520 * The event_type of \a ev should be set to the expected output type.
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());
530 const uint32_t event_type = iter.list->parameter().type();
532 // initialize the event pointer with a new event, if necessary
534 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, Time(), 3, NULL, true));
537 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
538 ev->set_event_type(_type_map.midi_event_type(midi_type));
541 case MIDI_CMD_CONTROL:
542 assert(iter.list.get());
543 assert(iter.list->parameter().channel() < 16);
544 assert(iter.list->parameter().id() <= INT8_MAX);
545 assert(iter.y <= INT8_MAX);
547 ev->set_time(Time(iter.x));
549 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
550 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
551 ev->buffer()[2] = (uint8_t)iter.y;
554 case MIDI_CMD_PGM_CHANGE:
555 assert(iter.list.get());
556 assert(iter.list->parameter().channel() < 16);
557 assert(iter.y <= INT8_MAX);
559 ev->set_time(Time(iter.x));
561 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
562 ev->buffer()[1] = (uint8_t)iter.y;
565 case MIDI_CMD_BENDER:
566 assert(iter.list.get());
567 assert(iter.list->parameter().channel() < 16);
568 assert(iter.y < (1<<14));
570 ev->set_time(Time(iter.x));
572 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
573 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
574 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
577 case MIDI_CMD_NOTE_PRESSURE:
578 assert(iter.list.get());
579 assert(iter.list->parameter().channel() < 16);
580 assert(iter.list->parameter().id() <= INT8_MAX);
581 assert(iter.y <= INT8_MAX);
583 ev->set_time(Time(iter.x));
585 ev->buffer()[0] = MIDI_CMD_NOTE_PRESSURE + iter.list->parameter().channel();
586 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
587 ev->buffer()[2] = (uint8_t)iter.y;
590 case MIDI_CMD_CHANNEL_PRESSURE:
591 assert(iter.list.get());
592 assert(iter.list->parameter().channel() < 16);
593 assert(iter.y <= INT8_MAX);
595 ev->set_time(Time(iter.x));
597 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
598 ev->buffer()[1] = (uint8_t)iter.y;
608 /** Clear all events from the model.
610 template<typename Time>
612 Sequence<Time>::clear()
614 WriteLock lock(write_lock());
616 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
617 li->second->list()->clear();
620 /** Begin a write of events to the model.
622 * If \a mode is Sustained, complete notes with length are constructed as note
623 * on/off events are received. Otherwise (Percussive), only note on events are
624 * stored; note off events are discarded entirely and all contained notes will
627 template<typename Time>
629 Sequence<Time>::start_write()
631 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
632 WriteLock lock(write_lock());
634 for (int i = 0; i < 16; ++i) {
635 _write_notes[i].clear();
639 /** Finish a write of events to the model.
641 * If \a delete_stuck is true and the current mode is Sustained, note on events
642 * that were never resolved with a corresonding note off will be deleted.
643 * Otherwise they will remain as notes with length 0.
645 template<typename Time>
647 Sequence<Time>::end_write (StuckNoteOption option, Time when)
649 WriteLock lock(write_lock());
655 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
657 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
658 typename Notes::iterator next = n;
661 if (!(*n)->length()) {
665 case DeleteStuckNotes:
666 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
669 case ResolveStuckNotes:
670 if (when <= (*n)->time()) {
671 cerr << "WARNING: Stuck note resolution - end time @ "
672 << when << " is before note on: " << (**n) << endl;
675 (*n)->set_length (when - (*n)->time());
676 cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
685 for (int i = 0; i < 16; ++i) {
686 _write_notes[i].clear();
693 template<typename Time>
695 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
697 /* This is the core method to add notes to a Sequence
700 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
702 if (resolve_overlaps_unlocked (note, arg)) {
703 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
707 if (note->id() < 0) {
708 note->set_id (Evoral::next_event_id());
711 if (note->note() < _lowest_note)
712 _lowest_note = note->note();
713 if (note->note() > _highest_note)
714 _highest_note = note->note();
716 _notes.insert (note);
717 _pitches[note->channel()].insert (note);
724 template<typename Time>
726 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
729 bool id_matched = false;
731 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
733 /* first try searching for the note using the time index, which is
734 * faster since the container is "indexed" by time. (technically, this
735 * means that lower_bound() can do a binary search rather than linear)
737 * this may not work, for reasons explained below.
740 typename Sequence<Time>::Notes::iterator i;
742 for (i = note_lower_bound(note->time()); i != _notes.end() && (*i)->time() == note->time(); ++i) {
746 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
749 if (note->note() == _lowest_note || note->note() == _highest_note) {
754 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
755 if ((*ii)->note() < _lowest_note)
756 _lowest_note = (*ii)->note();
757 if ((*ii)->note() > _highest_note)
758 _highest_note = (*ii)->note();
767 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()));
771 /* if the note's time property was changed in tandem with some
772 * other property as the next operation after it was added to
773 * the sequence, then at the point where we call this to undo
774 * the add, the note we are targetting currently has a
775 * different time property than the one we we passed via
778 * in this scenario, we have no choice other than to linear
779 * search the list of notes and find the note by ID.
782 for (i = _notes.begin(); i != _notes.end(); ++i) {
784 if ((*i)->id() == note->id()) {
786 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\tID-based pass, erasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
789 if (note->note() == _lowest_note || note->note() == _highest_note) {
794 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
795 if ((*ii)->note() < _lowest_note)
796 _lowest_note = (*ii)->note();
797 if ((*ii)->note() > _highest_note)
798 _highest_note = (*ii)->note();
811 Pitches& p (pitches (note->channel()));
813 typename Pitches::iterator j;
815 /* if we had to ID-match above, we can't expect to find it in
816 * pitches via note comparison either. so do another linear
817 * search to locate it. otherwise, we can use the note index
818 * to potentially speed things up.
823 for (j = p.begin(); j != p.end(); ++j) {
824 if ((*j)->id() == note->id()) {
832 /* Now find the same note in the "pitches" list (which indexes
833 * notes by channel+time. We care only about its note number
834 * so the search_note has all other properties unset.
837 NotePtr search_note (new Note<Time>(0, Time(), Time(), note->note(), 0));
839 for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
842 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
850 warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
856 cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
860 template<typename Time>
862 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
864 typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
866 while (i != _patch_changes.end() && ((*i)->time() == p->time())) {
868 typename Sequence<Time>::PatchChanges::iterator tmp = i;
872 _patch_changes.erase (i);
879 template<typename Time>
881 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
883 typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
884 while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
886 typename Sequence<Time>::SysExes::iterator tmp = i;
897 /** Append \a ev to model. NOT realtime safe.
899 * The timestamp of event is expected to be relative to
900 * the start of this model (t=0) and MUST be monotonically increasing
901 * and MUST be >= the latest event currently in the model.
903 template<typename Time>
905 Sequence<Time>::append(const Event<Time>& event, event_id_t evid)
907 WriteLock lock(write_lock());
909 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
911 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
914 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
915 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
919 if (ev.is_note_on() && ev.velocity() > 0) {
920 append_note_on_unlocked (ev, evid);
921 } else if (ev.is_note_off() || (ev.is_note_on() && ev.velocity() == 0)) {
922 /* XXX note: event ID is discarded because we merge the on+off events into
925 append_note_off_unlocked (ev);
926 } else if (ev.is_sysex()) {
927 append_sysex_unlocked(ev, evid);
928 } else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
929 /* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
930 if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
931 _bank[ev.channel()] &= ~(0x7f << 7);
932 _bank[ev.channel()] |= ev.cc_value() << 7;
934 _bank[ev.channel()] &= ~0x7f;
935 _bank[ev.channel()] |= ev.cc_value();
937 } else if (ev.is_cc()) {
938 append_control_unlocked(
939 Parameter(ev.event_type(), ev.channel(), ev.cc_number()),
940 ev.time(), ev.cc_value(), evid);
941 } else if (ev.is_pgm_change()) {
942 /* write a patch change with this program change and any previously set-up bank number */
943 append_patch_change_unlocked (PatchChange<Time> (ev.time(), ev.channel(), ev.pgm_number(), _bank[ev.channel()]), evid);
944 } else if (ev.is_pitch_bender()) {
945 append_control_unlocked(
946 Parameter(ev.event_type(), ev.channel()),
947 ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
948 | (0x7F & ev.pitch_bender_lsb())),
950 } else if (ev.is_poly_pressure()) {
951 append_control_unlocked (Parameter (ev.event_type(), ev.channel(), ev.poly_note()), ev.time(), ev.poly_pressure(), evid);
952 } else if (ev.is_channel_pressure()) {
953 append_control_unlocked(
954 Parameter(ev.event_type(), ev.channel()),
955 ev.time(), ev.channel_pressure(), evid);
956 } else if (!_type_map.type_is_midi(ev.event_type())) {
957 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
958 for (size_t i=0; i < ev.size(); ++i) {
959 printf("%X ", ev.buffer()[i]);
963 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
969 template<typename Time>
971 Sequence<Time>::append_note_on_unlocked (const MIDIEvent<Time>& ev, event_id_t evid)
973 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
974 (int)ev.channel(), (int)ev.note(),
975 ev.time(), (int)ev.velocity()));
978 if (ev.note() > 127) {
979 error << string_compose (_("invalid note on number (%1) ignored"), (int) ev.note()) << endmsg;
981 } else if (ev.channel() >= 16) {
982 error << string_compose (_("invalid note on channel (%1) ignored"), (int) ev.channel()) << endmsg;
984 } else if (ev.velocity() == 0) {
985 // Note on with velocity 0 handled as note off by caller
986 error << string_compose (_("invalid note on velocity (%1) ignored"), (int) ev.velocity()) << endmsg;
990 NotePtr note(new Note<Time>(ev.channel(), ev.time(), Time(), ev.note(), ev.velocity()));
993 add_note_unlocked (note);
995 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Appending active note on %1 channel %2\n",
996 (unsigned)(uint8_t)note->note(), note->channel()));
997 _write_notes[note->channel()].insert (note);
1001 template<typename Time>
1003 Sequence<Time>::append_note_off_unlocked (const MIDIEvent<Time>& ev)
1005 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
1006 this, (int)ev.channel(),
1007 (int)ev.note(), ev.time(), (int)ev.velocity()));
1010 if (ev.note() > 127) {
1011 error << string_compose (_("invalid note off number (%1) ignored"), (int) ev.note()) << endmsg;
1013 } else if (ev.channel() >= 16) {
1014 error << string_compose (_("invalid note off channel (%1) ignored"), (int) ev.channel()) << endmsg;
1020 bool resolved = false;
1022 /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1023 matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1024 whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1028 /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1030 for (typename WriteNotes::iterator n = _write_notes[ev.channel()].begin(); n != _write_notes[ev.channel()].end(); ) {
1032 typename WriteNotes::iterator tmp = n;
1036 if (ev.note() == nn->note() && nn->channel() == ev.channel()) {
1037 assert(ev.time() >= nn->time());
1039 nn->set_length (ev.time() - nn->time());
1040 nn->set_off_velocity (ev.velocity());
1042 _write_notes[ev.channel()].erase(n);
1043 DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1052 cerr << this << " spurious note off chan " << (int)ev.channel()
1053 << ", note " << (int)ev.note() << " @ " << ev.time() << endl;
1057 template<typename Time>
1059 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1061 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1062 this, _type_map.to_symbol(param), time, value, _controls.size()));
1063 boost::shared_ptr<Control> c = control(param, true);
1064 c->list()->add (time.to_double(), value, true, false);
1065 /* XXX control events should use IDs */
1068 template<typename Time>
1070 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev, event_id_t /* evid */)
1072 #ifdef DEBUG_SEQUENCE
1073 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1074 for (size_t i=0; i < ev.size(); ++i) {
1075 cerr << int(ev.buffer()[i]) << " ";
1076 } cerr << "]" << endl;
1079 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
1080 /* XXX sysex events should use IDs */
1081 _sysexes.insert(event);
1084 template<typename Time>
1086 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1088 PatchChangePtr p (new PatchChange<Time> (ev));
1094 _patch_changes.insert (p);
1097 template<typename Time>
1099 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1102 p->set_id (Evoral::next_event_id ());
1105 _patch_changes.insert (p);
1108 template<typename Time>
1110 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1113 s->set_id (Evoral::next_event_id ());
1116 _sysexes.insert (s);
1119 template<typename Time>
1121 Sequence<Time>::contains (const NotePtr& note) const
1123 ReadLock lock (read_lock());
1124 return contains_unlocked (note);
1127 template<typename Time>
1129 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1131 const Pitches& p (pitches (note->channel()));
1132 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1134 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1135 i != p.end() && (*i)->note() == note->note(); ++i) {
1145 template<typename Time>
1147 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1149 ReadLock lock (read_lock());
1150 return overlaps_unlocked (note, without);
1153 template<typename Time>
1155 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1157 Time sa = note->time();
1158 Time ea = note->end_time();
1160 const Pitches& p (pitches (note->channel()));
1161 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1163 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1164 i != p.end() && (*i)->note() == note->note(); ++i) {
1166 if (without && (**i) == *without) {
1170 Time sb = (*i)->time();
1171 Time eb = (*i)->end_time();
1173 if (((sb > sa) && (eb <= ea)) ||
1174 ((eb >= sa) && (eb <= ea)) ||
1175 ((sb > sa) && (sb <= ea)) ||
1176 ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1184 template<typename Time>
1186 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1191 // CONST iterator implementations (x3)
1193 /** Return the earliest note with time >= t */
1194 template<typename Time>
1195 typename Sequence<Time>::Notes::const_iterator
1196 Sequence<Time>::note_lower_bound (Time t) const
1198 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1199 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1200 assert(i == _notes.end() || (*i)->time() >= t);
1204 /** Return the earliest patch change with time >= t */
1205 template<typename Time>
1206 typename Sequence<Time>::PatchChanges::const_iterator
1207 Sequence<Time>::patch_change_lower_bound (Time t) const
1209 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1210 typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1211 assert (i == _patch_changes.end() || (*i)->time() >= t);
1215 /** Return the earliest sysex with time >= t */
1216 template<typename Time>
1217 typename Sequence<Time>::SysExes::const_iterator
1218 Sequence<Time>::sysex_lower_bound (Time t) const
1220 SysExPtr search (new Event<Time> (0, t));
1221 typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1222 assert (i == _sysexes.end() || (*i)->time() >= t);
1226 // NON-CONST iterator implementations (x3)
1228 /** Return the earliest note with time >= t */
1229 template<typename Time>
1230 typename Sequence<Time>::Notes::iterator
1231 Sequence<Time>::note_lower_bound (Time t)
1233 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1234 typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1235 assert(i == _notes.end() || (*i)->time() >= t);
1239 /** Return the earliest patch change with time >= t */
1240 template<typename Time>
1241 typename Sequence<Time>::PatchChanges::iterator
1242 Sequence<Time>::patch_change_lower_bound (Time t)
1244 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1245 typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1246 assert (i == _patch_changes.end() || (*i)->time() >= t);
1250 /** Return the earliest sysex with time >= t */
1251 template<typename Time>
1252 typename Sequence<Time>::SysExes::iterator
1253 Sequence<Time>::sysex_lower_bound (Time t)
1255 SysExPtr search (new Event<Time> (0, t));
1256 typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1257 assert (i == _sysexes.end() || (*i)->time() >= t);
1261 template<typename Time>
1263 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1268 case PitchLessThanOrEqual:
1270 case PitchGreaterThanOrEqual:
1271 get_notes_by_pitch (n, op, val, chan_mask);
1275 case VelocityLessThan:
1276 case VelocityLessThanOrEqual:
1277 case VelocityGreater:
1278 case VelocityGreaterThanOrEqual:
1279 get_notes_by_velocity (n, op, val, chan_mask);
1284 template<typename Time>
1286 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1288 for (uint8_t c = 0; c < 16; ++c) {
1290 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1294 const Pitches& p (pitches (c));
1295 NotePtr search_note(new Note<Time>(0, Time(), Time(), val, 0));
1296 typename Pitches::const_iterator i;
1299 i = p.lower_bound (search_note);
1300 while (i != p.end() && (*i)->note() == val) {
1305 i = p.upper_bound (search_note);
1306 while (i != p.end() && (*i)->note() < val) {
1310 case PitchLessThanOrEqual:
1311 i = p.upper_bound (search_note);
1312 while (i != p.end() && (*i)->note() <= val) {
1317 i = p.lower_bound (search_note);
1318 while (i != p.end() && (*i)->note() > val) {
1322 case PitchGreaterThanOrEqual:
1323 i = p.lower_bound (search_note);
1324 while (i != p.end() && (*i)->note() >= val) {
1330 //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1331 abort(); /* NOTREACHED*/
1336 template<typename Time>
1338 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1340 ReadLock lock (read_lock());
1342 for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1344 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1350 if ((*i)->velocity() == val) {
1354 case VelocityLessThan:
1355 if ((*i)->velocity() < val) {
1359 case VelocityLessThanOrEqual:
1360 if ((*i)->velocity() <= val) {
1364 case VelocityGreater:
1365 if ((*i)->velocity() > val) {
1369 case VelocityGreaterThanOrEqual:
1370 if ((*i)->velocity() >= val) {
1375 // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1376 abort(); /* NOTREACHED*/
1382 template<typename Time>
1384 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1386 _overlap_pitch_resolution = opr;
1388 /* XXX todo: clean up existing overlaps in source data? */
1391 template<typename Time>
1393 Sequence<Time>::control_list_marked_dirty ()
1398 template<typename Time>
1400 Sequence<Time>::dump (ostream& str) const
1402 typename Sequence<Time>::const_iterator i;
1403 str << "+++ dump\n";
1404 for (i = begin(); i != end(); ++i) {
1407 str << "--- dump\n";
1410 template class Sequence<Evoral::Beats>;
1412 } // namespace Evoral