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 after t
103 boost::shared_ptr< Note<Time> > search_note(new Note<Time>(0, t, 0, 0, 0));
104 _note_iter = seq.notes().lower_bound(search_note);
105 assert(_note_iter == seq.notes().end() || (*_note_iter)->time() >= t);
107 // Find first sysex event after t
108 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
109 i != seq.sysexes().end(); ++i) {
110 if ((*i)->time() >= t) {
115 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
117 // Find first control event after t
118 ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
119 _control_iters.reserve(seq._controls.size());
121 size_t earliest_control_index = 0;
122 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
123 DUMP(format("Iterator: control: %1%\n") % seq._type_map.to_symbol(i->first));
125 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
127 DUMP(format("Iterator: CC %1% (size %2%) has no events past %3%\n")
128 % i->first.id() % i->second->list()->size() % t);
134 if (y < i->first.min() || y > i->first.max()) {
135 cerr << "ERROR: Controller value " << y
136 << " out of range [" << i->first.min() << "," << i->first.max()
137 << "], event ignored" << endl;
141 DUMP(format("Iterator: CC %1% added (%2%, %3%)\n") % i->first.id() % x % y);
143 const ControlIterator new_iter(i->second->list(), x, y);
144 _control_iters.push_back(new_iter);
146 // Found a new earliest_control
147 if (x < earliest_control.x) {
148 earliest_control = new_iter;
149 earliest_control_index = _control_iters.size() - 1;
155 _control_iter = _control_iters.begin() + earliest_control_index;
157 _control_iter = _control_iters.end();
160 // Now find the earliest event overall and point to it
163 if (_note_iter != seq.notes().end()) {
165 earliest_t = (*_note_iter)->time();
168 if (_sysex_iter != seq.sysexes().end() && (*_sysex_iter)->time() < earliest_t) {
170 earliest_t = (*_sysex_iter)->time();
173 if (_control_iter != _control_iters.end()
174 && earliest_control.list && earliest_control.x >= t
175 && earliest_control.x < earliest_t) {
177 earliest_t = earliest_control.x;
182 DUMP(format("Starting at note on event @ %1%\n") % earliest_t);
183 _event = boost::shared_ptr< Event<Time> >(
184 new Event<Time>((*_note_iter)->on_event(), true));
185 _active_notes.push(*_note_iter);
188 DUMP(format("Starting at sysex event @ %1%\n") % earliest_t);
189 _event = boost::shared_ptr< Event<Time> >(
190 new Event<Time>(*(*_sysex_iter), true));
193 DUMP(format("Starting at control event @ %1%\n") % earliest_t);
194 seq.control_to_midi_event(_event, earliest_control);
200 if (_type == NIL || !_event || _event->size() == 0) {
201 DUMP(format("Starting at end @ %1%\n") % t);
207 DUMP(printf("New iterator = 0x%x : 0x%x @ %f\n",
208 (int)_event->event_type(),
209 (int)((MIDIEvent<Time>*)_event.get())->type(),
211 assert(midi_event_is_valid(_event->buffer(), _event->size()));
215 template<typename Time>
216 Sequence<Time>::const_iterator::~const_iterator()
223 template<typename Time>
225 Sequence<Time>::const_iterator::invalidate()
227 while (!_active_notes.empty()) {
233 _note_iter = _seq->notes().end();
234 _sysex_iter = _seq->sysexes().end();
236 _control_iter = _control_iters.end();
243 template<typename Time>
244 const typename Sequence<Time>::const_iterator&
245 Sequence<Time>::const_iterator::operator++()
248 throw std::logic_error("Attempt to iterate past end of Sequence");
251 DUMP("Sequence::const_iterator++\n");
252 assert(_event && _event->buffer() && _event->size() > 0);
254 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
258 || ev.is_pgm_change()
259 || ev.is_pitch_bender()
260 || ev.is_channel_pressure()
261 || ev.is_sysex()) ) {
262 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
263 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
270 // Increment past current event
278 // Increment current controller iterator
279 ret = _control_iter->list->rt_safe_earliest_event_unlocked(
280 _control_iter->x, DBL_MAX, x, y, false);
281 assert(!ret || x > _control_iter->x);
283 _control_iter->x = x;
284 _control_iter->y = y;
286 _control_iter->list.reset();
287 _control_iter->x = DBL_MAX;
288 _control_iter->y = DBL_MAX;
291 // Find the controller with the next earliest event time
292 _control_iter = _control_iters.begin();
293 for (ControlIterators::iterator i = _control_iters.begin();
294 i != _control_iters.end(); ++i) {
295 if (i->x < _control_iter->x) {
307 // Now find the earliest event overall and point to it
309 Time earliest_t = std::numeric_limits<Time>::max();
311 // Next earliest note on
312 if (_note_iter != _seq->notes().end()) {
314 earliest_t = (*_note_iter)->time();
317 // Use the next note off iff it's earlier or the same time as the note on
318 if (!_seq->percussive() && (!_active_notes.empty())) {
319 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
321 earliest_t = _active_notes.top()->end_time();
325 // Use the next earliest controller iff it's earlier than the note event
326 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
327 if (_type == NIL || _control_iter->x < earliest_t) {
329 earliest_t = _control_iter->x;
333 // Use the next earliest SysEx iff it's earlier than the controller
334 if (_sysex_iter != _seq->sysexes().end()) {
335 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
337 earliest_t = (*_sysex_iter)->time();
341 // Set event to reflect new position
344 DUMP("iterator = note on\n");
345 *_event = (*_note_iter)->on_event();
346 _active_notes.push(*_note_iter);
349 DUMP("iterator = note off\n");
350 assert(!_active_notes.empty());
351 *_event = _active_notes.top()->off_event();
355 DUMP("iterator = control\n");
356 _seq->control_to_midi_event(_event, *_control_iter);
359 DUMP("iterator = sysex\n");
360 *_event = *(*_sysex_iter);
363 DUMP("iterator = end\n");
367 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
372 template<typename Time>
374 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
376 if (_seq != other._seq) {
378 } else if (_is_end || other._is_end) {
379 return (_is_end == other._is_end);
380 } else if (_type != other._type) {
383 return (_event == other._event);
387 template<typename Time>
388 typename Sequence<Time>::const_iterator&
389 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
391 if (_seq != other._seq) {
396 other._seq->read_lock();
398 } else if (!_locked && other._locked) {
403 _event = other._event;
404 _active_notes = other._active_notes;
406 _is_end = other._is_end;
407 _locked = other._locked;
408 _note_iter = other._note_iter;
409 _sysex_iter = other._sysex_iter;
410 _control_iters = other._control_iters;
412 if (other._control_iter == other._control_iters.end()) {
413 _control_iter = _control_iters.end();
415 const size_t index = other._control_iter - other._control_iters.begin();
416 _control_iter = _control_iters.begin() + index;
424 template<typename Time>
425 Sequence<Time>::Sequence(const TypeMap& type_map)
427 , _type_map(type_map)
429 , _end_iter(*this, DBL_MAX)
434 DUMP(format("Sequence (size %1%) constructed: %2%\n") % size % this);
435 assert(_end_iter._is_end);
436 assert( ! _end_iter._locked);
439 /** Write the controller event pointed to by \a iter to \a ev.
440 * The buffer of \a ev will be allocated or resized as necessary.
441 * The event_type of \a ev should be set to the expected output type.
442 * \return true on success
444 template<typename Time>
446 Sequence<Time>::control_to_midi_event(
447 boost::shared_ptr< Event<Time> >& ev,
448 const ControlIterator& iter) const
450 assert(iter.list.get());
451 const uint32_t event_type = iter.list->parameter().type();
453 // initialize the event pointer with a new event, if necessary
455 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
458 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
459 ev->set_event_type(_type_map.midi_event_type(midi_type));
461 case MIDI_CMD_CONTROL:
462 assert(iter.list.get());
463 assert(iter.list->parameter().channel() < 16);
464 assert(iter.list->parameter().id() <= INT8_MAX);
465 assert(iter.y <= INT8_MAX);
469 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
470 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
471 ev->buffer()[2] = (uint8_t)iter.y;
474 case MIDI_CMD_PGM_CHANGE:
475 assert(iter.list.get());
476 assert(iter.list->parameter().channel() < 16);
477 assert(iter.y <= INT8_MAX);
481 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
482 ev->buffer()[1] = (uint8_t)iter.y;
485 case MIDI_CMD_BENDER:
486 assert(iter.list.get());
487 assert(iter.list->parameter().channel() < 16);
488 assert(iter.y < (1<<14));
492 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
493 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
494 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
497 case MIDI_CMD_CHANNEL_PRESSURE:
498 assert(iter.list.get());
499 assert(iter.list->parameter().channel() < 16);
500 assert(iter.y <= INT8_MAX);
504 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
505 ev->buffer()[1] = (uint8_t)iter.y;
515 /** Clear all events from the model.
517 template<typename Time>
519 Sequence<Time>::clear()
523 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
524 li->second->list()->clear();
525 _lock.writer_unlock();
528 /** Begin a write of events to the model.
530 * If \a mode is Sustained, complete notes with length are constructed as note
531 * on/off events are received. Otherwise (Percussive), only note on events are
532 * stored; note off events are discarded entirely and all contained notes will
535 template<typename Time>
537 Sequence<Time>::start_write()
539 DUMP(format("%1% : start_write (percussive = %2%)\n") % this % _percussive);
542 for (int i = 0; i < 16; ++i) {
543 _write_notes[i].clear();
545 _dirty_controls.clear();
549 /** Finish a write of events to the model.
551 * If \a delete_stuck is true and the current mode is Sustained, note on events
552 * that were never resolved with a corresonding note off will be deleted.
553 * Otherwise they will remain as notes with length 0.
555 template<typename Time>
557 Sequence<Time>::end_write(bool delete_stuck)
562 DUMP(format("%1% : end_write (%2% notes)\n") % this % _notes.size());
564 if (!_percussive && delete_stuck) {
565 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
566 typename Notes::iterator next = n;
568 if ((*n)->length() == 0) {
569 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
576 for (int i = 0; i < 16; ++i) {
577 if (!_write_notes[i].empty()) {
578 cerr << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
579 << _write_notes[i].size() << " stuck notes" << endl;
581 _write_notes[i].clear();
584 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
592 /** Append \a ev to model. NOT realtime safe.
594 * Timestamps of events in \a buf are expected to be relative to
595 * the start of this model (t=0) and MUST be monotonically increasing
596 * and MUST be >= the latest event currently in the model.
598 template<typename Time>
600 Sequence<Time>::append(const Event<Time>& event)
605 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
607 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
610 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
611 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
616 if (ev.is_note_on()) {
617 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
618 } else if (ev.is_note_off()) {
619 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
620 } else if (ev.is_sysex()) {
621 append_sysex_unlocked(ev);
622 } else if (!_type_map.type_is_midi(ev.event_type())) {
623 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
624 for (size_t i=0; i < ev.size(); ++i) {
625 printf("%X ", ev.buffer()[i]);
628 } else if (ev.is_cc()) {
629 append_control_unlocked(
630 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
631 ev.time(), ev.cc_value());
632 } else if (ev.is_pgm_change()) {
633 append_control_unlocked(
634 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
635 ev.time(), ev.pgm_number());
636 } else if (ev.is_pitch_bender()) {
637 append_control_unlocked(
638 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
639 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
640 | (0x7F & ev.pitch_bender_lsb()) ));
641 } else if (ev.is_channel_pressure()) {
642 append_control_unlocked(
643 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
644 ev.time(), ev.channel_pressure());
646 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
652 template<typename Time>
654 Sequence<Time>::append_note_on_unlocked(uint8_t chan, Time time, uint8_t note_num, uint8_t velocity)
656 DUMP(format("%1% c=%2% note %3% on @ %4% v=%5%\n")
657 % this % (int)chan % (int)note_num % time % (int)velocity);
658 assert(note_num <= 127);
664 append_note_off_unlocked(chan, time, note_num);
668 if (note_num < _lowest_note)
669 _lowest_note = note_num;
670 if (note_num > _highest_note)
671 _highest_note = note_num;
673 boost::shared_ptr< Note<Time> > new_note(new Note<Time>(chan, time, 0, note_num, velocity));
674 _notes.insert(new_note);
676 DUMP(format("Sustained: Appending active note on %1% channel %2%\n")
677 % (unsigned)(uint8_t)note_num % chan);
678 _write_notes[chan].insert(new_note);
680 DUMP("Percussive: NOT appending active note on\n");
684 template<typename Time>
686 Sequence<Time>::append_note_off_unlocked(uint8_t chan, Time time, uint8_t note_num)
688 DUMP(format("%1% c=%2% note %3% off @ %4%\n")
689 % this % (int)chan % (int)note_num % time);
690 assert(note_num <= 127);
696 DUMP("Sequence Ignoring note off (percussive mode)\n");
700 // TODO: support note off velocity
702 bool resolved = false;
703 for (typename WriteNotes::iterator n = _write_notes[chan].begin();
704 n != _write_notes[chan].end(); ++n) {
705 boost::shared_ptr< Note<Time> > note = *n;
706 if (note->note() == note_num) {
707 assert(time >= note->time());
708 note->set_length(time - note->time());
709 _write_notes[chan].erase(n);
710 DUMP(format("resolved note, length: %1%\n") % note.length());
717 cerr << this << " spurious note off chan " << (int)chan
718 << ", note " << (int)note_num << " @ " << time << endl;
722 template<typename Time>
724 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value)
726 DUMP(format("%1% %2% @ %3%\t=\t%4% # controls: %5%\n")
727 % this % _type_map.to_symbol(param) % time % value % _controls.size());
728 boost::shared_ptr<Control> c = control(param, true);
729 c->list()->rt_add(time, value);
732 template<typename Time>
734 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev)
736 #ifdef DEBUG_SEQUENCE
737 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
738 for (size_t i=0; i < ev.size(); ++i) {
739 cerr << int(ev.buffer()[i]) << " ";
740 } cerr << "]" << endl;
743 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
744 _sysexes.push_back(event);
747 template<typename Time>
749 Sequence<Time>::add_note_unlocked(const boost::shared_ptr< Note<Time> > note)
751 DUMP(format("%1% add note %2% @ %3%\n") % this % (int)note->note() % note->time());
753 typename Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
754 note_time_comparator);
755 _notes.insert(i, note);
758 template<typename Time>
760 Sequence<Time>::remove_note_unlocked(const boost::shared_ptr< const Note<Time> > note)
763 DUMP(format("%1% remove note %2% @ %3%\n") % this % (int)note->note() % note->time());
764 for (typename Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
765 if (*(*n) == *note) {
772 template<typename Time>
774 Sequence<Time>::set_notes (const Sequence<Time>::Notes& n)
779 template class Sequence<Evoral::MusicalTime>;
781 } // namespace Evoral