1 /* This file is part of Evoral.
2 * Copyright (C) 2008 Dave 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
19 #define __STDC_LIMIT_MACROS 1
27 #include "evoral/Control.hpp"
28 #include "evoral/ControlList.hpp"
29 #include "evoral/ControlSet.hpp"
30 #include "evoral/EventSink.hpp"
31 #include "evoral/MIDIParameters.hpp"
32 #include "evoral/Sequence.hpp"
33 #include "evoral/TypeMap.hpp"
34 #include "evoral/midi_util.h"
36 // #define DEBUG_SEQUENCE 1
38 #include <boost/format.hpp>
40 #define DUMP(x) cerr << (x);
49 // Read iterator (const_iterator)
51 template<typename Time>
52 Sequence<Time>::const_iterator::const_iterator()
55 , _control_iter(_control_iters.end())
57 _event = boost::shared_ptr< Event<Time> >(new Event<Time>());
60 template<typename Time>
61 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq, Time t)
64 , _is_end((t == DBL_MAX) || seq.empty())
65 , _note_iter(seq.notes().end())
66 , _sysex_iter(seq.sysexes().end())
67 , _control_iter(_control_iters.end())
69 DUMP(format("Created Iterator @ %1% (is end: %2%)\n)") % t % _is_end);
72 _lock = seq.read_lock();
77 typename Sequence<Time>::ReadLock lock(seq.read_lock());
79 // Find first note which begins at or after t
80 _note_iter = seq.note_lower_bound(t);
82 // Find first sysex event at or after t
83 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
84 i != seq.sysexes().end(); ++i) {
85 if ((*i)->time() >= t) {
90 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
92 // Find first control event after t
93 ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
94 _control_iters.reserve(seq._controls.size());
96 size_t earliest_control_index = 0;
97 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
98 DUMP(format("Iterator: control: %1%\n") % seq._type_map.to_symbol(i->first));
100 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y, true);
102 DUMP(format("Iterator: CC %1% (size %2%) has no events past %3%\n")
103 % i->first.id() % i->second->list()->size() % t);
109 if (y < i->first.min() || y > i->first.max()) {
110 cerr << "ERROR: Controller value " << y
111 << " out of range [" << i->first.min() << "," << i->first.max()
112 << "], event ignored" << endl;
116 DUMP(format("Iterator: CC %1% added (%2%, %3%)\n") % i->first.id() % x % y);
118 const ControlIterator new_iter(i->second->list(), x, y);
119 _control_iters.push_back(new_iter);
121 // Found a new earliest_control
122 if (x < earliest_control.x) {
123 earliest_control = new_iter;
124 earliest_control_index = _control_iters.size() - 1;
130 _control_iter = _control_iters.begin() + earliest_control_index;
131 assert(_control_iter != _control_iters.end());
133 _control_iter = _control_iters.end();
136 // Now find the earliest event overall and point to it
139 if (_note_iter != seq.notes().end()) {
141 earliest_t = (*_note_iter)->time();
144 if (_sysex_iter != seq.sysexes().end()
145 && ((*_sysex_iter)->time() < earliest_t || _type == NIL)) {
147 earliest_t = (*_sysex_iter)->time();
150 if (_control_iter != _control_iters.end()
151 && earliest_control.list && earliest_control.x >= t
152 && (earliest_control.x < earliest_t || _type == NIL)) {
154 earliest_t = earliest_control.x;
159 DUMP(format("Starting at note on event @ %1%\n") % earliest_t);
160 _event = boost::shared_ptr< Event<Time> >(
161 new Event<Time>((*_note_iter)->on_event(), true));
162 _active_notes.push(*_note_iter);
165 DUMP(format("Starting at sysex event @ %1%\n") % earliest_t);
166 _event = boost::shared_ptr< Event<Time> >(
167 new Event<Time>(*(*_sysex_iter), true));
170 DUMP(format("Starting at control event @ %1%\n") % earliest_t);
171 seq.control_to_midi_event(_event, earliest_control);
177 if (_type == NIL || !_event || _event->size() == 0) {
178 DUMP(format("Starting at end @ %1%\n") % t);
182 DUMP(printf("New iterator = 0x%x : 0x%x @ %f\n",
183 (int)_event->event_type(),
184 (int)((MIDIEvent<Time>*)_event.get())->type(),
186 assert(midi_event_is_valid(_event->buffer(), _event->size()));
190 template<typename Time>
191 Sequence<Time>::const_iterator::~const_iterator()
195 template<typename Time>
197 Sequence<Time>::const_iterator::invalidate()
199 while (!_active_notes.empty()) {
205 _note_iter = _seq->notes().end();
206 _sysex_iter = _seq->sysexes().end();
208 _control_iter = _control_iters.end();
212 template<typename Time>
213 const typename Sequence<Time>::const_iterator&
214 Sequence<Time>::const_iterator::operator++()
217 throw std::logic_error("Attempt to iterate past end of Sequence");
220 DUMP("Sequence::const_iterator++\n");
221 assert(_event && _event->buffer() && _event->size() > 0);
223 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
227 || ev.is_pgm_change()
228 || ev.is_pitch_bender()
229 || ev.is_channel_pressure()
230 || ev.is_sysex()) ) {
231 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
232 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
239 // Increment past current event
247 // Increment current controller iterator
248 ret = _control_iter->list->rt_safe_earliest_event_unlocked(
249 _control_iter->x, DBL_MAX, x, y, false);
250 assert(!ret || x > _control_iter->x);
252 _control_iter->x = x;
253 _control_iter->y = y;
255 _control_iter->list.reset();
256 _control_iter->x = DBL_MAX;
257 _control_iter->y = DBL_MAX;
260 // Find the controller with the next earliest event time
261 _control_iter = _control_iters.begin();
262 for (ControlIterators::iterator i = _control_iters.begin();
263 i != _control_iters.end(); ++i) {
264 if (i->x < _control_iter->x) {
276 // Now find the earliest event overall and point to it
278 Time earliest_t = std::numeric_limits<Time>::max();
280 // Next earliest note on
281 if (_note_iter != _seq->notes().end()) {
283 earliest_t = (*_note_iter)->time();
286 // Use the next note off iff it's earlier or the same time as the note on
287 if (!_seq->percussive() && (!_active_notes.empty())) {
288 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
290 earliest_t = _active_notes.top()->end_time();
294 // Use the next earliest controller iff it's earlier than the note event
295 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
296 if (_type == NIL || _control_iter->x < earliest_t) {
298 earliest_t = _control_iter->x;
302 // Use the next earliest SysEx iff it's earlier than the controller
303 if (_sysex_iter != _seq->sysexes().end()) {
304 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
306 earliest_t = (*_sysex_iter)->time();
310 // Set event to reflect new position
313 DUMP("iterator = note on\n");
314 *_event = (*_note_iter)->on_event();
315 _active_notes.push(*_note_iter);
318 DUMP("iterator = note off\n");
319 assert(!_active_notes.empty());
320 *_event = _active_notes.top()->off_event();
324 DUMP("iterator = control\n");
325 _seq->control_to_midi_event(_event, *_control_iter);
328 DUMP("iterator = sysex\n");
329 *_event = *(*_sysex_iter);
332 DUMP("iterator = end\n");
336 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
341 template<typename Time>
343 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
345 if (_seq != other._seq) {
347 } else if (_is_end || other._is_end) {
348 return (_is_end == other._is_end);
349 } else if (_type != other._type) {
352 return (_event == other._event);
356 template<typename Time>
357 typename Sequence<Time>::const_iterator&
358 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
361 _event = other._event;
362 _active_notes = other._active_notes;
364 _is_end = other._is_end;
365 _note_iter = other._note_iter;
366 _sysex_iter = other._sysex_iter;
367 _control_iters = other._control_iters;
370 _lock = _seq->read_lock();
374 if (other._control_iter == other._control_iters.end()) {
375 _control_iter = _control_iters.end();
377 const size_t index = other._control_iter - other._control_iters.begin();
378 _control_iter = _control_iters.begin() + index;
386 template<typename Time>
387 Sequence<Time>::Sequence(const TypeMap& type_map)
389 , _type_map(type_map)
391 , _end_iter(*this, DBL_MAX)
396 DUMP(format("Sequence constructed: %1%\n") % this);
397 assert(_end_iter._is_end);
398 assert( ! _end_iter._lock);
401 template<typename Time>
402 Sequence<Time>::Sequence(const Sequence<Time>& other)
405 , _type_map(other._type_map)
407 , _end_iter(*this, DBL_MAX)
408 , _percussive(other._percussive)
409 , _lowest_note(other._lowest_note)
410 , _highest_note(other._highest_note)
412 for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
413 boost::shared_ptr<Note<Time> > n (new Note<Time> (**i));
417 for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
418 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
419 _sysexes.push_back (n);
422 DUMP(format("Sequence copied: %1%\n") % this);
423 assert(_end_iter._is_end);
424 assert(! _end_iter._lock);
427 /** Write the controller event pointed to by \a iter to \a ev.
428 * The buffer of \a ev will be allocated or resized as necessary.
429 * The event_type of \a ev should be set to the expected output type.
430 * \return true on success
432 template<typename Time>
434 Sequence<Time>::control_to_midi_event(
435 boost::shared_ptr< Event<Time> >& ev,
436 const ControlIterator& iter) const
438 assert(iter.list.get());
439 const uint32_t event_type = iter.list->parameter().type();
441 // initialize the event pointer with a new event, if necessary
443 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
446 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
447 ev->set_event_type(_type_map.midi_event_type(midi_type));
449 case MIDI_CMD_CONTROL:
450 assert(iter.list.get());
451 assert(iter.list->parameter().channel() < 16);
452 assert(iter.list->parameter().id() <= INT8_MAX);
453 assert(iter.y <= INT8_MAX);
457 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
458 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
459 ev->buffer()[2] = (uint8_t)iter.y;
462 case MIDI_CMD_PGM_CHANGE:
463 assert(iter.list.get());
464 assert(iter.list->parameter().channel() < 16);
465 assert(iter.y <= INT8_MAX);
469 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
470 ev->buffer()[1] = (uint8_t)iter.y;
473 case MIDI_CMD_BENDER:
474 assert(iter.list.get());
475 assert(iter.list->parameter().channel() < 16);
476 assert(iter.y < (1<<14));
480 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
481 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
482 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
485 case MIDI_CMD_CHANNEL_PRESSURE:
486 assert(iter.list.get());
487 assert(iter.list->parameter().channel() < 16);
488 assert(iter.y <= INT8_MAX);
492 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
493 ev->buffer()[1] = (uint8_t)iter.y;
503 /** Clear all events from the model.
505 template<typename Time>
507 Sequence<Time>::clear()
509 WriteLock lock(write_lock());
511 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
512 li->second->list()->clear();
515 /** Begin a write of events to the model.
517 * If \a mode is Sustained, complete notes with length are constructed as note
518 * on/off events are received. Otherwise (Percussive), only note on events are
519 * stored; note off events are discarded entirely and all contained notes will
522 template<typename Time>
524 Sequence<Time>::start_write()
526 DUMP(format("%1% : start_write (percussive = %2%)\n") % this % _percussive);
527 WriteLock lock(write_lock());
529 for (int i = 0; i < 16; ++i) {
530 _write_notes[i].clear();
532 _dirty_controls.clear();
535 /** Finish a write of events to the model.
537 * If \a delete_stuck is true and the current mode is Sustained, note on events
538 * that were never resolved with a corresonding note off will be deleted.
539 * Otherwise they will remain as notes with length 0.
541 template<typename Time>
543 Sequence<Time>::end_write(bool delete_stuck)
545 WriteLock lock(write_lock());
551 DUMP(format("%1% : end_write (%2% notes)\n") % this % _notes.size());
553 if (!_percussive && delete_stuck) {
554 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
555 typename Notes::iterator next = n;
557 if ((*n)->length() == 0) {
558 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
565 for (int i = 0; i < 16; ++i) {
566 if (!_write_notes[i].empty()) {
567 cerr << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
568 << _write_notes[i].size() << " stuck notes" << endl;
570 _write_notes[i].clear();
573 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
580 /** Append \a ev to model. NOT realtime safe.
582 * Timestamps of events in \a buf are expected to be relative to
583 * the start of this model (t=0) and MUST be monotonically increasing
584 * and MUST be >= the latest event currently in the model.
586 template<typename Time>
588 Sequence<Time>::append(const Event<Time>& event)
590 WriteLock lock(write_lock());
593 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
595 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
598 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
599 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
603 if (ev.is_note_on()) {
604 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
605 } else if (ev.is_note_off()) {
606 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
607 } else if (ev.is_sysex()) {
608 append_sysex_unlocked(ev);
609 } else if (!_type_map.type_is_midi(ev.event_type())) {
610 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
611 for (size_t i=0; i < ev.size(); ++i) {
612 printf("%X ", ev.buffer()[i]);
615 } else if (ev.is_cc()) {
616 append_control_unlocked(
617 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
618 ev.time(), ev.cc_value());
619 } else if (ev.is_pgm_change()) {
620 append_control_unlocked(
621 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
622 ev.time(), ev.pgm_number());
623 } else if (ev.is_pitch_bender()) {
624 append_control_unlocked(
625 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
626 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
627 | (0x7F & ev.pitch_bender_lsb()) ));
628 } else if (ev.is_channel_pressure()) {
629 append_control_unlocked(
630 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
631 ev.time(), ev.channel_pressure());
633 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
637 template<typename Time>
639 Sequence<Time>::append_note_on_unlocked(uint8_t chan, Time time, uint8_t note_num, uint8_t velocity)
641 DUMP(format("%1% c=%2% note %3% on @ %4% v=%5%\n")
642 % this % (int)chan % (int)note_num % time % (int)velocity);
643 assert(note_num <= 127);
649 append_note_off_unlocked(chan, time, note_num);
653 if (note_num < _lowest_note)
654 _lowest_note = note_num;
655 if (note_num > _highest_note)
656 _highest_note = note_num;
658 boost::shared_ptr< Note<Time> > new_note(new Note<Time>(chan, time, 0, note_num, velocity));
659 _notes.insert(new_note);
661 DUMP(format("Sustained: Appending active note on %1% channel %2%\n")
662 % (unsigned)(uint8_t)note_num % chan);
663 _write_notes[chan].insert(new_note);
665 DUMP("Percussive: NOT appending active note on\n");
669 template<typename Time>
671 Sequence<Time>::append_note_off_unlocked(uint8_t chan, Time time, uint8_t note_num)
673 DUMP(format("%1% c=%2% note %3% off @ %4%\n")
674 % this % (int)chan % (int)note_num % time);
675 assert(note_num <= 127);
681 DUMP("Sequence Ignoring note off (percussive mode)\n");
685 // TODO: support note off velocity
687 bool resolved = false;
688 for (typename WriteNotes::iterator n = _write_notes[chan].begin();
689 n != _write_notes[chan].end(); ++n) {
690 boost::shared_ptr< Note<Time> > note = *n;
691 if (note->note() == note_num) {
692 assert(time >= note->time());
693 note->set_length(time - note->time());
694 _write_notes[chan].erase(n);
695 DUMP(format("resolved note, length: %1%\n") % note->length());
702 cerr << this << " spurious note off chan " << (int)chan
703 << ", note " << (int)note_num << " @ " << time << endl;
707 template<typename Time>
709 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value)
711 DUMP(format("%1% %2% @ %3%\t=\t%4% # controls: %5%\n")
712 % this % _type_map.to_symbol(param) % time % value % _controls.size());
713 boost::shared_ptr<Control> c = control(param, true);
714 c->list()->rt_add(time, value);
717 template<typename Time>
719 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev)
721 #ifdef DEBUG_SEQUENCE
722 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
723 for (size_t i=0; i < ev.size(); ++i) {
724 cerr << int(ev.buffer()[i]) << " ";
725 } cerr << "]" << endl;
728 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
729 _sysexes.push_back(event);
732 template<typename Time>
734 Sequence<Time>::contains(const boost::shared_ptr< Note<Time> > note) const
736 ReadLock lock (read_lock());
738 for (typename Sequence<Time>::Notes::const_iterator i = note_lower_bound(note->time());
739 i != _notes.end() && (*i)->time() == note->time(); ++i) {
741 cerr << "Existing note matches: " << *i << endl;
745 cerr << "No matching note for " << note << endl;
749 template<typename Time>
751 Sequence<Time>::add_note_unlocked(const boost::shared_ptr< Note<Time> > note)
753 DUMP(format("%1% add note %2% @ %3%\n") % this % (int)note->note() % note->time());
755 for (typename Sequence<Time>::Notes::iterator i = note_lower_bound(note->time());
756 i != _notes.end() && (*i)->time() == note->time(); ++i) {
767 template<typename Time>
769 Sequence<Time>::remove_note_unlocked(const boost::shared_ptr< const Note<Time> > note)
772 DUMP(format("%1% remove note %2% @ %3%\n") % this % (int)note->note() % note->time());
773 for (typename Sequence<Time>::Notes::iterator i = note_lower_bound(note->time());
774 i != _notes.end() && (*i)->time() == note->time(); ++i) {
779 cerr << "Unable to find note to erase" << endl;
782 template<typename Time>
784 Sequence<Time>::set_notes (const Sequence<Time>::Notes& n)
789 /** Return the earliest note with time >= t */
790 template<typename Time>
791 typename Sequence<Time>::Notes::const_iterator
792 Sequence<Time>::note_lower_bound (Time t) const
794 boost::shared_ptr< Note<Time> > search_note(new Note<Time>(0, t, 0, 0, 0));
795 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
796 assert(i == _notes.end() || (*i)->time() >= t);
800 template<typename Time>
802 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
804 ReadLock lock (read_lock());
806 for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
808 if (chan_mask != 0 && !((1<<(*i)->channel()) & chan_mask)) {
814 if ((*i)->note() == val) {
819 if ((*i)->note() < val) {
823 case PitchLessThanOrEqual:
824 if ((*i)->note() <= val) {
829 if ((*i)->note() > val) {
833 case PitchGreaterThanOrEqual:
834 if ((*i)->note() >= val) {
839 if ((*i)->velocity() == val) {
843 case VelocityLessThan:
844 if ((*i)->velocity() < val) {
848 case VelocityLessThanOrEqual:
849 if ((*i)->velocity() <= val) {
853 case VelocityGreater:
854 if ((*i)->velocity() > val) {
858 case VelocityGreaterThanOrEqual:
859 if ((*i)->velocity() >= val) {
867 template class Sequence<Evoral::MusicalTime>;
869 } // namespace Evoral