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/Sequence.hpp"
27 #include "evoral/ControlList.hpp"
28 #include "evoral/Control.hpp"
29 #include "evoral/ControlSet.hpp"
30 #include "evoral/EventSink.hpp"
31 #include "evoral/MIDIParameters.hpp"
32 #include "evoral/TypeMap.hpp"
39 void Sequence<T>::write_lock() {
45 void Sequence<T>::write_unlock() {
46 _lock.writer_unlock();
47 _control_lock.unlock();
51 void Sequence<T>::read_lock() const {
56 void Sequence<T>::read_unlock() const {
57 _lock.reader_unlock();
60 struct null_ostream : public std::ostream {
61 null_ostream(): std::ios(0), std::ostream(0) {}
63 static null_ostream nullout;
65 static ostream& debugout = cout;
66 //static ostream& debugout = nullout;
67 static ostream& errorout = cerr;
69 // Read iterator (const_iterator)
72 Sequence<T>::const_iterator::const_iterator(const Sequence<T>& seq, T t)
74 , _is_end( (t == DBL_MAX) || seq.empty() )
77 debugout << "Created Iterator @ " << t << " (is end: " << _is_end << ")" << endl;
85 // find first note which begins after t
86 _note_iter = seq.notes().end();
87 for (typename Sequence<T>::Notes::const_iterator i = seq.notes().begin();
88 i != seq.notes().end(); ++i) {
89 if ((*i)->time() >= t) {
94 assert(_note_iter == seq.notes().end() || (*_note_iter)->time() >= t);
96 // find first sysex which begins after t
97 _sysex_iter = seq.sysexes().end();
98 for (typename Sequence<T>::SysExes::const_iterator i = seq.sysexes().begin();
99 i != seq.sysexes().end(); ++i) {
100 if ((*i)->time() >= t) {
105 assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
107 ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
109 _control_iters.reserve(seq._controls.size());
111 // find the earliest control event available
112 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
113 debugout << "Iterator: control: " << seq._type_map.to_symbol(i->first) << endl;
115 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
117 debugout << "Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
118 << ") has no events past " << t << endl;
124 /*if (y < i->first.min() || y > i->first.max()) {
125 errorout << "ERROR: Controller " << i->first.symbol() << " value " << y
126 << " out of range [" << i->first.min() << "," << i->first.max()
127 << "], event ignored" << endl;
131 const ControlIterator new_iter(i->second->list(), x, y);
133 debugout << "Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
134 _control_iters.push_back(new_iter);
136 // if the x of the current control is less than earliest_control
137 // we have a new earliest_control
138 if (x < earliest_control.x) {
139 earliest_control = new_iter;
140 _control_iter = _control_iters.end();
142 // now _control_iter points to the last Element in _control_iters
146 #define MAKE_SURE_ADDING_SYSEXES_PRESERVES_OLD_SEMANTICS 1
147 #if MAKE_SURE_ADDING_SYSEXES_PRESERVES_OLD_SEMANTICS
148 MIDIMessageType original_type = NIL;
149 assert (!earliest_control.list || earliest_control.x >= t);
151 if (_note_iter != seq.notes().end()
152 && (*_note_iter)->on_event().time() >= t
153 && (!earliest_control.list
154 || (*_note_iter)->on_event().time() < earliest_control.x)) {
155 original_type = NOTE_ON;
157 original_type = CONTROL;
161 MIDIMessageType type = NIL;
164 // if the note comes before anything else set the iterator to the note
165 if (_note_iter != seq.notes().end() && (*_note_iter)->on_event().time() >= t) {
167 earliest_t = (*_note_iter)->on_event().time();
170 if (earliest_control.list &&
171 earliest_control.x >= t &&
172 earliest_control.x <= earliest_t) {
174 earliest_t = earliest_control.x;
177 if (_sysex_iter != seq.sysexes().end() &&
178 (*_sysex_iter)->time() >= t &&
179 (*_sysex_iter)->time() <= earliest_t) {
181 earliest_t = (*_sysex_iter)->time();
184 #if MAKE_SURE_ADDING_SYSEXES_PRESERVES_OLD_SEMANTICS
185 assert (type == original_type || type == SYSEX);
188 if (type == NOTE_ON) {
189 debugout << "Reading note on event @ " << earliest_t << endl;
190 // initialize the event pointer with a new event
191 _event = boost::shared_ptr< Event<T> >(new Event<T>((*_note_iter)->on_event(), true));
192 _active_notes.push(*_note_iter);
194 _control_iter = _control_iters.end();
195 } else if (type == CONTROL) {
196 debugout << "Reading control event @ " << earliest_t << endl;
197 seq.control_to_midi_event(_event, earliest_control);
198 } else if (type == SYSEX) {
199 debugout << "Reading system exclusive event @ " << earliest_t << endl;
200 // initialize the event pointer with a new event
201 _event = boost::shared_ptr< Event<T> >(new Event<T>(*(*_sysex_iter), true));
203 _control_iter = _control_iters.end();
206 if ( (! _event.get()) || _event->size() == 0) {
207 debugout << "New iterator @ " << t << " is at end." << endl;
210 // eliminate possible race condition here (ugly)
211 static Glib::Mutex mutex;
212 Glib::Mutex::Lock lock(mutex);
218 debugout << "New Iterator = " << _event->event_type();
219 debugout << " : " << hex << (int)((MIDIEvent<T>*)_event.get())->type();
220 debugout << " @ " << _event->time() << endl;
223 //assert(_is_end || (_event->buffer() && _event->buffer()[0] != '\0'));
227 Sequence<T>::const_iterator::~const_iterator()
235 const typename Sequence<T>::const_iterator&
236 Sequence<T>::const_iterator::operator++()
239 throw std::logic_error("Attempt to iterate past end of Sequence");
242 debugout << "Iterator ++" << endl;
243 assert(_event->buffer() && _event->size() > 0);
245 const MIDIEvent<T>& ev = *((MIDIEvent<T>*)_event.get());
247 //debugout << "const_iterator::operator++: " << _event->to_string() << endl;
249 if (! (ev.is_note() || ev.is_cc() || ev.is_pgm_change()
250 || ev.is_pitch_bender() || ev.is_channel_pressure() || ev.is_sysex()) ) {
251 errorout << "Unknown event type: " << hex << int(ev.buffer()[0])
252 << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
258 ev.is_pgm_change() ||
259 ev.is_pitch_bender() ||
260 ev.is_channel_pressure() ||
264 // Increment past current control event
265 if (!ev.is_note() && _control_iter != _control_iters.end() && _control_iter->list.get()) {
266 double x = 0.0, y = 0.0;
267 const bool ret = _control_iter->list->rt_safe_earliest_event_unlocked(
268 _control_iter->x, DBL_MAX, x, y, false);
270 assert(!ret || x > _control_iter->x);
273 _control_iter->x = x;
274 _control_iter->y = y;
276 _control_iter->list.reset();
277 _control_iter->x = DBL_MAX;
278 _control_iter->y = DBL_MAX;
282 _control_iter = _control_iters.begin();
284 // find the _control_iter with the earliest event time
285 for (ControlIterators::iterator i = _control_iters.begin(); i != _control_iters.end(); ++i) {
286 if (i->x < _control_iter->x) {
291 MIDIMessageType type = NIL;
294 // Next earliest note on
295 if (_note_iter != _seq->notes().end()) {
297 earliest_t = (*_note_iter)->time();
300 // Use the next earliest note off iff it's earlier than the note on
301 if (!_seq->percussive() && (! _active_notes.empty())) {
302 if (type == NIL || _active_notes.top()->end_time() <= earliest_t) {
304 earliest_t = _active_notes.top()->end_time();
308 // Use the next earliest controller iff it's earlier than the note event
309 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
310 if (type == NIL || _control_iter->x <= earliest_t) {
312 earliest_t = _control_iter->x;
316 // Use the next earliest SysEx iff it's earlier than the controller
317 if (_sysex_iter != _seq->sysexes().end()) {
318 if (type == NIL || (*_sysex_iter)->time() <= earliest_t) {
320 earliest_t = (*_sysex_iter)->time();
324 if (type == NOTE_ON) {
325 debugout << "Iterator = note on" << endl;
326 *_event = (*_note_iter)->on_event();
327 _active_notes.push(*_note_iter);
329 } else if (type == NOTE_OFF) {
330 debugout << "Iterator = note off" << endl;
331 *_event = _active_notes.top()->off_event();
333 } else if (type == CONTROL) {
334 debugout << "Iterator = control" << endl;
335 _seq->control_to_midi_event(_event, *_control_iter);
336 } else if (type == SYSEX) {
337 debugout << "Iterator = SysEx" << endl;
338 *_event =*(*_sysex_iter);
341 debugout << "Iterator = End" << endl;
345 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
352 Sequence<T>::const_iterator::operator==(const const_iterator& other) const
354 if (_is_end || other._is_end) {
355 return (_is_end == other._is_end);
357 return (_event == other._event);
362 typename Sequence<T>::const_iterator&
363 Sequence<T>::const_iterator::operator=(const const_iterator& other)
365 if (_locked && _seq != other._seq) {
370 _active_notes = other._active_notes;
371 _is_end = other._is_end;
372 _locked = other._locked;
373 _note_iter = other._note_iter;
374 _sysex_iter = other._sysex_iter;
375 _control_iters = other._control_iters;
376 size_t index = other._control_iter - other._control_iters.begin();
377 _control_iter = _control_iters.begin() + index;
379 if (!_is_end && other._event) {
381 *_event = *other._event.get();
383 _event = boost::shared_ptr< Event<T> >(new Event<T>(*other._event, true));
397 Sequence<T>::Sequence(const TypeMap& type_map, size_t size)
398 : _read_iter(*this, DBL_MAX)
400 , _type_map(type_map)
403 , _end_iter(*this, DBL_MAX)
404 , _next_read(UINT32_MAX)
409 debugout << "Sequence (size " << size << ") constructed: " << this << endl;
410 assert(_end_iter._is_end);
411 assert( ! _end_iter._locked);
414 /** Read events in frame range \a start .. \a start+cnt into \a dst,
415 * adding \a offset to each event's timestamp.
416 * \return number of events written to \a dst
420 Sequence<T>::read(EventSink<T>& dst, timestamp_t start, timedur_t nframes, timestamp_t offset) const
422 debugout << this << " read @ " << start << " * " << nframes << " + " << offset << endl;
423 debugout << this << " # notes: " << n_notes() << endl;
424 debugout << this << " # controls: " << _controls.size() << endl;
426 size_t read_events = 0;
428 if (start != _next_read) {
429 debugout << "Repositioning iterator from " << _next_read << " to " << start << endl;
430 _read_iter = const_iterator(*this, (double)start);
432 debugout << "Using cached iterator at " << _next_read << endl;
435 _next_read = (FrameTime) floor (start + nframes);
437 while (_read_iter != end() && _read_iter->time() < start + nframes) {
438 assert(_read_iter->size() > 0);
439 assert(_read_iter->buffer());
440 dst.write(_read_iter->time() + offset,
441 _read_iter->event_type(),
443 _read_iter->buffer());
445 debugout << this << " read event type " << _read_iter->event_type()
446 << " @ " << _read_iter->time() << " : ";
447 for (size_t i = 0; i < _read_iter->size(); ++i)
448 debugout << hex << (int)_read_iter->buffer()[i];
458 /** Write the controller event pointed to by \a iter to \a ev.
459 * The buffer of \a ev will be allocated or resized as necessary.
460 * The event_type of \a ev should be set to the expected output type.
461 * \return true on success
465 Sequence<T>::control_to_midi_event(boost::shared_ptr< Event<T> >& ev, const ControlIterator& iter) const
467 assert(iter.list.get());
468 const uint32_t event_type = iter.list->parameter().type();
470 // initialize the event pointer with a new event, if necessary
472 ev = boost::shared_ptr< Event<T> >(new Event<T>(event_type, 0, 3, NULL, true));
475 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
476 ev->set_event_type(_type_map.midi_event_type(midi_type));
478 case MIDI_CMD_CONTROL:
479 assert(iter.list.get());
480 assert(iter.list->parameter().channel() < 16);
481 assert(iter.list->parameter().id() <= INT8_MAX);
482 assert(iter.y <= INT8_MAX);
486 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
487 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
488 ev->buffer()[2] = (uint8_t)iter.y;
491 case MIDI_CMD_PGM_CHANGE:
492 assert(iter.list.get());
493 assert(iter.list->parameter().channel() < 16);
494 assert(iter.y <= INT8_MAX);
498 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
499 ev->buffer()[1] = (uint8_t)iter.y;
502 case MIDI_CMD_BENDER:
503 assert(iter.list.get());
504 assert(iter.list->parameter().channel() < 16);
505 assert(iter.y < (1<<14));
509 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
510 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
511 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
514 case MIDI_CMD_CHANNEL_PRESSURE:
515 assert(iter.list.get());
516 assert(iter.list->parameter().channel() < 16);
517 assert(iter.y <= INT8_MAX);
521 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
522 ev->buffer()[1] = (uint8_t)iter.y;
532 /** Clear all events from the model.
540 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
541 li->second->list()->clear();
544 _lock.writer_unlock();
547 /** Begin a write of events to the model.
549 * If \a mode is Sustained, complete notes with length are constructed as note
550 * on/off events are received. Otherwise (Percussive), only note on events are
551 * stored; note off events are discarded entirely and all contained notes will
556 Sequence<T>::start_write()
558 debugout << this << " START WRITE, PERCUSSIVE = " << _percussive << endl;
561 for (int i = 0; i < 16; ++i)
562 _write_notes[i].clear();
564 _dirty_controls.clear();
568 /** Finish a write of events to the model.
570 * If \a delete_stuck is true and the current mode is Sustained, note on events
571 * that were never resolved with a corresonding note off will be deleted.
572 * Otherwise they will remain as notes with length 0.
576 Sequence<T>::end_write(bool delete_stuck)
581 debugout << this << " END WRITE: " << _notes.size() << " NOTES\n";
583 if (!_percussive && delete_stuck) {
584 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
585 if ((*n)->length() == 0) {
586 errorout << "WARNING: Stuck note lost: " << (*n)->note() << endl;
588 // we have to break here because erase invalidates the iterator
596 for (int i = 0; i < 16; ++i) {
597 if (!_write_notes[i].empty()) {
598 errorout << "WARNING: Sequence<T>::end_write: Channel " << i << " has "
599 << _write_notes[i].size() << " stuck notes" << endl;
601 _write_notes[i].clear();
604 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
612 /** Append \a ev to model. NOT realtime safe.
614 * Timestamps of events in \a buf are expected to be relative to
615 * the start of this model (t=0) and MUST be monotonically increasing
616 * and MUST be >= the latest event currently in the model.
620 Sequence<T>::append(const Event<T>& event)
625 const MIDIEvent<T>& ev = (const MIDIEvent<T>&)event;
627 assert(_notes.empty() || ev.time() >= _notes.back()->time());
630 if (ev.is_note_on()) {
631 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(),
633 } else if (ev.is_note_off()) {
634 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
635 } else if (ev.is_sysex()) {
636 append_sysex_unlocked(ev);
637 } else if (!_type_map.type_is_midi(ev.event_type())) {
638 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
639 for (size_t i=0; i < ev.size(); ++i) {
640 printf("%X ", ev.buffer()[i]);
643 } else if (ev.is_cc()) {
644 append_control_unlocked(
645 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
646 ev.time(), ev.cc_value());
647 } else if (ev.is_pgm_change()) {
648 append_control_unlocked(
649 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
650 ev.time(), ev.pgm_number());
651 } else if (ev.is_pitch_bender()) {
652 append_control_unlocked(
653 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
654 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
655 | (0x7F & ev.pitch_bender_lsb()) ));
656 } else if (ev.is_channel_pressure()) {
657 append_control_unlocked(
658 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
659 ev.time(), ev.channel_pressure());
661 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
669 Sequence<T>::append_note_on_unlocked(uint8_t chan, T time, uint8_t note_num, uint8_t velocity)
671 debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
672 assert(note_num <= 127);
677 if (note_num < _lowest_note)
678 _lowest_note = note_num;
679 if (note_num > _highest_note)
680 _highest_note = note_num;
682 boost::shared_ptr< Note<T> > new_note(new Note<T>(chan, time, 0, note_num, velocity));
683 _notes.push_back(new_note);
685 debugout << "Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
686 _write_notes[chan].push_back(_notes.size() - 1);
688 debugout << "Percussive: NOT appending active note on" << endl;
694 Sequence<T>::append_note_off_unlocked(uint8_t chan, T time, uint8_t note_num)
696 debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
697 assert(note_num <= 127);
703 debugout << "Sequence Ignoring note off (percussive mode)" << endl;
707 /* FIXME: make _write_notes fixed size (127 noted) for speed */
709 /* FIXME: note off velocity for that one guy out there who actually has
710 * keys that send it */
712 bool resolved = false;
714 for (WriteNotes::iterator n = _write_notes[chan].begin(); n
715 != _write_notes[chan].end(); ++n) {
716 Note<T>& note = *_notes[*n].get();
717 if (note.note() == note_num) {
718 assert(time >= note.time());
719 note.set_length(time - note.time());
720 _write_notes[chan].erase(n);
721 debugout << "resolved note, length: " << note.length() << endl;
728 errorout << this << " spurious note off chan " << (int)chan
729 << ", note " << (int)note_num << " @ " << time << endl;
735 Sequence<T>::append_control_unlocked(const Parameter& param, T time, double value)
737 debugout << this << " " << _type_map.to_symbol(param) << " @ " << time << " \t= \t" << value
738 << " # controls: " << _controls.size() << endl;
739 boost::shared_ptr<Control> c = control(param, true);
740 c->list()->rt_add(time, value);
745 Sequence<T>::append_sysex_unlocked(const MIDIEvent<T>& ev)
747 debugout << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
748 for (size_t i=0; i < ev.size(); ++i) {
749 debugout << int(ev.buffer()[i]) << " ";
751 debugout << "]" << endl;
753 boost::shared_ptr<MIDIEvent<T> > event(new MIDIEvent<T>(ev, true));
754 _sysexes.push_back(event);
759 Sequence<T>::add_note_unlocked(const boost::shared_ptr< Note<T> > note)
761 debugout << this << " add note " << (int)note->note() << " @ " << note->time() << endl;
763 typename Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
764 note_time_comparator);
765 _notes.insert(i, note);
770 Sequence<T>::remove_note_unlocked(const boost::shared_ptr< const Note<T> > note)
773 debugout << this << " remove note " << (int)note->note() << " @ " << note->time() << endl;
774 for (typename Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
776 const Note<T>& _note = *note;
777 // TODO: There is still the issue, that after restarting ardour
778 // persisted undo does not work, because of rounding errors in the
779 // event times after saving/restoring to/from MIDI files
780 /*cerr << "======================================= " << endl;
781 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.length()) << "-- #" << int(_n.velocity()) << endl;
782 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.length()) << "-- #" << int(_note.velocity()) << endl;
783 cerr << "Equal: " << bool(_n == _note) << endl;
784 cerr << endl << endl;*/
787 // we have to break here, because erase invalidates all iterators, ie. n itself
793 /** Slow! for debugging only. */
797 Sequence<T>::is_sorted() const {
799 for (typename Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
800 if ((*n)->time() < t)
809 template class Sequence<double>;
811 } // namespace Evoral