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
26 #include "evoral/Control.hpp"
27 #include "evoral/ControlList.hpp"
28 #include "evoral/ControlSet.hpp"
29 #include "evoral/EventSink.hpp"
30 #include "evoral/MIDIParameters.hpp"
31 #include "evoral/Sequence.hpp"
32 #include "evoral/TypeMap.hpp"
33 #include "evoral/midi_util.h"
35 //#define DEBUG_SEQUENCE 1
37 #include <boost/format.hpp>
39 #define DUMP(x) cerr << (x);
48 template<typename Time>
49 void Sequence<Time>::write_lock() {
54 template<typename Time>
55 void Sequence<Time>::write_unlock() {
56 _lock.writer_unlock();
57 _control_lock.unlock();
60 template<typename Time>
61 void Sequence<Time>::read_lock() const {
65 template<typename Time>
66 void Sequence<Time>::read_unlock() const {
67 _lock.reader_unlock();
71 // Read iterator (const_iterator)
73 template<typename Time>
74 Sequence<Time>::const_iterator::const_iterator()
79 _event = boost::shared_ptr< Event<Time> >(new Event<Time>());
82 template<typename Time>
83 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq, Time t)
86 , _is_end((t == DBL_MAX) || seq.empty())
89 DUMP(format("Created Iterator @ %1% (is end: %2%)\n)") % t % _is_end);
97 // Find first note which begins after t
98 _note_iter = seq.notes().end();
99 for (typename Sequence<Time>::Notes::const_iterator i = seq.notes().begin();
100 i != seq.notes().end(); ++i) {
101 if ((*i)->time() >= t) {
106 assert(_note_iter == seq.notes().end() || (*_note_iter)->time() >= t);
108 // Find first sysex event after t
109 _sysex_iter = seq.sysexes().end();
110 for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
111 i != seq.sysexes().end(); ++i) {
112 if ((*i)->time() >= t) {
117 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
119 // Find first control event after t
120 ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
121 _control_iters.reserve(seq._controls.size());
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 _control_iter = _control_iters.end();
150 --_control_iter; // now points to the last element in _control_iters
154 // Now find the earliest event overall and point to it
157 if (_note_iter != seq.notes().end()) {
159 earliest_t = (*_note_iter)->time();
162 if (_sysex_iter != seq.sysexes().end() && (*_sysex_iter)->time() < earliest_t) {
164 earliest_t = (*_sysex_iter)->time();
167 if (earliest_control.list && earliest_control.x >= t && earliest_control.x < earliest_t) {
169 earliest_t = earliest_control.x;
174 DUMP(format("Starting at note on event @ %1%\n") % earliest_t);
175 _event = boost::shared_ptr< Event<Time> >(
176 new Event<Time>((*_note_iter)->on_event(), true));
177 _active_notes.push(*_note_iter);
180 DUMP(format("Starting at sysex event @ %1%\n") % earliest_t);
181 _event = boost::shared_ptr< Event<Time> >(
182 new Event<Time>(*(*_sysex_iter), true));
185 DUMP(format("Starting at control event @ %1%\n") % earliest_t);
186 seq.control_to_midi_event(_event, earliest_control);
192 if (!_event || _event->size() == 0) {
193 DUMP(format("Starting at end @ %1%\n") % t);
201 DUMP(format("New iterator = %1% : %2% @ %3%\n")
202 % (int)_event->event_type()
203 % (int)((MIDIEvent<Time>*)_event.get())->type()
207 assert(_event && _event->size() > 0 && _event->time() >= t);
208 assert(midi_event_is_valid(_event->buffer(), _event->size()));
211 template<typename Time>
212 Sequence<Time>::const_iterator::~const_iterator()
219 template<typename Time>
220 const typename Sequence<Time>::const_iterator&
221 Sequence<Time>::const_iterator::operator++()
224 throw std::logic_error("Attempt to iterate past end of Sequence");
227 DUMP("Sequence::const_iterator++\n");
228 assert(_event && _event->buffer() && _event->size() > 0);
230 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
234 || ev.is_pgm_change()
235 || ev.is_pitch_bender()
236 || ev.is_channel_pressure()
237 || ev.is_sysex()) ) {
238 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
239 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
246 // Increment past current event
254 // Increment current controller iterator
255 ret = _control_iter->list->rt_safe_earliest_event_unlocked(
256 _control_iter->x, DBL_MAX, x, y, false);
257 assert(!ret || x > _control_iter->x);
259 _control_iter->x = x;
260 _control_iter->y = y;
262 _control_iter->list.reset();
263 _control_iter->x = DBL_MAX;
264 _control_iter->y = DBL_MAX;
267 // Find the controller with the next earliest event time
268 _control_iter = _control_iters.begin();
269 for (ControlIterators::iterator i = _control_iters.begin();
270 i != _control_iters.end(); ++i) {
271 if (i->x < _control_iter->x) {
283 // Now find the earliest event overall and point to it
285 Time earliest_t = std::numeric_limits<Time>::max();
287 // Next earliest note on
288 if (_note_iter != _seq->notes().end()) {
290 earliest_t = (*_note_iter)->time();
293 // Use the next note off iff it's earlier or the same time as the note on
294 if (!_seq->percussive() && (!_active_notes.empty())) {
295 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
297 earliest_t = _active_notes.top()->end_time();
301 // Use the next earliest controller iff it's earlier than the note event
302 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
303 if (_type == NIL || _control_iter->x < earliest_t) {
305 earliest_t = _control_iter->x;
309 // Use the next earliest SysEx iff it's earlier than the controller
310 if (_sysex_iter != _seq->sysexes().end()) {
311 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
313 earliest_t = (*_sysex_iter)->time();
317 // Set event to reflect new position
320 DUMP("iterator = note on\n");
321 *_event = (*_note_iter)->on_event();
322 _active_notes.push(*_note_iter);
325 DUMP("iterator = note off\n");
326 assert(!_active_notes.empty());
327 *_event = _active_notes.top()->off_event();
331 DUMP("iterator = control\n");
332 _seq->control_to_midi_event(_event, *_control_iter);
335 DUMP("iterator = sysex\n");
336 *_event = *(*_sysex_iter);
339 DUMP("iterator = end\n");
343 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
348 template<typename Time>
350 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
352 if (_seq != other._seq) {
354 } else if (_is_end || other._is_end) {
355 return (_is_end == other._is_end);
356 } else if (_type != other._type) {
359 return (_event == other._event);
363 template<typename Time>
364 typename Sequence<Time>::const_iterator&
365 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
367 if (_seq != other._seq) {
372 other._seq->read_lock();
377 _event = other._event;
378 _active_notes = other._active_notes;
380 _is_end = other._is_end;
381 _locked = other._locked;
382 _note_iter = other._note_iter;
383 _sysex_iter = other._sysex_iter;
384 _control_iters = other._control_iters;
385 size_t index = other._control_iter - other._control_iters.begin();
386 _control_iter = _control_iters.begin() + index;
393 template<typename Time>
394 Sequence<Time>::Sequence(const TypeMap& type_map, size_t size)
395 : _read_iter(*this, DBL_MAX)
397 , _type_map(type_map)
400 , _end_iter(*this, DBL_MAX)
405 DUMP(format("Sequence (size %1%) constructed: %2%\n") % size % this);
406 assert(_end_iter._is_end);
407 assert( ! _end_iter._locked);
410 /** Write the controller event pointed to by \a iter to \a ev.
411 * The buffer of \a ev will be allocated or resized as necessary.
412 * The event_type of \a ev should be set to the expected output type.
413 * \return true on success
415 template<typename Time>
417 Sequence<Time>::control_to_midi_event(
418 boost::shared_ptr< Event<Time> >& ev,
419 const ControlIterator& iter) const
421 assert(iter.list.get());
422 const uint32_t event_type = iter.list->parameter().type();
424 // initialize the event pointer with a new event, if necessary
426 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
429 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
430 ev->set_event_type(_type_map.midi_event_type(midi_type));
432 case MIDI_CMD_CONTROL:
433 assert(iter.list.get());
434 assert(iter.list->parameter().channel() < 16);
435 assert(iter.list->parameter().id() <= INT8_MAX);
436 assert(iter.y <= INT8_MAX);
440 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
441 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
442 ev->buffer()[2] = (uint8_t)iter.y;
445 case MIDI_CMD_PGM_CHANGE:
446 assert(iter.list.get());
447 assert(iter.list->parameter().channel() < 16);
448 assert(iter.y <= INT8_MAX);
452 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
453 ev->buffer()[1] = (uint8_t)iter.y;
456 case MIDI_CMD_BENDER:
457 assert(iter.list.get());
458 assert(iter.list->parameter().channel() < 16);
459 assert(iter.y < (1<<14));
463 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
464 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
465 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
468 case MIDI_CMD_CHANNEL_PRESSURE:
469 assert(iter.list.get());
470 assert(iter.list->parameter().channel() < 16);
471 assert(iter.y <= INT8_MAX);
475 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
476 ev->buffer()[1] = (uint8_t)iter.y;
486 /** Clear all events from the model.
488 template<typename Time>
490 Sequence<Time>::clear()
494 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
495 li->second->list()->clear();
497 _lock.writer_unlock();
500 /** Begin a write of events to the model.
502 * If \a mode is Sustained, complete notes with length are constructed as note
503 * on/off events are received. Otherwise (Percussive), only note on events are
504 * stored; note off events are discarded entirely and all contained notes will
507 template<typename Time>
509 Sequence<Time>::start_write()
511 DUMP(format("%1% : start_write (percussive = %2%)\n") % this % _percussive);
514 for (int i = 0; i < 16; ++i) {
515 _write_notes[i].clear();
517 _dirty_controls.clear();
521 /** Finish a write of events to the model.
523 * If \a delete_stuck is true and the current mode is Sustained, note on events
524 * that were never resolved with a corresonding note off will be deleted.
525 * Otherwise they will remain as notes with length 0.
527 template<typename Time>
529 Sequence<Time>::end_write(bool delete_stuck)
534 DUMP(format("%1% : end_write (%2% notes)\n") % this % _notes.size());
536 if (!_percussive && delete_stuck) {
537 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
538 if ((*n)->length() == 0) {
539 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
541 // we have to break here because erase invalidates the iterator
549 for (int i = 0; i < 16; ++i) {
550 if (!_write_notes[i].empty()) {
551 cerr << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
552 << _write_notes[i].size() << " stuck notes" << endl;
554 _write_notes[i].clear();
557 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
565 /** Append \a ev to model. NOT realtime safe.
567 * Timestamps of events in \a buf are expected to be relative to
568 * the start of this model (t=0) and MUST be monotonically increasing
569 * and MUST be >= the latest event currently in the model.
571 template<typename Time>
573 Sequence<Time>::append(const Event<Time>& event)
578 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
580 assert(_notes.empty() || ev.time() >= _notes.back()->time());
583 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
584 cerr << "WARNING: Ignoring illegal MIDI event" << endl;
588 if (ev.is_note_on()) {
589 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
590 } else if (ev.is_note_off()) {
591 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
592 } else if (ev.is_sysex()) {
593 append_sysex_unlocked(ev);
594 } else if (!_type_map.type_is_midi(ev.event_type())) {
595 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
596 for (size_t i=0; i < ev.size(); ++i) {
597 printf("%X ", ev.buffer()[i]);
600 } else if (ev.is_cc()) {
601 append_control_unlocked(
602 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
603 ev.time(), ev.cc_value());
604 } else if (ev.is_pgm_change()) {
605 append_control_unlocked(
606 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
607 ev.time(), ev.pgm_number());
608 } else if (ev.is_pitch_bender()) {
609 append_control_unlocked(
610 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
611 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
612 | (0x7F & ev.pitch_bender_lsb()) ));
613 } else if (ev.is_channel_pressure()) {
614 append_control_unlocked(
615 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
616 ev.time(), ev.channel_pressure());
618 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
624 template<typename Time>
626 Sequence<Time>::append_note_on_unlocked(uint8_t chan, Time time, uint8_t note_num, uint8_t velocity)
628 DUMP(format("%1% c=%2% note %3% on @ %4% v=%5%\n")
629 % this % (int)chan % (int)note_num % time % (int)velocity);
630 assert(note_num <= 127);
636 append_note_off_unlocked(chan, time, note_num);
640 if (note_num < _lowest_note)
641 _lowest_note = note_num;
642 if (note_num > _highest_note)
643 _highest_note = note_num;
645 boost::shared_ptr< Note<Time> > new_note(new Note<Time>(chan, time, 0, note_num, velocity));
646 _notes.push_back(new_note);
648 DUMP(format("Sustained: Appending active note on %1% channel %2%\n")
649 % (unsigned)(uint8_t)note_num % chan);
650 _write_notes[chan].push_back(_notes.size() - 1);
652 DUMP("Percussive: NOT appending active note on\n");
656 template<typename Time>
658 Sequence<Time>::append_note_off_unlocked(uint8_t chan, Time time, uint8_t note_num)
660 DUMP(format("%1% c=%2% note %3% off @ %4%\n")
661 % this % (int)chan % (int)note_num % time);
662 assert(note_num <= 127);
668 DUMP("Sequence Ignoring note off (percussive mode)\n");
672 /* FIXME: make _write_notes fixed size (127 noted) for speed */
674 /* FIXME: note off velocity for that one guy out there who actually has
675 * keys that send it */
677 bool resolved = false;
679 for (WriteNotes::iterator n = _write_notes[chan].begin(); n
680 != _write_notes[chan].end(); ++n) {
681 Note<Time>& note = *_notes[*n].get();
682 if (note.note() == note_num) {
683 assert(time >= note.time());
684 note.set_length(time - note.time());
685 _write_notes[chan].erase(n);
686 DUMP(format("resolved note, length: %1%\n") % note.length());
693 cerr << this << " spurious note off chan " << (int)chan
694 << ", note " << (int)note_num << " @ " << time << endl;
698 template<typename Time>
700 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value)
702 DUMP(format("%1% %2% @ %3%\t=\t%4% # controls: %5%\n")
703 % this % _type_map.to_symbol(param) % time % value % _controls.size());
704 boost::shared_ptr<Control> c = control(param, true);
705 c->list()->rt_add(time, value);
708 template<typename Time>
710 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev)
712 #ifdef DEBUG_SEQUENCE
713 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
714 for (size_t i=0; i < ev.size(); ++i) {
715 cerr << int(ev.buffer()[i]) << " ";
716 } cerr << "]" << endl;
719 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
720 _sysexes.push_back(event);
723 template<typename Time>
725 Sequence<Time>::add_note_unlocked(const boost::shared_ptr< Note<Time> > note)
727 DUMP(format("%1% add note %2% @ %3%\n") % this % (int)note->note() % note->time());
729 typename Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
730 note_time_comparator);
731 _notes.insert(i, note);
734 template<typename Time>
736 Sequence<Time>::remove_note_unlocked(const boost::shared_ptr< const Note<Time> > note)
739 DUMP(format("%1% remove note %2% @ %3%\n") % this % (int)note->note() % note->time());
740 for (typename Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
741 if (*(*n) == *note) {
748 template class Sequence<double>;
750 } // namespace Evoral