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);
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;
132 _control_iter = _control_iters.end();
135 // Now find the earliest event overall and point to it
138 if (_note_iter != seq.notes().end()) {
140 earliest_t = (*_note_iter)->time();
143 if (_sysex_iter != seq.sysexes().end() && (*_sysex_iter)->time() < earliest_t) {
145 earliest_t = (*_sysex_iter)->time();
148 if (_control_iter != _control_iters.end()
149 && earliest_control.list && earliest_control.x >= t
150 && earliest_control.x < earliest_t) {
152 earliest_t = earliest_control.x;
157 DUMP(format("Starting at note on event @ %1%\n") % earliest_t);
158 _event = boost::shared_ptr< Event<Time> >(
159 new Event<Time>((*_note_iter)->on_event(), true));
160 _active_notes.push(*_note_iter);
163 DUMP(format("Starting at sysex event @ %1%\n") % earliest_t);
164 _event = boost::shared_ptr< Event<Time> >(
165 new Event<Time>(*(*_sysex_iter), true));
168 DUMP(format("Starting at control event @ %1%\n") % earliest_t);
169 seq.control_to_midi_event(_event, earliest_control);
175 if (_type == NIL || !_event || _event->size() == 0) {
176 DUMP(format("Starting at end @ %1%\n") % t);
180 DUMP(printf("New iterator = 0x%x : 0x%x @ %f\n",
181 (int)_event->event_type(),
182 (int)((MIDIEvent<Time>*)_event.get())->type(),
184 assert(midi_event_is_valid(_event->buffer(), _event->size()));
188 template<typename Time>
189 Sequence<Time>::const_iterator::~const_iterator()
193 template<typename Time>
195 Sequence<Time>::const_iterator::invalidate()
197 while (!_active_notes.empty()) {
203 _note_iter = _seq->notes().end();
204 _sysex_iter = _seq->sysexes().end();
206 _control_iter = _control_iters.end();
210 template<typename Time>
211 const typename Sequence<Time>::const_iterator&
212 Sequence<Time>::const_iterator::operator++()
215 throw std::logic_error("Attempt to iterate past end of Sequence");
218 DUMP("Sequence::const_iterator++\n");
219 assert(_event && _event->buffer() && _event->size() > 0);
221 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
225 || ev.is_pgm_change()
226 || ev.is_pitch_bender()
227 || ev.is_channel_pressure()
228 || ev.is_sysex()) ) {
229 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
230 << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
237 // Increment past current event
245 // Increment current controller iterator
246 ret = _control_iter->list->rt_safe_earliest_event_unlocked(
247 _control_iter->x, DBL_MAX, x, y, false);
248 assert(!ret || x > _control_iter->x);
250 _control_iter->x = x;
251 _control_iter->y = y;
253 _control_iter->list.reset();
254 _control_iter->x = DBL_MAX;
255 _control_iter->y = DBL_MAX;
258 // Find the controller with the next earliest event time
259 _control_iter = _control_iters.begin();
260 for (ControlIterators::iterator i = _control_iters.begin();
261 i != _control_iters.end(); ++i) {
262 if (i->x < _control_iter->x) {
274 // Now find the earliest event overall and point to it
276 Time earliest_t = std::numeric_limits<Time>::max();
278 // Next earliest note on
279 if (_note_iter != _seq->notes().end()) {
281 earliest_t = (*_note_iter)->time();
284 // Use the next note off iff it's earlier or the same time as the note on
285 if (!_seq->percussive() && (!_active_notes.empty())) {
286 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
288 earliest_t = _active_notes.top()->end_time();
292 // Use the next earliest controller iff it's earlier than the note event
293 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
294 if (_type == NIL || _control_iter->x < earliest_t) {
296 earliest_t = _control_iter->x;
300 // Use the next earliest SysEx iff it's earlier than the controller
301 if (_sysex_iter != _seq->sysexes().end()) {
302 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
304 earliest_t = (*_sysex_iter)->time();
308 // Set event to reflect new position
311 DUMP("iterator = note on\n");
312 *_event = (*_note_iter)->on_event();
313 _active_notes.push(*_note_iter);
316 DUMP("iterator = note off\n");
317 assert(!_active_notes.empty());
318 *_event = _active_notes.top()->off_event();
322 DUMP("iterator = control\n");
323 _seq->control_to_midi_event(_event, *_control_iter);
326 DUMP("iterator = sysex\n");
327 *_event = *(*_sysex_iter);
330 DUMP("iterator = end\n");
334 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
339 template<typename Time>
341 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
343 if (_seq != other._seq) {
345 } else if (_is_end || other._is_end) {
346 return (_is_end == other._is_end);
347 } else if (_type != other._type) {
350 return (_event == other._event);
354 template<typename Time>
355 typename Sequence<Time>::const_iterator&
356 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
359 _event = other._event;
360 _active_notes = other._active_notes;
362 _is_end = other._is_end;
363 _note_iter = other._note_iter;
364 _sysex_iter = other._sysex_iter;
365 _control_iters = other._control_iters;
368 _lock = _seq->read_lock();
372 if (other._control_iter == other._control_iters.end()) {
373 _control_iter = _control_iters.end();
375 const size_t index = other._control_iter - other._control_iters.begin();
376 _control_iter = _control_iters.begin() + index;
384 template<typename Time>
385 Sequence<Time>::Sequence(const TypeMap& type_map)
387 , _type_map(type_map)
389 , _end_iter(*this, DBL_MAX)
394 DUMP(format("Sequence (size %1%) constructed: %2%\n") % size % this);
395 assert(_end_iter._is_end);
396 assert( ! _end_iter._lock);
399 /** Write the controller event pointed to by \a iter to \a ev.
400 * The buffer of \a ev will be allocated or resized as necessary.
401 * The event_type of \a ev should be set to the expected output type.
402 * \return true on success
404 template<typename Time>
406 Sequence<Time>::control_to_midi_event(
407 boost::shared_ptr< Event<Time> >& ev,
408 const ControlIterator& iter) const
410 assert(iter.list.get());
411 const uint32_t event_type = iter.list->parameter().type();
413 // initialize the event pointer with a new event, if necessary
415 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
418 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
419 ev->set_event_type(_type_map.midi_event_type(midi_type));
421 case MIDI_CMD_CONTROL:
422 assert(iter.list.get());
423 assert(iter.list->parameter().channel() < 16);
424 assert(iter.list->parameter().id() <= INT8_MAX);
425 assert(iter.y <= INT8_MAX);
429 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
430 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
431 ev->buffer()[2] = (uint8_t)iter.y;
434 case MIDI_CMD_PGM_CHANGE:
435 assert(iter.list.get());
436 assert(iter.list->parameter().channel() < 16);
437 assert(iter.y <= INT8_MAX);
441 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
442 ev->buffer()[1] = (uint8_t)iter.y;
445 case MIDI_CMD_BENDER:
446 assert(iter.list.get());
447 assert(iter.list->parameter().channel() < 16);
448 assert(iter.y < (1<<14));
452 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
453 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
454 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
457 case MIDI_CMD_CHANNEL_PRESSURE:
458 assert(iter.list.get());
459 assert(iter.list->parameter().channel() < 16);
460 assert(iter.y <= INT8_MAX);
464 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
465 ev->buffer()[1] = (uint8_t)iter.y;
475 /** Clear all events from the model.
477 template<typename Time>
479 Sequence<Time>::clear()
481 WriteLock lock(write_lock());
483 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
484 li->second->list()->clear();
487 /** Begin a write of events to the model.
489 * If \a mode is Sustained, complete notes with length are constructed as note
490 * on/off events are received. Otherwise (Percussive), only note on events are
491 * stored; note off events are discarded entirely and all contained notes will
494 template<typename Time>
496 Sequence<Time>::start_write()
498 DUMP(format("%1% : start_write (percussive = %2%)\n") % this % _percussive);
499 WriteLock lock(write_lock());
501 for (int i = 0; i < 16; ++i) {
502 _write_notes[i].clear();
504 _dirty_controls.clear();
507 /** Finish a write of events to the model.
509 * If \a delete_stuck is true and the current mode is Sustained, note on events
510 * that were never resolved with a corresonding note off will be deleted.
511 * Otherwise they will remain as notes with length 0.
513 template<typename Time>
515 Sequence<Time>::end_write(bool delete_stuck)
517 WriteLock lock(write_lock());
523 DUMP(format("%1% : end_write (%2% notes)\n") % this % _notes.size());
525 if (!_percussive && delete_stuck) {
526 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
527 typename Notes::iterator next = n;
529 if ((*n)->length() == 0) {
530 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
537 for (int i = 0; i < 16; ++i) {
538 if (!_write_notes[i].empty()) {
539 cerr << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
540 << _write_notes[i].size() << " stuck notes" << endl;
542 _write_notes[i].clear();
545 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
552 /** Append \a ev to model. NOT realtime safe.
554 * Timestamps of events in \a buf are expected to be relative to
555 * the start of this model (t=0) and MUST be monotonically increasing
556 * and MUST be >= the latest event currently in the model.
558 template<typename Time>
560 Sequence<Time>::append(const Event<Time>& event)
562 WriteLock lock(write_lock());
565 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
567 assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
570 if (!midi_event_is_valid(ev.buffer(), ev.size())) {
571 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
575 if (ev.is_note_on()) {
576 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
577 } else if (ev.is_note_off()) {
578 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
579 } else if (ev.is_sysex()) {
580 append_sysex_unlocked(ev);
581 } else if (!_type_map.type_is_midi(ev.event_type())) {
582 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
583 for (size_t i=0; i < ev.size(); ++i) {
584 printf("%X ", ev.buffer()[i]);
587 } else if (ev.is_cc()) {
588 append_control_unlocked(
589 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
590 ev.time(), ev.cc_value());
591 } else if (ev.is_pgm_change()) {
592 append_control_unlocked(
593 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
594 ev.time(), ev.pgm_number());
595 } else if (ev.is_pitch_bender()) {
596 append_control_unlocked(
597 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
598 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
599 | (0x7F & ev.pitch_bender_lsb()) ));
600 } else if (ev.is_channel_pressure()) {
601 append_control_unlocked(
602 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
603 ev.time(), ev.channel_pressure());
605 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
609 template<typename Time>
611 Sequence<Time>::append_note_on_unlocked(uint8_t chan, Time time, uint8_t note_num, uint8_t velocity)
613 DUMP(format("%1% c=%2% note %3% on @ %4% v=%5%\n")
614 % this % (int)chan % (int)note_num % time % (int)velocity);
615 assert(note_num <= 127);
621 append_note_off_unlocked(chan, time, note_num);
625 if (note_num < _lowest_note)
626 _lowest_note = note_num;
627 if (note_num > _highest_note)
628 _highest_note = note_num;
630 boost::shared_ptr< Note<Time> > new_note(new Note<Time>(chan, time, 0, note_num, velocity));
631 _notes.insert(new_note);
633 DUMP(format("Sustained: Appending active note on %1% channel %2%\n")
634 % (unsigned)(uint8_t)note_num % chan);
635 _write_notes[chan].insert(new_note);
637 DUMP("Percussive: NOT appending active note on\n");
641 template<typename Time>
643 Sequence<Time>::append_note_off_unlocked(uint8_t chan, Time time, uint8_t note_num)
645 DUMP(format("%1% c=%2% note %3% off @ %4%\n")
646 % this % (int)chan % (int)note_num % time);
647 assert(note_num <= 127);
653 DUMP("Sequence Ignoring note off (percussive mode)\n");
657 // TODO: support note off velocity
659 bool resolved = false;
660 for (typename WriteNotes::iterator n = _write_notes[chan].begin();
661 n != _write_notes[chan].end(); ++n) {
662 boost::shared_ptr< Note<Time> > note = *n;
663 if (note->note() == note_num) {
664 assert(time >= note->time());
665 note->set_length(time - note->time());
666 _write_notes[chan].erase(n);
667 DUMP(format("resolved note, length: %1%\n") % note.length());
674 cerr << this << " spurious note off chan " << (int)chan
675 << ", note " << (int)note_num << " @ " << time << endl;
679 template<typename Time>
681 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value)
683 DUMP(format("%1% %2% @ %3%\t=\t%4% # controls: %5%\n")
684 % this % _type_map.to_symbol(param) % time % value % _controls.size());
685 boost::shared_ptr<Control> c = control(param, true);
686 c->list()->rt_add(time, value);
689 template<typename Time>
691 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev)
693 #ifdef DEBUG_SEQUENCE
694 cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
695 for (size_t i=0; i < ev.size(); ++i) {
696 cerr << int(ev.buffer()[i]) << " ";
697 } cerr << "]" << endl;
700 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
701 _sysexes.push_back(event);
704 template<typename Time>
706 Sequence<Time>::add_note_unlocked(const boost::shared_ptr< Note<Time> > note)
708 DUMP(format("%1% add note %2% @ %3%\n") % this % (int)note->note() % note->time());
710 typename Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
711 note_time_comparator);
712 _notes.insert(i, note);
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 Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
722 if (*(*n) == *note) {
729 template<typename Time>
731 Sequence<Time>::set_notes (const Sequence<Time>::Notes& n)
736 /** Return the earliest note with time >= t */
737 template<typename Time>
738 typename Sequence<Time>::Notes::const_iterator
739 Sequence<Time>::note_lower_bound (Time t) const
741 boost::shared_ptr< Note<Time> > search_note(new Note<Time>(0, t, 0, 0, 0));
742 typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
743 assert(i == _notes.end() || (*i)->time() >= t);
747 template class Sequence<Evoral::MusicalTime>;
749 } // namespace Evoral