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"
38 template<typename Time>
39 void Sequence<Time>::write_lock() {
44 template<typename Time>
45 void Sequence<Time>::write_unlock() {
46 _lock.writer_unlock();
47 _control_lock.unlock();
50 template<typename Time>
51 void Sequence<Time>::read_lock() const {
55 template<typename Time>
56 void Sequence<Time>::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)
71 template<typename Time>
72 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq, Time 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<Time>::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<Time>::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<Time> >(new Event<Time>((*_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<Time> >(new Event<Time>(*(*_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<Time>*)_event.get())->type();
220 debugout << " @ " << _event->time() << endl;
223 assert(_event && _event->size() > 0);
225 //assert(_is_end || (_event->buffer() && _event->buffer()[0] != '\0'));
228 template<typename Time>
229 Sequence<Time>::const_iterator::~const_iterator()
236 template<typename Time>
237 const typename Sequence<Time>::const_iterator&
238 Sequence<Time>::const_iterator::operator++()
241 throw std::logic_error("Attempt to iterate past end of Sequence");
244 debugout << "Iterator ++" << endl;
245 assert(_event && _event->buffer() && _event->size() > 0);
247 const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
249 //debugout << "const_iterator::operator++: " << _event->to_string() << endl;
251 if (! (ev.is_note() || ev.is_cc() || ev.is_pgm_change()
252 || ev.is_pitch_bender() || ev.is_channel_pressure() || ev.is_sysex()) ) {
253 errorout << "Unknown event type: " << hex << int(ev.buffer()[0])
254 << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
260 ev.is_pgm_change() ||
261 ev.is_pitch_bender() ||
262 ev.is_channel_pressure() ||
266 // Increment past current control event
267 if (!ev.is_note() && _control_iter != _control_iters.end() && _control_iter->list.get()) {
268 double x = 0.0, y = 0.0;
269 const bool ret = _control_iter->list->rt_safe_earliest_event_unlocked(
270 _control_iter->x, DBL_MAX, x, y, false);
272 assert(!ret || x > _control_iter->x);
275 _control_iter->x = x;
276 _control_iter->y = y;
278 _control_iter->list.reset();
279 _control_iter->x = DBL_MAX;
280 _control_iter->y = DBL_MAX;
284 _control_iter = _control_iters.begin();
286 // find the _control_iter with the earliest event time
287 for (ControlIterators::iterator i = _control_iters.begin(); i != _control_iters.end(); ++i) {
288 if (i->x < _control_iter->x) {
293 MIDIMessageType type = NIL;
296 // Next earliest note on
297 if (_note_iter != _seq->notes().end()) {
299 earliest_t = (*_note_iter)->time();
302 // Use the next earliest note off iff it's earlier than the note on
303 if (!_seq->percussive() && (! _active_notes.empty())) {
304 if (type == NIL || _active_notes.top()->end_time() <= earliest_t) {
306 earliest_t = _active_notes.top()->end_time();
310 // Use the next earliest controller iff it's earlier than the note event
311 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
312 if (type == NIL || _control_iter->x <= earliest_t) {
314 earliest_t = _control_iter->x;
318 // Use the next earliest SysEx iff it's earlier than the controller
319 if (_sysex_iter != _seq->sysexes().end()) {
320 if (type == NIL || (*_sysex_iter)->time() <= earliest_t) {
322 earliest_t = (*_sysex_iter)->time();
326 if (type == NOTE_ON) {
327 debugout << "Iterator = note on" << endl;
328 *_event = (*_note_iter)->on_event();
329 _active_notes.push(*_note_iter);
331 } else if (type == NOTE_OFF) {
332 debugout << "Iterator = note off" << endl;
333 *_event = _active_notes.top()->off_event();
335 } else if (type == CONTROL) {
336 debugout << "Iterator = control" << endl;
337 _seq->control_to_midi_event(_event, *_control_iter);
338 } else if (type == SYSEX) {
339 debugout << "Iterator = SysEx" << endl;
340 *_event =*(*_sysex_iter);
343 debugout << "Iterator = End" << endl;
347 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
352 template<typename Time>
354 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
356 if (_is_end || other._is_end) {
357 return (_is_end == other._is_end);
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 (_locked && _seq != other._seq) {
372 _active_notes = other._active_notes;
373 _is_end = other._is_end;
374 _locked = other._locked;
375 _note_iter = other._note_iter;
376 _sysex_iter = other._sysex_iter;
377 _control_iters = other._control_iters;
378 size_t index = other._control_iter - other._control_iters.begin();
379 _control_iter = _control_iters.begin() + index;
381 if (!_is_end && other._event) {
383 *_event = *other._event.get();
385 _event = boost::shared_ptr< Event<Time> >(new Event<Time>(*other._event, true));
398 template<typename Time>
399 Sequence<Time>::Sequence(const TypeMap& type_map, size_t size)
400 : _read_iter(*this, DBL_MAX)
402 , _type_map(type_map)
405 , _end_iter(*this, DBL_MAX)
406 , _next_read(UINT32_MAX)
411 debugout << "Sequence (size " << size << ") constructed: " << this << endl;
412 assert(_end_iter._is_end);
413 assert( ! _end_iter._locked);
416 /** Read events in frame range \a start .. \a start+cnt into \a dst,
417 * adding \a offset to each event's timestamp.
418 * \return number of events written to \a dst
420 template<typename Time>
422 Sequence<Time>::read(EventSink<Time>& dst, timestamp_t start, timedur_t nframes, timestamp_t offset) const
424 debugout << this << " read @ " << start << " * " << nframes << " + " << offset << endl;
425 debugout << this << " # notes: " << n_notes() << endl;
426 debugout << this << " # controls: " << _controls.size() << endl;
428 size_t read_events = 0;
430 if (start != _next_read) {
431 debugout << "Repositioning iterator from " << _next_read << " to " << start << endl;
432 _read_iter = const_iterator(*this, (double)start);
434 debugout << "Using cached iterator at " << _next_read << endl;
437 _next_read = (FrameTime) floor (start + nframes);
439 while (_read_iter != end() && _read_iter->time() < start + nframes) {
440 assert(_read_iter->size() > 0);
441 assert(_read_iter->buffer());
442 dst.write(_read_iter->time() + offset,
443 _read_iter->event_type(),
445 _read_iter->buffer());
447 debugout << this << " read event type " << _read_iter->event_type()
448 << " @ " << _read_iter->time() << " : ";
449 for (size_t i = 0; i < _read_iter->size(); ++i)
450 debugout << hex << (int)_read_iter->buffer()[i];
460 /** Write the controller event pointed to by \a iter to \a ev.
461 * The buffer of \a ev will be allocated or resized as necessary.
462 * The event_type of \a ev should be set to the expected output type.
463 * \return true on success
465 template<typename Time>
467 Sequence<Time>::control_to_midi_event(boost::shared_ptr< Event<Time> >& ev, const ControlIterator& iter) const
469 assert(iter.list.get());
470 const uint32_t event_type = iter.list->parameter().type();
472 // initialize the event pointer with a new event, if necessary
474 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
477 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
478 ev->set_event_type(_type_map.midi_event_type(midi_type));
480 case MIDI_CMD_CONTROL:
481 assert(iter.list.get());
482 assert(iter.list->parameter().channel() < 16);
483 assert(iter.list->parameter().id() <= INT8_MAX);
484 assert(iter.y <= INT8_MAX);
488 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
489 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
490 ev->buffer()[2] = (uint8_t)iter.y;
493 case MIDI_CMD_PGM_CHANGE:
494 assert(iter.list.get());
495 assert(iter.list->parameter().channel() < 16);
496 assert(iter.y <= INT8_MAX);
500 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
501 ev->buffer()[1] = (uint8_t)iter.y;
504 case MIDI_CMD_BENDER:
505 assert(iter.list.get());
506 assert(iter.list->parameter().channel() < 16);
507 assert(iter.y < (1<<14));
511 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
512 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
513 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
516 case MIDI_CMD_CHANNEL_PRESSURE:
517 assert(iter.list.get());
518 assert(iter.list->parameter().channel() < 16);
519 assert(iter.y <= INT8_MAX);
523 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
524 ev->buffer()[1] = (uint8_t)iter.y;
534 /** Clear all events from the model.
536 template<typename Time>
538 Sequence<Time>::clear()
542 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
543 li->second->list()->clear();
546 _lock.writer_unlock();
549 /** Begin a write of events to the model.
551 * If \a mode is Sustained, complete notes with length are constructed as note
552 * on/off events are received. Otherwise (Percussive), only note on events are
553 * stored; note off events are discarded entirely and all contained notes will
556 template<typename Time>
558 Sequence<Time>::start_write()
560 debugout << this << " START WRITE, PERCUSSIVE = " << _percussive << endl;
563 for (int i = 0; i < 16; ++i)
564 _write_notes[i].clear();
566 _dirty_controls.clear();
570 /** Finish a write of events to the model.
572 * If \a delete_stuck is true and the current mode is Sustained, note on events
573 * that were never resolved with a corresonding note off will be deleted.
574 * Otherwise they will remain as notes with length 0.
576 template<typename Time>
578 Sequence<Time>::end_write(bool delete_stuck)
583 debugout << this << " END WRITE: " << _notes.size() << " NOTES\n";
585 if (!_percussive && delete_stuck) {
586 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
587 if ((*n)->length() == 0) {
588 errorout << "WARNING: Stuck note lost: " << (*n)->note() << endl;
590 // we have to break here because erase invalidates the iterator
598 for (int i = 0; i < 16; ++i) {
599 if (!_write_notes[i].empty()) {
600 errorout << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
601 << _write_notes[i].size() << " stuck notes" << endl;
603 _write_notes[i].clear();
606 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
614 /** Append \a ev to model. NOT realtime safe.
616 * Timestamps of events in \a buf are expected to be relative to
617 * the start of this model (t=0) and MUST be monotonically increasing
618 * and MUST be >= the latest event currently in the model.
620 template<typename Time>
622 Sequence<Time>::append(const Event<Time>& event)
627 const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
629 assert(_notes.empty() || ev.time() >= _notes.back()->time());
632 if (ev.is_note_on()) {
633 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(),
635 } else if (ev.is_note_off()) {
636 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
637 } else if (ev.is_sysex()) {
638 append_sysex_unlocked(ev);
639 } else if (!_type_map.type_is_midi(ev.event_type())) {
640 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
641 for (size_t i=0; i < ev.size(); ++i) {
642 printf("%X ", ev.buffer()[i]);
645 } else if (ev.is_cc()) {
646 append_control_unlocked(
647 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
648 ev.time(), ev.cc_value());
649 } else if (ev.is_pgm_change()) {
650 append_control_unlocked(
651 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
652 ev.time(), ev.pgm_number());
653 } else if (ev.is_pitch_bender()) {
654 append_control_unlocked(
655 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
656 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
657 | (0x7F & ev.pitch_bender_lsb()) ));
658 } else if (ev.is_channel_pressure()) {
659 append_control_unlocked(
660 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
661 ev.time(), ev.channel_pressure());
663 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
669 template<typename Time>
671 Sequence<Time>::append_note_on_unlocked(uint8_t chan, Time time, uint8_t note_num, uint8_t velocity)
673 debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
674 assert(note_num <= 127);
679 if (note_num < _lowest_note)
680 _lowest_note = note_num;
681 if (note_num > _highest_note)
682 _highest_note = note_num;
684 boost::shared_ptr< Note<Time> > new_note(new Note<Time>(chan, time, 0, note_num, velocity));
685 _notes.push_back(new_note);
687 debugout << "Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
688 _write_notes[chan].push_back(_notes.size() - 1);
690 debugout << "Percussive: NOT appending active note on" << endl;
694 template<typename Time>
696 Sequence<Time>::append_note_off_unlocked(uint8_t chan, Time time, uint8_t note_num)
698 debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
699 assert(note_num <= 127);
705 debugout << "Sequence Ignoring note off (percussive mode)" << endl;
709 /* FIXME: make _write_notes fixed size (127 noted) for speed */
711 /* FIXME: note off velocity for that one guy out there who actually has
712 * keys that send it */
714 bool resolved = false;
716 for (WriteNotes::iterator n = _write_notes[chan].begin(); n
717 != _write_notes[chan].end(); ++n) {
718 Note<Time>& note = *_notes[*n].get();
719 if (note.note() == note_num) {
720 assert(time >= note.time());
721 note.set_length(time - note.time());
722 _write_notes[chan].erase(n);
723 debugout << "resolved note, length: " << note.length() << endl;
730 errorout << this << " spurious note off chan " << (int)chan
731 << ", note " << (int)note_num << " @ " << time << endl;
735 template<typename Time>
737 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value)
739 debugout << this << " " << _type_map.to_symbol(param) << " @ " << time << " \t= \t" << value
740 << " # controls: " << _controls.size() << endl;
741 boost::shared_ptr<Control> c = control(param, true);
742 c->list()->rt_add(time, value);
745 template<typename Time>
747 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev)
749 debugout << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
750 for (size_t i=0; i < ev.size(); ++i) {
751 debugout << int(ev.buffer()[i]) << " ";
753 debugout << "]" << endl;
755 boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
756 _sysexes.push_back(event);
759 template<typename Time>
761 Sequence<Time>::add_note_unlocked(const boost::shared_ptr< Note<Time> > note)
763 debugout << this << " add note " << (int)note->note() << " @ " << note->time() << endl;
765 typename Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
766 note_time_comparator);
767 _notes.insert(i, note);
770 template<typename Time>
772 Sequence<Time>::remove_note_unlocked(const boost::shared_ptr< const Note<Time> > note)
775 debugout << this << " remove note " << (int)note->note() << " @ " << note->time() << endl;
776 for (typename Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
777 Note<Time>& _n = *(*n);
778 const Note<Time>& _note = *note;
779 // TODO: There is still the issue, that after restarting ardour
780 // persisted undo does not work, because of rounding errors in the
781 // event times after saving/restoring to/from MIDI files
782 /*cerr << "======================================= " << endl;
783 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.length()) << "-- #" << int(_n.velocity()) << endl;
784 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.length()) << "-- #" << int(_note.velocity()) << endl;
785 cerr << "Equal: " << bool(_n == _note) << endl;
786 cerr << endl << endl;*/
789 // we have to break here, because erase invalidates all iterators, ie. n itself
795 /** Slow! for debugging only. */
797 template<typename Time>
799 Sequence<Time>::is_sorted() const {
801 for (typename Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
802 if ((*n)->time() < t)
811 template class Sequence<double>;
813 } // namespace Evoral