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 /** Write the controller event pointed to by \a iter to \a ev.
402 * The buffer of \a ev will be allocated or resized as necessary.
403 * The event_type of \a ev should be set to the expected output type.
404 * \return true on success
406 template<typename Time>
408 Sequence<Time>::control_to_midi_event(
409 boost::shared_ptr< Event<Time> >& ev,
410 const ControlIterator& iter) const
412 assert(iter.list.get());
413 const uint32_t event_type = iter.list->parameter().type();
415 // initialize the event pointer with a new event, if necessary
417 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
420 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
421 ev->set_event_type(_type_map.midi_event_type(midi_type));
423 case MIDI_CMD_CONTROL:
424 assert(iter.list.get());
425 assert(iter.list->parameter().channel() < 16);
426 assert(iter.list->parameter().id() <= INT8_MAX);
427 assert(iter.y <= INT8_MAX);
431 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
432 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
433 ev->buffer()[2] = (uint8_t)iter.y;
436 case MIDI_CMD_PGM_CHANGE:
437 assert(iter.list.get());
438 assert(iter.list->parameter().channel() < 16);
439 assert(iter.y <= INT8_MAX);
443 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
444 ev->buffer()[1] = (uint8_t)iter.y;
447 case MIDI_CMD_BENDER:
448 assert(iter.list.get());
449 assert(iter.list->parameter().channel() < 16);
450 assert(iter.y < (1<<14));
454 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
455 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
456 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
459 case MIDI_CMD_CHANNEL_PRESSURE:
460 assert(iter.list.get());
461 assert(iter.list->parameter().channel() < 16);
462 assert(iter.y <= INT8_MAX);
466 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
467 ev->buffer()[1] = (uint8_t)iter.y;
477 /** Clear all events from the model.
479 template<typename Time>
481 Sequence<Time>::clear()
483 WriteLock lock(write_lock());
485 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
486 li->second->list()->clear();
489 /** Begin a write of events to the model.
491 * If \a mode is Sustained, complete notes with length are constructed as note
492 * on/off events are received. Otherwise (Percussive), only note on events are
493 * stored; note off events are discarded entirely and all contained notes will
496 template<typename Time>
498 Sequence<Time>::start_write()
500 DUMP(format("%1% : start_write (percussive = %2%)\n") % this % _percussive);
501 WriteLock lock(write_lock());
503 for (int i = 0; i < 16; ++i) {
504 _write_notes[i].clear();
506 _dirty_controls.clear();
509 /** Finish a write of events to the model.
511 * If \a delete_stuck is true and the current mode is Sustained, note on events
512 * that were never resolved with a corresonding note off will be deleted.
513 * Otherwise they will remain as notes with length 0.
515 template<typename Time>
517 Sequence<Time>::end_write(bool delete_stuck)
519 WriteLock lock(write_lock());
525 DUMP(format("%1% : end_write (%2% notes)\n") % this % _notes.size());
527 if (!_percussive && delete_stuck) {
528 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
529 typename Notes::iterator next = n;
531 if ((*n)->length() == 0) {
532 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
539 for (int i = 0; i < 16; ++i) {
540 if (!_write_notes[i].empty()) {
541 cerr << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
542 << _write_notes[i].size() << " stuck notes" << endl;
544 _write_notes[i].clear();
547 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
554 /** Append \a ev to model. NOT realtime safe.
556 * Timestamps of events in \a buf are expected to be relative to
557 * the start of this model (t=0) and MUST be monotonically increasing
558 * and MUST be >= the latest event currently in the model.
560 template<typename Time>
562 Sequence<Time>::append(const Event<Time>& event)
564 WriteLock lock(write_lock());
567 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
569 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
572 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
573 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
577 if (ev.is_note_on()) {
578 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
579 } else if (ev.is_note_off()) {
580 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
581 } else if (ev.is_sysex()) {
582 append_sysex_unlocked(ev);
583 } else if (!_type_map.type_is_midi(ev.event_type())) {
584 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
585 for (size_t i=0; i < ev.size(); ++i) {
586 printf("%X ", ev.buffer()[i]);
589 } else if (ev.is_cc()) {
590 append_control_unlocked(
591 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
592 ev.time(), ev.cc_value());
593 } else if (ev.is_pgm_change()) {
594 append_control_unlocked(
595 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
596 ev.time(), ev.pgm_number());
597 } else if (ev.is_pitch_bender()) {
598 append_control_unlocked(
599 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
600 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
601 | (0x7F & ev.pitch_bender_lsb()) ));
602 } else if (ev.is_channel_pressure()) {
603 append_control_unlocked(
604 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
605 ev.time(), ev.channel_pressure());
607 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
611 template<typename Time>
613 Sequence<Time>::append_note_on_unlocked(uint8_t chan, Time time, uint8_t note_num, uint8_t velocity)
615 DUMP(format("%1% c=%2% note %3% on @ %4% v=%5%\n")
616 % this % (int)chan % (int)note_num % time % (int)velocity);
617 assert(note_num <= 127);
623 append_note_off_unlocked(chan, time, note_num);
627 if (note_num < _lowest_note)
628 _lowest_note = note_num;
629 if (note_num > _highest_note)
630 _highest_note = note_num;
632 boost::shared_ptr< Note<Time> > new_note(new Note<Time>(chan, time, 0, note_num, velocity));
633 _notes.insert(new_note);
635 DUMP(format("Sustained: Appending active note on %1% channel %2%\n")
636 % (unsigned)(uint8_t)note_num % chan);
637 _write_notes[chan].insert(new_note);
639 DUMP("Percussive: NOT appending active note on\n");
643 template<typename Time>
645 Sequence<Time>::append_note_off_unlocked(uint8_t chan, Time time, uint8_t note_num)
647 DUMP(format("%1% c=%2% note %3% off @ %4%\n")
648 % this % (int)chan % (int)note_num % time);
649 assert(note_num <= 127);
655 DUMP("Sequence Ignoring note off (percussive mode)\n");
659 // TODO: support note off velocity
661 bool resolved = false;
662 for (typename WriteNotes::iterator n = _write_notes[chan].begin();
663 n != _write_notes[chan].end(); ++n) {
664 boost::shared_ptr< Note<Time> > note = *n;
665 if (note->note() == note_num) {
666 assert(time >= note->time());
667 note->set_length(time - note->time());
668 _write_notes[chan].erase(n);
669 DUMP(format("resolved note, length: %1%\n") % note->length());
676 cerr << this << " spurious note off chan " << (int)chan
677 << ", note " << (int)note_num << " @ " << time << endl;
681 template<typename Time>
683 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value)
685 DUMP(format("%1% %2% @ %3%\t=\t%4% # controls: %5%\n")
686 % this % _type_map.to_symbol(param) % time % value % _controls.size());
687 boost::shared_ptr<Control> c = control(param, true);
688 c->list()->rt_add(time, value);
691 template<typename Time>
693 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev)
695 #ifdef DEBUG_SEQUENCE
696 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
697 for (size_t i=0; i < ev.size(); ++i) {
698 cerr << int(ev.buffer()[i]) << " ";
699 } cerr << "]" << endl;
702 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
703 _sysexes.push_back(event);
706 template<typename Time>
708 Sequence<Time>::add_note_unlocked(const boost::shared_ptr< Note<Time> > note)
710 DUMP(format("%1% add note %2% @ %3%\n") % this % (int)note->note() % note->time());
715 template<typename Time>
717 Sequence<Time>::remove_note_unlocked(const boost::shared_ptr< const Note<Time> > note)
720 DUMP(format("%1% remove note %2% @ %3%\n") % this % (int)note->note() % note->time());
721 for (typename Sequence<Time>::Notes::iterator i = note_lower_bound(note->time());
722 i != _notes.end() && (*i)->time() == note->time(); ++i) {
727 cerr << "Unable to find note to erase" << endl;
730 template<typename Time>
732 Sequence<Time>::set_notes (const Sequence<Time>::Notes& n)
737 /** Return the earliest note with time >= t */
738 template<typename Time>
739 typename Sequence<Time>::Notes::const_iterator
740 Sequence<Time>::note_lower_bound (Time t) const
742 boost::shared_ptr< Note<Time> > search_note(new Note<Time>(0, t, 0, 0, 0));
743 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
744 assert(i == _notes.end() || (*i)->time() >= t);
748 template class Sequence<Evoral::MusicalTime>;
750 } // namespace Evoral