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 template<typename Time>
50 void Sequence<Time>::write_lock() {
55 template<typename Time>
56 void Sequence<Time>::write_unlock() {
57 _lock.writer_unlock();
58 _control_lock.unlock();
61 template<typename Time>
62 void Sequence<Time>::read_lock() const {
66 template<typename Time>
67 void Sequence<Time>::read_unlock() const {
68 _lock.reader_unlock();
72 // Read iterator (const_iterator)
74 template<typename Time>
75 Sequence<Time>::const_iterator::const_iterator()
79 , _control_iter(_control_iters.end())
81 _event = boost::shared_ptr< Event<Time> >(new Event<Time>());
84 template<typename Time>
85 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq, Time t)
88 , _is_end((t == DBL_MAX) || seq.empty())
90 , _note_iter(seq.notes().end())
91 , _sysex_iter(seq.sysexes().end())
92 , _control_iter(_control_iters.end())
94 DUMP(format("Created Iterator @ %1% (is end: %2%)\n)") % t % _is_end);
102 // Find first note which begins at or after t
103 _note_iter = seq.note_lower_bound(t);
105 // Find first sysex event at or after t
106 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
107 i != seq.sysexes().end(); ++i) {
108 if ((*i)->time() >= t) {
113 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
115 // Find first control event after t
116 ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
117 _control_iters.reserve(seq._controls.size());
119 size_t earliest_control_index = 0;
120 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
121 DUMP(format("Iterator: control: %1%\n") % seq._type_map.to_symbol(i->first));
123 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
125 DUMP(format("Iterator: CC %1% (size %2%) has no events past %3%\n")
126 % i->first.id() % i->second->list()->size() % t);
132 if (y < i->first.min() || y > i->first.max()) {
133 cerr << "ERROR: Controller value " << y
134 << " out of range [" << i->first.min() << "," << i->first.max()
135 << "], event ignored" << endl;
139 DUMP(format("Iterator: CC %1% added (%2%, %3%)\n") % i->first.id() % x % y);
141 const ControlIterator new_iter(i->second->list(), x, y);
142 _control_iters.push_back(new_iter);
144 // Found a new earliest_control
145 if (x < earliest_control.x) {
146 earliest_control = new_iter;
147 earliest_control_index = _control_iters.size() - 1;
153 _control_iter = _control_iters.begin() + earliest_control_index;
155 _control_iter = _control_iters.end();
158 // Now find the earliest event overall and point to it
161 if (_note_iter != seq.notes().end()) {
163 earliest_t = (*_note_iter)->time();
166 if (_sysex_iter != seq.sysexes().end() && (*_sysex_iter)->time() < earliest_t) {
168 earliest_t = (*_sysex_iter)->time();
171 if (_control_iter != _control_iters.end()
172 && earliest_control.list && earliest_control.x >= t
173 && earliest_control.x < earliest_t) {
175 earliest_t = earliest_control.x;
180 DUMP(format("Starting at note on event @ %1%\n") % earliest_t);
181 _event = boost::shared_ptr< Event<Time> >(
182 new Event<Time>((*_note_iter)->on_event(), true));
183 _active_notes.push(*_note_iter);
186 DUMP(format("Starting at sysex event @ %1%\n") % earliest_t);
187 _event = boost::shared_ptr< Event<Time> >(
188 new Event<Time>(*(*_sysex_iter), true));
191 DUMP(format("Starting at control event @ %1%\n") % earliest_t);
192 seq.control_to_midi_event(_event, earliest_control);
198 if (_type == NIL || !_event || _event->size() == 0) {
199 DUMP(format("Starting at end @ %1%\n") % t);
205 DUMP(printf("New iterator = 0x%x : 0x%x @ %f\n",
206 (int)_event->event_type(),
207 (int)((MIDIEvent<Time>*)_event.get())->type(),
209 assert(midi_event_is_valid(_event->buffer(), _event->size()));
213 template<typename Time>
214 Sequence<Time>::const_iterator::~const_iterator()
221 template<typename Time>
223 Sequence<Time>::const_iterator::invalidate()
225 while (!_active_notes.empty()) {
231 _note_iter = _seq->notes().end();
232 _sysex_iter = _seq->sysexes().end();
234 _control_iter = _control_iters.end();
241 template<typename Time>
242 const typename Sequence<Time>::const_iterator&
243 Sequence<Time>::const_iterator::operator++()
246 throw std::logic_error("Attempt to iterate past end of Sequence");
249 DUMP("Sequence::const_iterator++\n");
250 assert(_event && _event->buffer() && _event->size() > 0);
252 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
256 || ev.is_pgm_change()
257 || ev.is_pitch_bender()
258 || ev.is_channel_pressure()
259 || ev.is_sysex()) ) {
260 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
261 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
268 // Increment past current event
276 // Increment current controller iterator
277 ret = _control_iter->list->rt_safe_earliest_event_unlocked(
278 _control_iter->x, DBL_MAX, x, y, false);
279 assert(!ret || x > _control_iter->x);
281 _control_iter->x = x;
282 _control_iter->y = y;
284 _control_iter->list.reset();
285 _control_iter->x = DBL_MAX;
286 _control_iter->y = DBL_MAX;
289 // Find the controller with the next earliest event time
290 _control_iter = _control_iters.begin();
291 for (ControlIterators::iterator i = _control_iters.begin();
292 i != _control_iters.end(); ++i) {
293 if (i->x < _control_iter->x) {
305 // Now find the earliest event overall and point to it
307 Time earliest_t = std::numeric_limits<Time>::max();
309 // Next earliest note on
310 if (_note_iter != _seq->notes().end()) {
312 earliest_t = (*_note_iter)->time();
315 // Use the next note off iff it's earlier or the same time as the note on
316 if (!_seq->percussive() && (!_active_notes.empty())) {
317 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
319 earliest_t = _active_notes.top()->end_time();
323 // Use the next earliest controller iff it's earlier than the note event
324 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
325 if (_type == NIL || _control_iter->x < earliest_t) {
327 earliest_t = _control_iter->x;
331 // Use the next earliest SysEx iff it's earlier than the controller
332 if (_sysex_iter != _seq->sysexes().end()) {
333 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
335 earliest_t = (*_sysex_iter)->time();
339 // Set event to reflect new position
342 DUMP("iterator = note on\n");
343 *_event = (*_note_iter)->on_event();
344 _active_notes.push(*_note_iter);
347 DUMP("iterator = note off\n");
348 assert(!_active_notes.empty());
349 *_event = _active_notes.top()->off_event();
353 DUMP("iterator = control\n");
354 _seq->control_to_midi_event(_event, *_control_iter);
357 DUMP("iterator = sysex\n");
358 *_event = *(*_sysex_iter);
361 DUMP("iterator = end\n");
365 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
370 template<typename Time>
372 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
374 if (_seq != other._seq) {
376 } else if (_is_end || other._is_end) {
377 return (_is_end == other._is_end);
378 } else if (_type != other._type) {
381 return (_event == other._event);
385 template<typename Time>
386 typename Sequence<Time>::const_iterator&
387 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
389 if (_seq != other._seq) {
394 other._seq->read_lock();
396 } else if (!_locked && other._locked) {
401 _event = other._event;
402 _active_notes = other._active_notes;
404 _is_end = other._is_end;
405 _locked = other._locked;
406 _note_iter = other._note_iter;
407 _sysex_iter = other._sysex_iter;
408 _control_iters = other._control_iters;
410 if (other._control_iter == other._control_iters.end()) {
411 _control_iter = _control_iters.end();
413 const size_t index = other._control_iter - other._control_iters.begin();
414 _control_iter = _control_iters.begin() + index;
422 template<typename Time>
423 Sequence<Time>::Sequence(const TypeMap& type_map)
425 , _type_map(type_map)
427 , _end_iter(*this, DBL_MAX)
432 DUMP(format("Sequence (size %1%) constructed: %2%\n") % size % this);
433 assert(_end_iter._is_end);
434 assert( ! _end_iter._locked);
437 /** Write the controller event pointed to by \a iter to \a ev.
438 * The buffer of \a ev will be allocated or resized as necessary.
439 * The event_type of \a ev should be set to the expected output type.
440 * \return true on success
442 template<typename Time>
444 Sequence<Time>::control_to_midi_event(
445 boost::shared_ptr< Event<Time> >& ev,
446 const ControlIterator& iter) const
448 assert(iter.list.get());
449 const uint32_t event_type = iter.list->parameter().type();
451 // initialize the event pointer with a new event, if necessary
453 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
456 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
457 ev->set_event_type(_type_map.midi_event_type(midi_type));
459 case MIDI_CMD_CONTROL:
460 assert(iter.list.get());
461 assert(iter.list->parameter().channel() < 16);
462 assert(iter.list->parameter().id() <= INT8_MAX);
463 assert(iter.y <= INT8_MAX);
467 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
468 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
469 ev->buffer()[2] = (uint8_t)iter.y;
472 case MIDI_CMD_PGM_CHANGE:
473 assert(iter.list.get());
474 assert(iter.list->parameter().channel() < 16);
475 assert(iter.y <= INT8_MAX);
479 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
480 ev->buffer()[1] = (uint8_t)iter.y;
483 case MIDI_CMD_BENDER:
484 assert(iter.list.get());
485 assert(iter.list->parameter().channel() < 16);
486 assert(iter.y < (1<<14));
490 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
491 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
492 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
495 case MIDI_CMD_CHANNEL_PRESSURE:
496 assert(iter.list.get());
497 assert(iter.list->parameter().channel() < 16);
498 assert(iter.y <= INT8_MAX);
502 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
503 ev->buffer()[1] = (uint8_t)iter.y;
513 /** Clear all events from the model.
515 template<typename Time>
517 Sequence<Time>::clear()
521 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
522 li->second->list()->clear();
523 _lock.writer_unlock();
526 /** Begin a write of events to the model.
528 * If \a mode is Sustained, complete notes with length are constructed as note
529 * on/off events are received. Otherwise (Percussive), only note on events are
530 * stored; note off events are discarded entirely and all contained notes will
533 template<typename Time>
535 Sequence<Time>::start_write()
537 DUMP(format("%1% : start_write (percussive = %2%)\n") % this % _percussive);
540 for (int i = 0; i < 16; ++i) {
541 _write_notes[i].clear();
543 _dirty_controls.clear();
547 /** Finish a write of events to the model.
549 * If \a delete_stuck is true and the current mode is Sustained, note on events
550 * that were never resolved with a corresonding note off will be deleted.
551 * Otherwise they will remain as notes with length 0.
553 template<typename Time>
555 Sequence<Time>::end_write(bool delete_stuck)
564 DUMP(format("%1% : end_write (%2% notes)\n") % this % _notes.size());
566 if (!_percussive && delete_stuck) {
567 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
568 typename Notes::iterator next = n;
570 if ((*n)->length() == 0) {
571 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
578 for (int i = 0; i < 16; ++i) {
579 if (!_write_notes[i].empty()) {
580 cerr << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
581 << _write_notes[i].size() << " stuck notes" << endl;
583 _write_notes[i].clear();
586 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
594 /** Append \a ev to model. NOT realtime safe.
596 * Timestamps of events in \a buf are expected to be relative to
597 * the start of this model (t=0) and MUST be monotonically increasing
598 * and MUST be >= the latest event currently in the model.
600 template<typename Time>
602 Sequence<Time>::append(const Event<Time>& event)
607 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
609 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
612 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
613 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
618 if (ev.is_note_on()) {
619 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
620 } else if (ev.is_note_off()) {
621 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
622 } else if (ev.is_sysex()) {
623 append_sysex_unlocked(ev);
624 } else if (!_type_map.type_is_midi(ev.event_type())) {
625 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
626 for (size_t i=0; i < ev.size(); ++i) {
627 printf("%X ", ev.buffer()[i]);
630 } else if (ev.is_cc()) {
631 append_control_unlocked(
632 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
633 ev.time(), ev.cc_value());
634 } else if (ev.is_pgm_change()) {
635 append_control_unlocked(
636 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
637 ev.time(), ev.pgm_number());
638 } else if (ev.is_pitch_bender()) {
639 append_control_unlocked(
640 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
641 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
642 | (0x7F & ev.pitch_bender_lsb()) ));
643 } else if (ev.is_channel_pressure()) {
644 append_control_unlocked(
645 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
646 ev.time(), ev.channel_pressure());
648 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
654 template<typename Time>
656 Sequence<Time>::append_note_on_unlocked(uint8_t chan, Time time, uint8_t note_num, uint8_t velocity)
658 DUMP(format("%1% c=%2% note %3% on @ %4% v=%5%\n")
659 % this % (int)chan % (int)note_num % time % (int)velocity);
660 assert(note_num <= 127);
666 append_note_off_unlocked(chan, time, note_num);
670 if (note_num < _lowest_note)
671 _lowest_note = note_num;
672 if (note_num > _highest_note)
673 _highest_note = note_num;
675 boost::shared_ptr< Note<Time> > new_note(new Note<Time>(chan, time, 0, note_num, velocity));
676 _notes.insert(new_note);
678 DUMP(format("Sustained: Appending active note on %1% channel %2%\n")
679 % (unsigned)(uint8_t)note_num % chan);
680 _write_notes[chan].insert(new_note);
682 DUMP("Percussive: NOT appending active note on\n");
686 template<typename Time>
688 Sequence<Time>::append_note_off_unlocked(uint8_t chan, Time time, uint8_t note_num)
690 DUMP(format("%1% c=%2% note %3% off @ %4%\n")
691 % this % (int)chan % (int)note_num % time);
692 assert(note_num <= 127);
698 DUMP("Sequence Ignoring note off (percussive mode)\n");
702 // TODO: support note off velocity
704 bool resolved = false;
705 for (typename WriteNotes::iterator n = _write_notes[chan].begin();
706 n != _write_notes[chan].end(); ++n) {
707 boost::shared_ptr< Note<Time> > note = *n;
708 if (note->note() == note_num) {
709 assert(time >= note->time());
710 note->set_length(time - note->time());
711 _write_notes[chan].erase(n);
712 DUMP(format("resolved note, length: %1%\n") % note.length());
719 cerr << this << " spurious note off chan " << (int)chan
720 << ", note " << (int)note_num << " @ " << time << endl;
724 template<typename Time>
726 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value)
728 DUMP(format("%1% %2% @ %3%\t=\t%4% # controls: %5%\n")
729 % this % _type_map.to_symbol(param) % time % value % _controls.size());
730 boost::shared_ptr<Control> c = control(param, true);
731 c->list()->rt_add(time, value);
734 template<typename Time>
736 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev)
738 #ifdef DEBUG_SEQUENCE
739 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
740 for (size_t i=0; i < ev.size(); ++i) {
741 cerr << int(ev.buffer()[i]) << " ";
742 } cerr << "]" << endl;
745 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
746 _sysexes.push_back(event);
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 typename Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
756 note_time_comparator);
757 _notes.insert(i, note);
760 template<typename Time>
762 Sequence<Time>::remove_note_unlocked(const boost::shared_ptr< const Note<Time> > note)
765 DUMP(format("%1% remove note %2% @ %3%\n") % this % (int)note->note() % note->time());
766 for (typename Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
767 if (*(*n) == *note) {
774 template<typename Time>
776 Sequence<Time>::set_notes (const Sequence<Time>::Notes& n)
781 /** Return the earliest note with time >= t */
782 template<typename Time>
783 typename Sequence<Time>::Notes::const_iterator
784 Sequence<Time>::note_lower_bound (Time t) const
786 boost::shared_ptr< Note<Time> > search_note(new Note<Time>(0, t, 0, 0, 0));
787 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
788 assert(i == _notes.end() || (*i)->time() >= t);
792 template class Sequence<Evoral::MusicalTime>;
794 } // namespace Evoral