1 /* This file is part of Evoral.
2 * Copyright (C) 2008 David Robillard <http://drobilla.net>
3 * Copyright (C) 2000-2008 Paul Davis
5 * Evoral is free software; you can redistribute it and/or modify it under the
6 * terms of the GNU General Public License as published by the Free Software
7 * Foundation; either version 2 of the License, or (at your option) any later
10 * Evoral is distributed in the hope that it will be useful, but WITHOUT ANY
11 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
28 #include "evoral/Note.hpp"
31 #include "pbd/compose.h"
32 #include "pbd/error.h"
34 #include "evoral/Control.hpp"
35 #include "evoral/ControlList.hpp"
36 #include "evoral/ControlSet.hpp"
37 #include "evoral/EventSink.hpp"
38 #include "evoral/ParameterDescriptor.hpp"
39 #include "evoral/Sequence.hpp"
40 #include "evoral/TypeMap.hpp"
41 #include "evoral/midi_util.h"
48 /** Minimum time between MIDI outputs from a single interpolated controller,
49 expressed in beats. This is to limit the rate at which MIDI messages
50 are generated. It is only applied to interpolated controllers.
52 XXX: This is a hack. The time should probably be expressed in
53 seconds rather than beats, and should be configurable etc. etc.
55 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
59 // Read iterator (const_iterator)
61 template<typename Time>
62 Sequence<Time>::const_iterator::const_iterator()
64 , _event(boost::shared_ptr< Event<Time> >(new Event<Time>()))
65 , _active_patch_change_message (0)
68 , _control_iter(_control_iters.end())
69 , _force_discrete(false)
73 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
74 template<typename Time>
75 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq,
78 const std::set<Evoral::Parameter>& filtered,
79 const std::set<WeakNotePtr>* active_notes)
81 , _active_patch_change_message (0)
83 , _is_end((t == DBL_MAX) || seq.empty())
84 , _note_iter(seq.notes().end())
85 , _sysex_iter(seq.sysexes().end())
86 , _patch_change_iter(seq.patch_changes().end())
87 , _control_iter(_control_iters.end())
88 , _force_discrete (force_discrete)
90 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
96 _lock = seq.read_lock();
98 // Add currently active notes, if given
100 for (typename std::set<WeakNotePtr>::const_iterator i = active_notes->begin();
101 i != active_notes->end(); ++i) {
102 NotePtr note = i->lock();
103 if (note && note->time() <= t && note->end_time() > t) {
104 _active_notes.push(note);
109 // Find first note which begins at or after t
110 _note_iter = seq.note_lower_bound(t);
112 // Find first sysex event at or after t
113 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
114 i != seq.sysexes().end(); ++i) {
115 if ((*i)->time() >= t) {
120 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
122 // Find first patch event at or after t
123 for (typename Sequence<Time>::PatchChanges::const_iterator i = seq.patch_changes().begin(); i != seq.patch_changes().end(); ++i) {
124 if ((*i)->time() >= t) {
125 _patch_change_iter = i;
129 assert (_patch_change_iter == seq.patch_changes().end() || (*_patch_change_iter)->time() >= t);
131 // Find first control event after t
132 _control_iters.reserve(seq._controls.size());
134 size_t earliest_control_index = 0;
135 double earliest_control_x = DBL_MAX;
136 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
138 if (filtered.find (i->first) != filtered.end()) {
139 /* this parameter is filtered, so don't bother setting up an iterator for it */
143 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
146 if (_force_discrete || i->second->list()->interpolation() == ControlList::Discrete) {
147 ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t.to_double(), x, y, true);
149 ret = i->second->list()->rt_safe_earliest_event_unlocked(t.to_double(), x, y, true);
152 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
153 i->first.id(), i->second->list()->size(), t));
159 const ParameterDescriptor& desc = seq.type_map().descriptor(i->first);
160 if (y < desc.lower || y > desc.upper) {
161 cerr << "ERROR: Controller value " << y
162 << " out of range [" << desc.lower << "," << desc.upper
163 << "], event ignored" << endl;
167 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
169 const ControlIterator new_iter(i->second->list(), x, y);
170 _control_iters.push_back(new_iter);
172 // Found a new earliest_control
173 if (x < earliest_control_x) {
174 earliest_control_x = x;
175 earliest_control_index = _control_iters.size() - 1;
181 _control_iter = _control_iters.begin() + earliest_control_index;
182 assert(_control_iter != _control_iters.end());
183 assert(_control_iter->list);
185 _control_iter = _control_iters.end();
188 // Choose the earliest event overall to point to
191 // Allocate a new event for storing the current event in MIDI format
192 _event = boost::shared_ptr< Event<Time> >(
193 new Event<Time>(0, Time(), 4, NULL, true));
195 // Set event from chosen sub-iterator
199 DEBUG_TRACE(DEBUG::Sequence,
200 string_compose("Starting at end @ %1\n", t));
202 DEBUG_TRACE(DEBUG::Sequence,
203 string_compose("Starting at type 0x%1 : 0x%2 @ %3\n",
204 (int)_event->event_type(),
205 (int)((MIDIEvent<Time>*)_event.get())->type(),
210 template<typename Time>
212 Sequence<Time>::const_iterator::invalidate(std::set< boost::weak_ptr< Note<Time> > >* notes)
214 while (!_active_notes.empty()) {
216 notes->insert(_active_notes.top());
223 _note_iter = _seq->notes().end();
224 _sysex_iter = _seq->sysexes().end();
225 _patch_change_iter = _seq->patch_changes().end();
226 _active_patch_change_message = 0;
228 _control_iters.clear();
229 _control_iter = _control_iters.end();
233 template<typename Time>
235 Sequence<Time>::const_iterator::choose_next(Time earliest_t)
239 // Next earliest note on
240 if (_note_iter != _seq->notes().end()) {
242 earliest_t = (*_note_iter)->time();
245 // Use the next note off iff it's earlier or the same time as the note on
246 if ((!_active_notes.empty())) {
247 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
249 earliest_t = _active_notes.top()->end_time();
253 // Use the next earliest controller iff it's earlier than the note event
254 if (_control_iter != _control_iters.end() &&
255 _control_iter->list && _control_iter->x != DBL_MAX) {
256 if (_type == NIL || _control_iter->x < earliest_t.to_double()) {
258 earliest_t = Time(_control_iter->x);
262 // Use the next earliest SysEx iff it's earlier than the controller
263 if (_sysex_iter != _seq->sysexes().end()) {
264 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
266 earliest_t = (*_sysex_iter)->time();
270 // Use the next earliest patch change iff it's earlier than the SysEx
271 if (_patch_change_iter != _seq->patch_changes().end()) {
272 if (_type == NIL || (*_patch_change_iter)->time() < earliest_t) {
273 _type = PATCH_CHANGE;
274 earliest_t = (*_patch_change_iter)->time();
280 template<typename Time>
282 Sequence<Time>::const_iterator::set_event()
286 DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
287 *_event = (*_note_iter)->on_event();
288 _active_notes.push(*_note_iter);
291 DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
292 assert(!_active_notes.empty());
293 *_event = _active_notes.top()->off_event();
294 // We don't pop the active note until we increment past it
297 DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
298 *_event = *(*_sysex_iter);
301 DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
302 _seq->control_to_midi_event(_event, *_control_iter);
305 DEBUG_TRACE(DEBUG::Sequence, "iterator = program change\n");
306 *_event = (*_patch_change_iter)->message (_active_patch_change_message);
313 if (_type == NIL || !_event || _event->size() == 0) {
314 DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
318 assert(midi_event_is_valid(_event->buffer(), _event->size()));
322 template<typename Time>
323 const typename Sequence<Time>::const_iterator&
324 Sequence<Time>::const_iterator::operator++()
327 throw std::logic_error("Attempt to iterate past end of Sequence");
330 assert(_event && _event->buffer() && _event->size() > 0);
332 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
336 || ev.is_pgm_change()
337 || ev.is_pitch_bender()
338 || ev.is_channel_pressure()
339 || ev.is_sysex()) ) {
340 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
341 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
348 // Increment past current event
357 // Increment current controller iterator
358 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
359 ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
360 _control_iter->x, x, y, false);
362 ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
363 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false);
365 assert(!ret || x > _control_iter->x);
367 _control_iter->x = x;
368 _control_iter->y = y;
370 _control_iter->list.reset();
371 _control_iter->x = DBL_MAX;
372 _control_iter->y = DBL_MAX;
375 // Find the controller with the next earliest event time
376 _control_iter = _control_iters.begin();
377 for (ControlIterators::iterator i = _control_iters.begin();
378 i != _control_iters.end(); ++i) {
379 if (i->x < _control_iter->x) {
388 ++_active_patch_change_message;
389 if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
390 ++_patch_change_iter;
391 _active_patch_change_message = 0;
398 // Choose the earliest event overall to point to
399 choose_next(std::numeric_limits<Time>::max());
401 // Set event from chosen sub-iterator
404 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
409 template<typename Time>
411 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
413 if (_seq != other._seq) {
415 } else if (_is_end || other._is_end) {
416 return (_is_end == other._is_end);
417 } else if (_type != other._type) {
420 return (_event == other._event);
424 template<typename Time>
425 typename Sequence<Time>::const_iterator&
426 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
429 _event = other._event;
430 _active_notes = other._active_notes;
432 _is_end = other._is_end;
433 _note_iter = other._note_iter;
434 _sysex_iter = other._sysex_iter;
435 _patch_change_iter = other._patch_change_iter;
436 _control_iters = other._control_iters;
437 _force_discrete = other._force_discrete;
438 _active_patch_change_message = other._active_patch_change_message;
441 _lock = _seq->read_lock();
446 if (other._control_iter == other._control_iters.end()) {
447 _control_iter = _control_iters.end();
449 const size_t index = other._control_iter - other._control_iters.begin();
450 _control_iter = _control_iters.begin() + index;
458 template<typename Time>
459 Sequence<Time>::Sequence(const TypeMap& type_map)
461 , _overlapping_pitches_accepted (true)
462 , _overlap_pitch_resolution (FirstOnFirstOff)
464 , _type_map(type_map)
465 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
470 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
471 assert(_end_iter._is_end);
472 assert( ! _end_iter._lock);
474 for (int i = 0; i < 16; ++i) {
479 template<typename Time>
480 Sequence<Time>::Sequence(const Sequence<Time>& other)
483 , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
484 , _overlap_pitch_resolution (other._overlap_pitch_resolution)
486 , _type_map(other._type_map)
487 , _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
488 , _percussive(other._percussive)
489 , _lowest_note(other._lowest_note)
490 , _highest_note(other._highest_note)
492 for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
493 NotePtr n (new Note<Time> (**i));
497 for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
498 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
502 for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
503 PatchChangePtr n (new PatchChange<Time> (**i));
504 _patch_changes.insert (n);
507 for (int i = 0; i < 16; ++i) {
508 _bank[i] = other._bank[i];
511 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
512 assert(_end_iter._is_end);
513 assert(! _end_iter._lock);
516 /** Write the controller event pointed to by \a iter to \a ev.
517 * The buffer of \a ev will be allocated or resized as necessary.
518 * The event_type of \a ev should be set to the expected output type.
519 * \return true on success
521 template<typename Time>
523 Sequence<Time>::control_to_midi_event(
524 boost::shared_ptr< Event<Time> >& ev,
525 const ControlIterator& iter) const
527 assert(iter.list.get());
528 const uint32_t event_type = iter.list->parameter().type();
530 // initialize the event pointer with a new event, if necessary
532 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, Time(), 3, NULL, true));
535 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
536 ev->set_event_type(_type_map.midi_event_type(midi_type));
538 case MIDI_CMD_CONTROL:
539 assert(iter.list.get());
540 assert(iter.list->parameter().channel() < 16);
541 assert(iter.list->parameter().id() <= INT8_MAX);
542 assert(iter.y <= INT8_MAX);
544 ev->set_time(Time(iter.x));
546 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
547 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
548 ev->buffer()[2] = (uint8_t)iter.y;
551 case MIDI_CMD_PGM_CHANGE:
552 assert(iter.list.get());
553 assert(iter.list->parameter().channel() < 16);
554 assert(iter.y <= INT8_MAX);
556 ev->set_time(Time(iter.x));
558 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
559 ev->buffer()[1] = (uint8_t)iter.y;
562 case MIDI_CMD_BENDER:
563 assert(iter.list.get());
564 assert(iter.list->parameter().channel() < 16);
565 assert(iter.y < (1<<14));
567 ev->set_time(Time(iter.x));
569 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
570 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
571 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
574 case MIDI_CMD_CHANNEL_PRESSURE:
575 assert(iter.list.get());
576 assert(iter.list->parameter().channel() < 16);
577 assert(iter.y <= INT8_MAX);
579 ev->set_time(Time(iter.x));
581 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
582 ev->buffer()[1] = (uint8_t)iter.y;
592 /** Clear all events from the model.
594 template<typename Time>
596 Sequence<Time>::clear()
598 WriteLock lock(write_lock());
600 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
601 li->second->list()->clear();
604 /** Begin a write of events to the model.
606 * If \a mode is Sustained, complete notes with length are constructed as note
607 * on/off events are received. Otherwise (Percussive), only note on events are
608 * stored; note off events are discarded entirely and all contained notes will
611 template<typename Time>
613 Sequence<Time>::start_write()
615 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
616 WriteLock lock(write_lock());
618 for (int i = 0; i < 16; ++i) {
619 _write_notes[i].clear();
623 /** Finish a write of events to the model.
625 * If \a delete_stuck is true and the current mode is Sustained, note on events
626 * that were never resolved with a corresonding note off will be deleted.
627 * Otherwise they will remain as notes with length 0.
629 template<typename Time>
631 Sequence<Time>::end_write (StuckNoteOption option, Time when)
633 WriteLock lock(write_lock());
639 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
641 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
642 typename Notes::iterator next = n;
645 if (!(*n)->length()) {
649 case DeleteStuckNotes:
650 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
653 case ResolveStuckNotes:
654 if (when <= (*n)->time()) {
655 cerr << "WARNING: Stuck note resolution - end time @ "
656 << when << " is before note on: " << (**n) << endl;
659 (*n)->set_length (when - (*n)->time());
660 cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
669 for (int i = 0; i < 16; ++i) {
670 _write_notes[i].clear();
677 template<typename Time>
679 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
681 /* This is the core method to add notes to a Sequence
684 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
686 if (resolve_overlaps_unlocked (note, arg)) {
687 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
691 if (note->id() < 0) {
692 note->set_id (Evoral::next_event_id());
695 if (note->note() < _lowest_note)
696 _lowest_note = note->note();
697 if (note->note() > _highest_note)
698 _highest_note = note->note();
700 _notes.insert (note);
701 _pitches[note->channel()].insert (note);
708 template<typename Time>
710 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
713 bool id_matched = false;
715 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
717 /* first try searching for the note using the time index, which is
718 * faster since the container is "indexed" by time. (technically, this
719 * means that lower_bound() can do a binary search rather than linear)
721 * this may not work, for reasons explained below.
724 typename Sequence<Time>::Notes::iterator i;
726 for (i = note_lower_bound(note->time()); i != _notes.end() && (*i)->time() == note->time(); ++i) {
730 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
733 if (note->note() == _lowest_note || note->note() == _highest_note) {
738 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
739 if ((*ii)->note() < _lowest_note)
740 _lowest_note = (*ii)->note();
741 if ((*ii)->note() > _highest_note)
742 _highest_note = (*ii)->note();
751 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()));
755 /* if the note's time property was changed in tandem with some
756 * other property as the next operation after it was added to
757 * the sequence, then at the point where we call this to undo
758 * the add, the note we are targetting currently has a
759 * different time property than the one we we passed via
762 * in this scenario, we have no choice other than to linear
763 * search the list of notes and find the note by ID.
766 for (i = _notes.begin(); i != _notes.end(); ++i) {
768 if ((*i)->id() == note->id()) {
770 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\tID-based pass, erasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
773 if (note->note() == _lowest_note || note->note() == _highest_note) {
778 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
779 if ((*ii)->note() < _lowest_note)
780 _lowest_note = (*ii)->note();
781 if ((*ii)->note() > _highest_note)
782 _highest_note = (*ii)->note();
795 Pitches& p (pitches (note->channel()));
797 typename Pitches::iterator j;
799 /* if we had to ID-match above, we can't expect to find it in
800 * pitches via note comparison either. so do another linear
801 * search to locate it. otherwise, we can use the note index
802 * to potentially speed things up.
807 for (j = p.begin(); j != p.end(); ++j) {
808 if ((*j)->id() == note->id()) {
816 /* Now find the same note in the "pitches" list (which indexes
817 * notes by channel+time. We care only about its note number
818 * so the search_note has all other properties unset.
821 NotePtr search_note (new Note<Time>(0, Time(), Time(), note->note(), 0));
823 for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
826 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
834 warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
840 cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
844 template<typename Time>
846 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
848 typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
850 while (i != _patch_changes.end() && ((*i)->time() == p->time())) {
852 typename Sequence<Time>::PatchChanges::iterator tmp = i;
856 _patch_changes.erase (i);
863 template<typename Time>
865 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
867 typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
868 while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
870 typename Sequence<Time>::SysExes::iterator tmp = i;
881 /** Append \a ev to model. NOT realtime safe.
883 * The timestamp of event is expected to be relative to
884 * the start of this model (t=0) and MUST be monotonically increasing
885 * and MUST be >= the latest event currently in the model.
887 template<typename Time>
889 Sequence<Time>::append(const Event<Time>& event, event_id_t evid)
891 WriteLock lock(write_lock());
893 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
895 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
898 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
899 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
903 if (ev.is_note_on() && ev.velocity() > 0) {
904 append_note_on_unlocked (ev, evid);
905 } else if (ev.is_note_off() || (ev.is_note_on() && ev.velocity() == 0)) {
906 /* XXX note: event ID is discarded because we merge the on+off events into
909 append_note_off_unlocked (ev);
910 } else if (ev.is_sysex()) {
911 append_sysex_unlocked(ev, evid);
912 } else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
913 /* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
914 if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
915 _bank[ev.channel()] &= ~(0x7f << 7);
916 _bank[ev.channel()] |= ev.cc_value() << 7;
918 _bank[ev.channel()] &= ~0x7f;
919 _bank[ev.channel()] |= ev.cc_value();
921 } else if (ev.is_cc()) {
922 append_control_unlocked(
923 Parameter(ev.event_type(), ev.channel(), ev.cc_number()),
924 ev.time(), ev.cc_value(), evid);
925 } else if (ev.is_pgm_change()) {
926 /* write a patch change with this program change and any previously set-up bank number */
927 append_patch_change_unlocked (PatchChange<Time> (ev.time(), ev.channel(), ev.pgm_number(), _bank[ev.channel()]), evid);
928 } else if (ev.is_pitch_bender()) {
929 append_control_unlocked(
930 Parameter(ev.event_type(), ev.channel()),
931 ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
932 | (0x7F & ev.pitch_bender_lsb())),
934 } else if (ev.is_channel_pressure()) {
935 append_control_unlocked(
936 Parameter(ev.event_type(), ev.channel()),
937 ev.time(), ev.channel_pressure(), evid);
938 } else if (!_type_map.type_is_midi(ev.event_type())) {
939 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
940 for (size_t i=0; i < ev.size(); ++i) {
941 printf("%X ", ev.buffer()[i]);
945 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
951 template<typename Time>
953 Sequence<Time>::append_note_on_unlocked (const MIDIEvent<Time>& ev, event_id_t evid)
955 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
956 (int)ev.channel(), (int)ev.note(),
957 ev.time(), (int)ev.velocity()));
960 if (ev.note() > 127) {
961 error << string_compose (_("invalid note on number (%1) ignored"), (int) ev.note()) << endmsg;
963 } else if (ev.channel() >= 16) {
964 error << string_compose (_("invalid note on channel (%1) ignored"), (int) ev.channel()) << endmsg;
966 } else if (ev.velocity() == 0) {
967 // Note on with velocity 0 handled as note off by caller
968 error << string_compose (_("invalid note on velocity (%1) ignored"), (int) ev.velocity()) << endmsg;
972 NotePtr note(new Note<Time>(ev.channel(), ev.time(), Time(), ev.note(), ev.velocity()));
975 add_note_unlocked (note);
977 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Appending active note on %1 channel %2\n",
978 (unsigned)(uint8_t)note->note(), note->channel()));
979 _write_notes[note->channel()].insert (note);
983 template<typename Time>
985 Sequence<Time>::append_note_off_unlocked (const MIDIEvent<Time>& ev)
987 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
988 this, (int)ev.channel(),
989 (int)ev.note(), ev.time(), (int)ev.velocity()));
992 if (ev.note() > 127) {
993 error << string_compose (_("invalid note off number (%1) ignored"), (int) ev.note()) << endmsg;
995 } else if (ev.channel() >= 16) {
996 error << string_compose (_("invalid note off channel (%1) ignored"), (int) ev.channel()) << endmsg;
1002 bool resolved = false;
1004 /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1005 matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1006 whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1010 /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1012 for (typename WriteNotes::iterator n = _write_notes[ev.channel()].begin(); n != _write_notes[ev.channel()].end(); ) {
1014 typename WriteNotes::iterator tmp = n;
1018 if (ev.note() == nn->note() && nn->channel() == ev.channel()) {
1019 assert(ev.time() >= nn->time());
1021 nn->set_length (ev.time() - nn->time());
1022 nn->set_off_velocity (ev.velocity());
1024 _write_notes[ev.channel()].erase(n);
1025 DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1034 cerr << this << " spurious note off chan " << (int)ev.channel()
1035 << ", note " << (int)ev.note() << " @ " << ev.time() << endl;
1039 template<typename Time>
1041 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1043 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1044 this, _type_map.to_symbol(param), time, value, _controls.size()));
1045 boost::shared_ptr<Control> c = control(param, true);
1046 c->list()->add (time.to_double(), value);
1047 /* XXX control events should use IDs */
1050 template<typename Time>
1052 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev, event_id_t /* evid */)
1054 #ifdef DEBUG_SEQUENCE
1055 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1056 for (size_t i=0; i < ev.size(); ++i) {
1057 cerr << int(ev.buffer()[i]) << " ";
1058 } cerr << "]" << endl;
1061 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
1062 /* XXX sysex events should use IDs */
1063 _sysexes.insert(event);
1066 template<typename Time>
1068 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1070 PatchChangePtr p (new PatchChange<Time> (ev));
1076 _patch_changes.insert (p);
1079 template<typename Time>
1081 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1084 p->set_id (Evoral::next_event_id ());
1087 _patch_changes.insert (p);
1090 template<typename Time>
1092 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1095 s->set_id (Evoral::next_event_id ());
1098 _sysexes.insert (s);
1101 template<typename Time>
1103 Sequence<Time>::contains (const NotePtr& note) const
1105 ReadLock lock (read_lock());
1106 return contains_unlocked (note);
1109 template<typename Time>
1111 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1113 const Pitches& p (pitches (note->channel()));
1114 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1116 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1117 i != p.end() && (*i)->note() == note->note(); ++i) {
1127 template<typename Time>
1129 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1131 ReadLock lock (read_lock());
1132 return overlaps_unlocked (note, without);
1135 template<typename Time>
1137 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1139 Time sa = note->time();
1140 Time ea = note->end_time();
1142 const Pitches& p (pitches (note->channel()));
1143 NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1145 for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1146 i != p.end() && (*i)->note() == note->note(); ++i) {
1148 if (without && (**i) == *without) {
1152 Time sb = (*i)->time();
1153 Time eb = (*i)->end_time();
1155 if (((sb > sa) && (eb <= ea)) ||
1156 ((eb >= sa) && (eb <= ea)) ||
1157 ((sb > sa) && (sb <= ea)) ||
1158 ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1166 template<typename Time>
1168 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1173 // CONST iterator implementations (x3)
1175 /** Return the earliest note with time >= t */
1176 template<typename Time>
1177 typename Sequence<Time>::Notes::const_iterator
1178 Sequence<Time>::note_lower_bound (Time t) const
1180 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1181 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1182 assert(i == _notes.end() || (*i)->time() >= t);
1186 /** Return the earliest patch change with time >= t */
1187 template<typename Time>
1188 typename Sequence<Time>::PatchChanges::const_iterator
1189 Sequence<Time>::patch_change_lower_bound (Time t) const
1191 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1192 typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1193 assert (i == _patch_changes.end() || (*i)->time() >= t);
1197 /** Return the earliest sysex with time >= t */
1198 template<typename Time>
1199 typename Sequence<Time>::SysExes::const_iterator
1200 Sequence<Time>::sysex_lower_bound (Time t) const
1202 SysExPtr search (new Event<Time> (0, t));
1203 typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1204 assert (i == _sysexes.end() || (*i)->time() >= t);
1208 // NON-CONST iterator implementations (x3)
1210 /** Return the earliest note with time >= t */
1211 template<typename Time>
1212 typename Sequence<Time>::Notes::iterator
1213 Sequence<Time>::note_lower_bound (Time t)
1215 NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1216 typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1217 assert(i == _notes.end() || (*i)->time() >= t);
1221 /** Return the earliest patch change with time >= t */
1222 template<typename Time>
1223 typename Sequence<Time>::PatchChanges::iterator
1224 Sequence<Time>::patch_change_lower_bound (Time t)
1226 PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1227 typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1228 assert (i == _patch_changes.end() || (*i)->time() >= t);
1232 /** Return the earliest sysex with time >= t */
1233 template<typename Time>
1234 typename Sequence<Time>::SysExes::iterator
1235 Sequence<Time>::sysex_lower_bound (Time t)
1237 SysExPtr search (new Event<Time> (0, t));
1238 typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1239 assert (i == _sysexes.end() || (*i)->time() >= t);
1243 template<typename Time>
1245 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1250 case PitchLessThanOrEqual:
1252 case PitchGreaterThanOrEqual:
1253 get_notes_by_pitch (n, op, val, chan_mask);
1257 case VelocityLessThan:
1258 case VelocityLessThanOrEqual:
1259 case VelocityGreater:
1260 case VelocityGreaterThanOrEqual:
1261 get_notes_by_velocity (n, op, val, chan_mask);
1266 template<typename Time>
1268 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1270 for (uint8_t c = 0; c < 16; ++c) {
1272 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1276 const Pitches& p (pitches (c));
1277 NotePtr search_note(new Note<Time>(0, Time(), Time(), val, 0));
1278 typename Pitches::const_iterator i;
1281 i = p.lower_bound (search_note);
1282 while (i != p.end() && (*i)->note() == val) {
1287 i = p.upper_bound (search_note);
1288 while (i != p.end() && (*i)->note() < val) {
1292 case PitchLessThanOrEqual:
1293 i = p.upper_bound (search_note);
1294 while (i != p.end() && (*i)->note() <= val) {
1299 i = p.lower_bound (search_note);
1300 while (i != p.end() && (*i)->note() > val) {
1304 case PitchGreaterThanOrEqual:
1305 i = p.lower_bound (search_note);
1306 while (i != p.end() && (*i)->note() >= val) {
1312 //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1313 abort(); /* NOTREACHED*/
1318 template<typename Time>
1320 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1322 ReadLock lock (read_lock());
1324 for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1326 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1332 if ((*i)->velocity() == val) {
1336 case VelocityLessThan:
1337 if ((*i)->velocity() < val) {
1341 case VelocityLessThanOrEqual:
1342 if ((*i)->velocity() <= val) {
1346 case VelocityGreater:
1347 if ((*i)->velocity() > val) {
1351 case VelocityGreaterThanOrEqual:
1352 if ((*i)->velocity() >= val) {
1357 // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1358 abort(); /* NOTREACHED*/
1364 template<typename Time>
1366 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1368 _overlap_pitch_resolution = opr;
1370 /* XXX todo: clean up existing overlaps in source data? */
1373 template<typename Time>
1375 Sequence<Time>::control_list_marked_dirty ()
1380 template<typename Time>
1382 Sequence<Time>::dump (ostream& str) const
1384 typename Sequence<Time>::const_iterator i;
1385 str << "+++ dump\n";
1386 for (i = begin(); i != end(); ++i) {
1389 str << "--- dump\n";
1392 template class Sequence<Evoral::Beats>;
1394 } // namespace Evoral