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_sysex()) ) {
341 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
342 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
349 // Increment past current event
358 // Increment current controller iterator
359 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
360 ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
361 _control_iter->x, x, y, false);
363 ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
364 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false);
366 assert(!ret || x > _control_iter->x);
368 _control_iter->x = x;
369 _control_iter->y = y;
371 _control_iter->list.reset();
372 _control_iter->x = DBL_MAX;
373 _control_iter->y = DBL_MAX;
376 // Find the controller with the next earliest event time
377 _control_iter = _control_iters.begin();
378 for (ControlIterators::iterator i = _control_iters.begin();
379 i != _control_iters.end(); ++i) {
380 if (i->x < _control_iter->x) {
389 ++_active_patch_change_message;
390 if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
391 ++_patch_change_iter;
392 _active_patch_change_message = 0;
399 // Choose the earliest event overall to point to
400 choose_next(std::numeric_limits<Time>::max());
402 // Set event from chosen sub-iterator
405 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
410 template<typename Time>
412 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
414 if (_seq != other._seq) {
416 } else if (_is_end || other._is_end) {
417 return (_is_end == other._is_end);
418 } else if (_type != other._type) {
421 return (_event == other._event);
425 template<typename Time>
426 typename Sequence<Time>::const_iterator&
427 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
430 _event = other._event;
431 _active_notes = other._active_notes;
433 _is_end = other._is_end;
434 _note_iter = other._note_iter;
435 _sysex_iter = other._sysex_iter;
436 _patch_change_iter = other._patch_change_iter;
437 _control_iters = other._control_iters;
438 _force_discrete = other._force_discrete;
439 _active_patch_change_message = other._active_patch_change_message;
442 _lock = _seq->read_lock();
447 if (other._control_iter == other._control_iters.end()) {
448 _control_iter = _control_iters.end();
450 const size_t index = other._control_iter - other._control_iters.begin();
451 _control_iter = _control_iters.begin() + index;
459 template<typename Time>
460 Sequence<Time>::Sequence(const TypeMap& type_map)
462 , _overlapping_pitches_accepted (true)
463 , _overlap_pitch_resolution (FirstOnFirstOff)
465 , _type_map(type_map)
466 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
471 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
472 assert(_end_iter._is_end);
473 assert( ! _end_iter._lock);
475 for (int i = 0; i < 16; ++i) {
480 template<typename Time>
481 Sequence<Time>::Sequence(const Sequence<Time>& other)
484 , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
485 , _overlap_pitch_resolution (other._overlap_pitch_resolution)
487 , _type_map(other._type_map)
488 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
489 , _percussive(other._percussive)
490 , _lowest_note(other._lowest_note)
491 , _highest_note(other._highest_note)
493 for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
494 NotePtr n (new Note<Time> (**i));
498 for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
499 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
503 for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
504 PatchChangePtr n (new PatchChange<Time> (**i));
505 _patch_changes.insert (n);
508 for (int i = 0; i < 16; ++i) {
509 _bank[i] = other._bank[i];
512 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
513 assert(_end_iter._is_end);
514 assert(! _end_iter._lock);
517 /** Write the controller event pointed to by \a iter to \a ev.
518 * The buffer of \a ev will be allocated or resized as necessary.
519 * The event_type of \a ev should be set to the expected output type.
520 * \return true on success
522 template<typename Time>
524 Sequence<Time>::control_to_midi_event(
525 boost::shared_ptr< Event<Time> >& ev,
526 const ControlIterator& iter) const
528 assert(iter.list.get());
529 const uint32_t event_type = iter.list->parameter().type();
531 // initialize the event pointer with a new event, if necessary
533 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, Time(), 3, NULL, true));
536 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
537 ev->set_event_type(_type_map.midi_event_type(midi_type));
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_CHANNEL_PRESSURE:
577 assert(iter.list.get());
578 assert(iter.list->parameter().channel() < 16);
579 assert(iter.y <= INT8_MAX);
581 ev->set_time(Time(iter.x));
583 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
584 ev->buffer()[1] = (uint8_t)iter.y;
594 /** Clear all events from the model.
596 template<typename Time>
598 Sequence<Time>::clear()
600 WriteLock lock(write_lock());
602 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
603 li->second->list()->clear();
606 /** Begin a write of events to the model.
608 * If \a mode is Sustained, complete notes with length are constructed as note
609 * on/off events are received. Otherwise (Percussive), only note on events are
610 * stored; note off events are discarded entirely and all contained notes will
613 template<typename Time>
615 Sequence<Time>::start_write()
617 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
618 WriteLock lock(write_lock());
620 for (int i = 0; i < 16; ++i) {
621 _write_notes[i].clear();
625 /** Finish a write of events to the model.
627 * If \a delete_stuck is true and the current mode is Sustained, note on events
628 * that were never resolved with a corresonding note off will be deleted.
629 * Otherwise they will remain as notes with length 0.
631 template<typename Time>
633 Sequence<Time>::end_write (StuckNoteOption option, Time when)
635 WriteLock lock(write_lock());
641 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
643 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
644 typename Notes::iterator next = n;
647 if (!(*n)->length()) {
651 case DeleteStuckNotes:
652 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
655 case ResolveStuckNotes:
656 if (when <= (*n)->time()) {
657 cerr << "WARNING: Stuck note resolution - end time @ "
658 << when << " is before note on: " << (**n) << endl;
661 (*n)->set_length (when - (*n)->time());
662 cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
671 for (int i = 0; i < 16; ++i) {
672 _write_notes[i].clear();
679 template<typename Time>
681 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
683 /* This is the core method to add notes to a Sequence
686 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
688 if (resolve_overlaps_unlocked (note, arg)) {
689 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
693 if (note->id() < 0) {
694 note->set_id (Evoral::next_event_id());
697 if (note->note() < _lowest_note)
698 _lowest_note = note->note();
699 if (note->note() > _highest_note)
700 _highest_note = note->note();
702 _notes.insert (note);
703 _pitches[note->channel()].insert (note);
710 template<typename Time>
712 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
715 bool id_matched = false;
717 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
719 /* first try searching for the note using the time index, which is
720 * faster since the container is "indexed" by time. (technically, this
721 * means that lower_bound() can do a binary search rather than linear)
723 * this may not work, for reasons explained below.
726 typename Sequence<Time>::Notes::iterator i;
728 for (i = note_lower_bound(note->time()); i != _notes.end() && (*i)->time() == note->time(); ++i) {
732 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
735 if (note->note() == _lowest_note || note->note() == _highest_note) {
740 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
741 if ((*ii)->note() < _lowest_note)
742 _lowest_note = (*ii)->note();
743 if ((*ii)->note() > _highest_note)
744 _highest_note = (*ii)->note();
753 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()));
757 /* if the note's time property was changed in tandem with some
758 * other property as the next operation after it was added to
759 * the sequence, then at the point where we call this to undo
760 * the add, the note we are targetting currently has a
761 * different time property than the one we we passed via
764 * in this scenario, we have no choice other than to linear
765 * search the list of notes and find the note by ID.
768 for (i = _notes.begin(); i != _notes.end(); ++i) {
770 if ((*i)->id() == note->id()) {
772 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\tID-based pass, erasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
775 if (note->note() == _lowest_note || note->note() == _highest_note) {
780 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
781 if ((*ii)->note() < _lowest_note)
782 _lowest_note = (*ii)->note();
783 if ((*ii)->note() > _highest_note)
784 _highest_note = (*ii)->note();
797 Pitches& p (pitches (note->channel()));
799 typename Pitches::iterator j;
801 /* if we had to ID-match above, we can't expect to find it in
802 * pitches via note comparison either. so do another linear
803 * search to locate it. otherwise, we can use the note index
804 * to potentially speed things up.
809 for (j = p.begin(); j != p.end(); ++j) {
810 if ((*j)->id() == note->id()) {
818 /* Now find the same note in the "pitches" list (which indexes
819 * notes by channel+time. We care only about its note number
820 * so the search_note has all other properties unset.
823 NotePtr search_note (new Note<Time>(0, Time(), Time(), note->note(), 0));
825 for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
828 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
836 warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
842 cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
846 template<typename Time>
848 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
850 typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
852 while (i != _patch_changes.end() && ((*i)->time() == p->time())) {
854 typename Sequence<Time>::PatchChanges::iterator tmp = i;
858 _patch_changes.erase (i);
865 template<typename Time>
867 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
869 typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
870 while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
872 typename Sequence<Time>::SysExes::iterator tmp = i;
883 /** Append \a ev to model. NOT realtime safe.
885 * The timestamp of event is expected to be relative to
886 * the start of this model (t=0) and MUST be monotonically increasing
887 * and MUST be >= the latest event currently in the model.
889 template<typename Time>
891 Sequence<Time>::append(const Event<Time>& event, event_id_t evid)
893 WriteLock lock(write_lock());
895 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
897 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
900 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
901 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
905 if (ev.is_note_on() && ev.velocity() > 0) {
906 append_note_on_unlocked (ev, evid);
907 } else if (ev.is_note_off() || (ev.is_note_on() && ev.velocity() == 0)) {
908 /* XXX note: event ID is discarded because we merge the on+off events into
911 append_note_off_unlocked (ev);
912 } else if (ev.is_sysex()) {
913 append_sysex_unlocked(ev, evid);
914 } else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
915 /* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
916 if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
917 _bank[ev.channel()] &= ~(0x7f << 7);
918 _bank[ev.channel()] |= ev.cc_value() << 7;
920 _bank[ev.channel()] &= ~0x7f;
921 _bank[ev.channel()] |= ev.cc_value();
923 } else if (ev.is_cc()) {
924 append_control_unlocked(
925 Parameter(ev.event_type(), ev.channel(), ev.cc_number()),
926 ev.time(), ev.cc_value(), evid);
927 } else if (ev.is_pgm_change()) {
928 /* write a patch change with this program change and any previously set-up bank number */
929 append_patch_change_unlocked (PatchChange<Time> (ev.time(), ev.channel(), ev.pgm_number(), _bank[ev.channel()]), evid);
930 } else if (ev.is_pitch_bender()) {
931 append_control_unlocked(
932 Parameter(ev.event_type(), ev.channel()),
933 ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
934 | (0x7F & ev.pitch_bender_lsb())),
936 } else if (ev.is_poly_pressure()) {
937 append_control_unlocked (Parameter (ev.event_type(), ev.channel(), ev.poly_note()), ev.time(), ev.poly_pressure(), evid);
938 } else if (ev.is_channel_pressure()) {
939 append_control_unlocked(
940 Parameter(ev.event_type(), ev.channel()),
941 ev.time(), ev.channel_pressure(), evid);
942 } else if (!_type_map.type_is_midi(ev.event_type())) {
943 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
944 for (size_t i=0; i < ev.size(); ++i) {
945 printf("%X ", ev.buffer()[i]);
949 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
955 template<typename Time>
957 Sequence<Time>::append_note_on_unlocked (const MIDIEvent<Time>& ev, event_id_t evid)
959 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
960 (int)ev.channel(), (int)ev.note(),
961 ev.time(), (int)ev.velocity()));
964 if (ev.note() > 127) {
965 error << string_compose (_("invalid note on number (%1) ignored"), (int) ev.note()) << endmsg;
967 } else if (ev.channel() >= 16) {
968 error << string_compose (_("invalid note on channel (%1) ignored"), (int) ev.channel()) << endmsg;
970 } else if (ev.velocity() == 0) {
971 // Note on with velocity 0 handled as note off by caller
972 error << string_compose (_("invalid note on velocity (%1) ignored"), (int) ev.velocity()) << endmsg;
976 NotePtr note(new Note<Time>(ev.channel(), ev.time(), Time(), ev.note(), ev.velocity()));
979 add_note_unlocked (note);
981 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Appending active note on %1 channel %2\n",
982 (unsigned)(uint8_t)note->note(), note->channel()));
983 _write_notes[note->channel()].insert (note);
987 template<typename Time>
989 Sequence<Time>::append_note_off_unlocked (const MIDIEvent<Time>& ev)
991 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
992 this, (int)ev.channel(),
993 (int)ev.note(), ev.time(), (int)ev.velocity()));
996 if (ev.note() > 127) {
997 error << string_compose (_("invalid note off number (%1) ignored"), (int) ev.note()) << endmsg;
999 } else if (ev.channel() >= 16) {
1000 error << string_compose (_("invalid note off channel (%1) ignored"), (int) ev.channel()) << endmsg;
1006 bool resolved = false;
1008 /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1009 matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1010 whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1014 /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1016 for (typename WriteNotes::iterator n = _write_notes[ev.channel()].begin(); n != _write_notes[ev.channel()].end(); ) {
1018 typename WriteNotes::iterator tmp = n;
1022 if (ev.note() == nn->note() && nn->channel() == ev.channel()) {
1023 assert(ev.time() >= nn->time());
1025 nn->set_length (ev.time() - nn->time());
1026 nn->set_off_velocity (ev.velocity());
1028 _write_notes[ev.channel()].erase(n);
1029 DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1038 cerr << this << " spurious note off chan " << (int)ev.channel()
1039 << ", note " << (int)ev.note() << " @ " << ev.time() << endl;
1043 template<typename Time>
1045 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1047 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1048 this, _type_map.to_symbol(param), time, value, _controls.size()));
1049 boost::shared_ptr<Control> c = control(param, true);
1050 c->list()->add (time.to_double(), value, true, false);
1051 /* XXX control events should use IDs */
1054 template<typename Time>
1056 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev, event_id_t /* evid */)
1058 #ifdef DEBUG_SEQUENCE
1059 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1060 for (size_t i=0; i < ev.size(); ++i) {
1061 cerr << int(ev.buffer()[i]) << " ";
1062 } cerr << "]" << endl;
1065 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
1066 /* XXX sysex events should use IDs */
1067 _sysexes.insert(event);
1070 template<typename Time>
1072 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1074 PatchChangePtr p (new PatchChange<Time> (ev));
1080 _patch_changes.insert (p);
1083 template<typename Time>
1085 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1088 p->set_id (Evoral::next_event_id ());
1091 _patch_changes.insert (p);
1094 template<typename Time>
1096 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1099 s->set_id (Evoral::next_event_id ());
1102 _sysexes.insert (s);
1105 template<typename Time>
1107 Sequence<Time>::contains (const NotePtr& note) const
1109 ReadLock lock (read_lock());
1110 return contains_unlocked (note);
1113 template<typename Time>
1115 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1117 const Pitches& p (pitches (note->channel()));
1118 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1120 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1121 i != p.end() && (*i)->note() == note->note(); ++i) {
1131 template<typename Time>
1133 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1135 ReadLock lock (read_lock());
1136 return overlaps_unlocked (note, without);
1139 template<typename Time>
1141 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1143 Time sa = note->time();
1144 Time ea = note->end_time();
1146 const Pitches& p (pitches (note->channel()));
1147 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1149 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1150 i != p.end() && (*i)->note() == note->note(); ++i) {
1152 if (without && (**i) == *without) {
1156 Time sb = (*i)->time();
1157 Time eb = (*i)->end_time();
1159 if (((sb > sa) && (eb <= ea)) ||
1160 ((eb >= sa) && (eb <= ea)) ||
1161 ((sb > sa) && (sb <= ea)) ||
1162 ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1170 template<typename Time>
1172 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1177 // CONST iterator implementations (x3)
1179 /** Return the earliest note with time >= t */
1180 template<typename Time>
1181 typename Sequence<Time>::Notes::const_iterator
1182 Sequence<Time>::note_lower_bound (Time t) const
1184 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1185 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1186 assert(i == _notes.end() || (*i)->time() >= t);
1190 /** Return the earliest patch change with time >= t */
1191 template<typename Time>
1192 typename Sequence<Time>::PatchChanges::const_iterator
1193 Sequence<Time>::patch_change_lower_bound (Time t) const
1195 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1196 typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1197 assert (i == _patch_changes.end() || (*i)->time() >= t);
1201 /** Return the earliest sysex with time >= t */
1202 template<typename Time>
1203 typename Sequence<Time>::SysExes::const_iterator
1204 Sequence<Time>::sysex_lower_bound (Time t) const
1206 SysExPtr search (new Event<Time> (0, t));
1207 typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1208 assert (i == _sysexes.end() || (*i)->time() >= t);
1212 // NON-CONST iterator implementations (x3)
1214 /** Return the earliest note with time >= t */
1215 template<typename Time>
1216 typename Sequence<Time>::Notes::iterator
1217 Sequence<Time>::note_lower_bound (Time t)
1219 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1220 typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1221 assert(i == _notes.end() || (*i)->time() >= t);
1225 /** Return the earliest patch change with time >= t */
1226 template<typename Time>
1227 typename Sequence<Time>::PatchChanges::iterator
1228 Sequence<Time>::patch_change_lower_bound (Time t)
1230 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1231 typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1232 assert (i == _patch_changes.end() || (*i)->time() >= t);
1236 /** Return the earliest sysex with time >= t */
1237 template<typename Time>
1238 typename Sequence<Time>::SysExes::iterator
1239 Sequence<Time>::sysex_lower_bound (Time t)
1241 SysExPtr search (new Event<Time> (0, t));
1242 typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1243 assert (i == _sysexes.end() || (*i)->time() >= t);
1247 template<typename Time>
1249 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1254 case PitchLessThanOrEqual:
1256 case PitchGreaterThanOrEqual:
1257 get_notes_by_pitch (n, op, val, chan_mask);
1261 case VelocityLessThan:
1262 case VelocityLessThanOrEqual:
1263 case VelocityGreater:
1264 case VelocityGreaterThanOrEqual:
1265 get_notes_by_velocity (n, op, val, chan_mask);
1270 template<typename Time>
1272 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1274 for (uint8_t c = 0; c < 16; ++c) {
1276 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1280 const Pitches& p (pitches (c));
1281 NotePtr search_note(new Note<Time>(0, Time(), Time(), val, 0));
1282 typename Pitches::const_iterator i;
1285 i = p.lower_bound (search_note);
1286 while (i != p.end() && (*i)->note() == val) {
1291 i = p.upper_bound (search_note);
1292 while (i != p.end() && (*i)->note() < val) {
1296 case PitchLessThanOrEqual:
1297 i = p.upper_bound (search_note);
1298 while (i != p.end() && (*i)->note() <= val) {
1303 i = p.lower_bound (search_note);
1304 while (i != p.end() && (*i)->note() > val) {
1308 case PitchGreaterThanOrEqual:
1309 i = p.lower_bound (search_note);
1310 while (i != p.end() && (*i)->note() >= val) {
1316 //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1317 abort(); /* NOTREACHED*/
1322 template<typename Time>
1324 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1326 ReadLock lock (read_lock());
1328 for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1330 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1336 if ((*i)->velocity() == val) {
1340 case VelocityLessThan:
1341 if ((*i)->velocity() < val) {
1345 case VelocityLessThanOrEqual:
1346 if ((*i)->velocity() <= val) {
1350 case VelocityGreater:
1351 if ((*i)->velocity() > val) {
1355 case VelocityGreaterThanOrEqual:
1356 if ((*i)->velocity() >= val) {
1361 // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1362 abort(); /* NOTREACHED*/
1368 template<typename Time>
1370 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1372 _overlap_pitch_resolution = opr;
1374 /* XXX todo: clean up existing overlaps in source data? */
1377 template<typename Time>
1379 Sequence<Time>::control_list_marked_dirty ()
1384 template<typename Time>
1386 Sequence<Time>::dump (ostream& str) const
1388 typename Sequence<Time>::const_iterator i;
1389 str << "+++ dump\n";
1390 for (i = begin(); i != end(); ++i) {
1393 str << "--- dump\n";
1396 template class Sequence<Evoral::Beats>;
1398 } // namespace Evoral