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 void Sequence::write_lock() {
43 void Sequence::write_unlock() {
44 _lock.writer_unlock();
45 _control_lock.unlock();
48 void Sequence::read_lock() const {
52 void Sequence::read_unlock() const {
53 _lock.reader_unlock();
56 struct null_ostream : public std::ostream {
57 null_ostream(): std::ios(0), std::ostream(0) {}
59 static null_ostream nullout;
61 //static ostream& debugout = cout;
62 static ostream& debugout = nullout;
63 static ostream& errorout = cerr;
65 // Read iterator (const_iterator)
67 Sequence::const_iterator::const_iterator(const Sequence& seq, EventTime t)
69 , _is_end( (t == DBL_MAX) || seq.empty() )
72 debugout << "Created Iterator @ " << t << " (is end: " << _is_end << ")" << endl;
80 // find first note which begins after t
81 _note_iter = seq.notes().end();
82 for (Sequence::Notes::const_iterator i = seq.notes().begin(); i != seq.notes().end(); ++i) {
83 if ((*i)->time() >= t) {
89 ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
91 _control_iters.reserve(seq._controls.size());
93 // find the earliest control event available
94 for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
95 debugout << "Iterator: control: " << i->first.symbol() << endl;
97 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
99 debugout << "Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
100 << ") has no events past " << t << endl;
106 /*if (y < i->first.min() || y > i->first.max()) {
107 errorout << "ERROR: Controller " << i->first.symbol() << " value " << y
108 << " out of range [" << i->first.min() << "," << i->first.max()
109 << "], event ignored" << endl;
113 const ControlIterator new_iter(i->second->list(), x, y);
115 debugout << "Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
116 _control_iters.push_back(new_iter);
118 // if the x of the current control is less than earliest_control
119 // we have a new earliest_control
120 if (x < earliest_control.x) {
121 earliest_control = new_iter;
122 _control_iter = _control_iters.end();
124 // now _control_iter points to the last Element in _control_iters
128 if (_note_iter != seq.notes().end()
129 && (*_note_iter)->on_event().time() >= t
130 && (!earliest_control.list
131 || (*_note_iter)->on_event().time() < earliest_control.x)) {
132 debugout << "Reading note on event @ " << (*_note_iter)->on_event().time() << endl;
133 _event = boost::shared_ptr<Event>(new Event((*_note_iter)->on_event(), true));
134 _active_notes.push(*_note_iter);
136 _control_iter = _control_iters.end();
137 } else if (earliest_control.list) {
138 debugout << "Reading control event @ " << earliest_control.x << endl;
139 seq.control_to_midi_event(_event, earliest_control);
142 if ( (! _event.get()) || _event->size() == 0) {
143 debugout << "New iterator @ " << t << " is at end." << endl;
146 // eliminate possible race condition here (ugly)
147 static Glib::Mutex mutex;
148 Glib::Mutex::Lock lock(mutex);
154 debugout << "New Iterator = " << _event->event_type();
155 debugout << " : " << hex << (int)((MIDIEvent*)_event.get())->type();
156 debugout << " @ " << _event->time() << endl;
159 //assert(_is_end || (_event->buffer() && _event->buffer()[0] != '\0'));
162 Sequence::const_iterator::~const_iterator()
170 Sequence::const_iterator& Sequence::const_iterator::operator++()
173 throw std::logic_error("Attempt to iterate past end of Sequence");
176 debugout << "Iterator ++" << endl;
177 assert(_event->buffer() && _event->size() > 0);
179 const MIDIEvent& ev = *((MIDIEvent*)_event.get());
181 //debugout << "const_iterator::operator++: " << _event->to_string() << endl;
183 if (! (ev.is_note() || ev.is_cc() || ev.is_pgm_change()
184 || ev.is_pitch_bender() || ev.is_channel_pressure()) ) {
185 errorout << "Unknown event type: " << hex << int(ev.buffer()[0])
186 << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
188 assert((ev.is_note() || ev.is_cc() || ev.is_pgm_change() || ev.is_pitch_bender() || ev.is_channel_pressure()));
190 // Increment past current control event
191 if (!ev.is_note() && _control_iter != _control_iters.end() && _control_iter->list.get()) {
192 double x = 0.0, y = 0.0;
193 const bool ret = _control_iter->list->rt_safe_earliest_event_unlocked(
194 _control_iter->x, DBL_MAX, x, y, false);
196 assert(!ret || x > _control_iter->x);
199 _control_iter->x = x;
200 _control_iter->y = y;
202 _control_iter->list.reset();
203 _control_iter->x = DBL_MAX;
204 _control_iter->y = DBL_MAX;
208 _control_iter = _control_iters.begin();
210 // find the _control_iter with the earliest event time
211 for (ControlIterators::iterator i = _control_iters.begin(); i != _control_iters.end(); ++i) {
212 if (i->x < _control_iter->x) {
217 enum Type {NIL, NOTE_ON, NOTE_OFF, CONTROL};
222 // Next earliest note on
223 if (_note_iter != _seq->notes().end()) {
225 t = (*_note_iter)->time();
228 // Use the next earliest note off iff it's earlier than the note on
229 if (!_seq->percussive() && (! _active_notes.empty())) {
230 if (type == NIL || _active_notes.top()->end_time() <= t) {
232 t = _active_notes.top()->end_time();
236 // Use the next earliest controller iff it's earlier than the note event
237 if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
238 if (type == NIL || _control_iter->x < t) {
243 if (type == NOTE_ON) {
244 debugout << "Iterator = note on" << endl;
245 *_event = (*_note_iter)->on_event();
246 _active_notes.push(*_note_iter);
248 } else if (type == NOTE_OFF) {
249 debugout << "Iterator = note off" << endl;
250 *_event = _active_notes.top()->off_event();
252 } else if (type == CONTROL) {
253 debugout << "Iterator = control" << endl;
254 _seq->control_to_midi_event(_event, *_control_iter);
256 debugout << "Iterator = End" << endl;
260 assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
266 Sequence::const_iterator::operator==(const const_iterator& other) const
268 if (_is_end || other._is_end) {
269 return (_is_end == other._is_end);
271 return (_event == other._event);
275 Sequence::const_iterator&
276 Sequence::const_iterator::operator=(const const_iterator& other)
278 if (_locked && _seq != other._seq) {
283 _active_notes = other._active_notes;
284 _is_end = other._is_end;
285 _locked = other._locked;
286 _note_iter = other._note_iter;
287 _control_iters = other._control_iters;
288 size_t index = other._control_iter - other._control_iters.begin();
289 _control_iter = _control_iters.begin() + index;
291 if (!_is_end && other._event) {
293 *_event = *other._event.get();
295 _event = boost::shared_ptr<Event>(new Event(*other._event, true));
308 Sequence::Sequence(const TypeMap& type_map, size_t size)
309 : _read_iter(*this, DBL_MAX)
311 , _type_map(type_map)
314 , _end_iter(*this, DBL_MAX)
315 , _next_read(UINT32_MAX)
320 debugout << "Sequence (size " << size << ") constructed: " << this << endl;
321 assert(_end_iter._is_end);
322 assert( ! _end_iter._locked);
325 /** Read events in frame range \a start .. \a start+cnt into \a dst,
326 * adding \a offset to each event's timestamp.
327 * \return number of events written to \a dst
330 Sequence::read(EventSink& dst, timestamp_t start, timedur_t nframes, timestamp_t offset) const
332 debugout << this << " read @ " << start << " * " << nframes << " + " << offset << endl;
333 debugout << this << " # notes: " << n_notes() << endl;
334 debugout << this << " # controls: " << _controls.size() << endl;
336 size_t read_events = 0;
338 if (start != _next_read) {
339 debugout << "Repositioning iterator from " << _next_read << " to " << start << endl;
340 _read_iter = const_iterator(*this, (double)start);
342 debugout << "Using cached iterator at " << _next_read << endl;
345 _next_read = (nframes_t) floor (start + nframes);
347 while (_read_iter != end() && _read_iter->time() < start + nframes) {
348 assert(_read_iter->size() > 0);
349 assert(_read_iter->buffer());
350 dst.write(_read_iter->time() + offset,
351 _read_iter->event_type(),
353 _read_iter->buffer());
355 debugout << this << " read event type " << _read_iter->event_type()
356 << " @ " << _read_iter->time() << " : ";
357 for (size_t i = 0; i < _read_iter->size(); ++i)
358 debugout << hex << (int)_read_iter->buffer()[i];
368 /** Write the controller event pointed to by \a iter to \a ev.
369 * The buffer of \a ev will be allocated or resized as necessary.
370 * The event_type of \a ev should be set to the expected output type.
371 * \return true on success
374 Sequence::control_to_midi_event(boost::shared_ptr<Event>& ev, const ControlIterator& iter) const
376 assert(iter.list.get());
377 const uint32_t event_type = iter.list->parameter().type();
379 ev = boost::shared_ptr<Event>(new Event(event_type, 0, 3, NULL, true));
382 uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
383 ev->set_event_type(_type_map.midi_event_type(midi_type));
385 case MIDI_CMD_CONTROL:
386 assert(iter.list.get());
387 assert(iter.list->parameter().channel() < 16);
388 assert(iter.list->parameter().id() <= INT8_MAX);
389 assert(iter.y <= INT8_MAX);
393 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
394 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
395 ev->buffer()[2] = (uint8_t)iter.y;
398 case MIDI_CMD_PGM_CHANGE:
399 assert(iter.list.get());
400 assert(iter.list->parameter().channel() < 16);
401 assert(iter.y <= INT8_MAX);
405 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
406 ev->buffer()[1] = (uint8_t)iter.y;
409 case MIDI_CMD_BENDER:
410 assert(iter.list.get());
411 assert(iter.list->parameter().channel() < 16);
412 assert(iter.y < (1<<14));
416 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
417 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
418 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
421 case MIDI_CMD_CHANNEL_PRESSURE:
422 assert(iter.list.get());
423 assert(iter.list->parameter().channel() < 16);
424 assert(iter.y <= INT8_MAX);
428 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
429 ev->buffer()[1] = (uint8_t)iter.y;
439 /** Clear all events from the model.
446 for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
447 li->second->list()->clear();
450 _lock.writer_unlock();
453 /** Begin a write of events to the model.
455 * If \a mode is Sustained, complete notes with length are constructed as note
456 * on/off events are received. Otherwise (Percussive), only note on events are
457 * stored; note off events are discarded entirely and all contained notes will
461 Sequence::start_write()
463 debugout << this << " START WRITE, PERCUSSIVE = " << _percussive << endl;
466 for (int i = 0; i < 16; ++i)
467 _write_notes[i].clear();
469 _dirty_controls.clear();
473 /** Finish a write of events to the model.
475 * If \a delete_stuck is true and the current mode is Sustained, note on events
476 * that were never resolved with a corresonding note off will be deleted.
477 * Otherwise they will remain as notes with length 0.
480 Sequence::end_write(bool delete_stuck)
485 debugout << this << " END WRITE: " << _notes.size() << " NOTES\n";
487 if (!_percussive && delete_stuck) {
488 for (Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
489 if ((*n)->length() == 0) {
490 errorout << "WARNING: Stuck note lost: " << (*n)->note() << endl;
492 // we have to break here because erase invalidates the iterator
500 for (int i = 0; i < 16; ++i) {
501 if (!_write_notes[i].empty()) {
502 errorout << "WARNING: Sequence::end_write: Channel " << i << " has "
503 << _write_notes[i].size() << " stuck notes" << endl;
505 _write_notes[i].clear();
508 for (ControlLists::const_iterator i = _dirty_controls.begin(); i != _dirty_controls.end(); ++i) {
516 /** Append \a ev to model. NOT realtime safe.
518 * Timestamps of events in \a buf are expected to be relative to
519 * the start of this model (t=0) and MUST be monotonically increasing
520 * and MUST be >= the latest event currently in the model.
523 Sequence::append(const Event& event)
528 const MIDIEvent& ev = (const MIDIEvent&)event;
530 assert(_notes.empty() || ev.time() >= _notes.back()->time());
533 if (ev.is_note_on()) {
534 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(),
536 } else if (ev.is_note_off()) {
537 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
538 } else if (!_type_map.type_is_midi(ev.event_type())) {
539 printf("WARNING: Sequence: Unknown event type %X\n", ev.event_type());
540 } else if (ev.is_cc()) {
541 append_control_unlocked(
542 Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
543 ev.time(), ev.cc_value());
544 } else if (ev.is_pgm_change()) {
545 append_control_unlocked(
546 Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
547 ev.time(), ev.pgm_number());
548 } else if (ev.is_pitch_bender()) {
549 append_control_unlocked(
550 Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
551 ev.time(), double( (0x7F & ev.pitch_bender_msb()) << 7
552 | (0x7F & ev.pitch_bender_lsb()) ));
553 } else if (ev.is_channel_pressure()) {
554 append_control_unlocked(
555 Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
556 ev.time(), ev.channel_pressure());
558 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
565 Sequence::append_note_on_unlocked(uint8_t chan, EventTime time, uint8_t note_num, uint8_t velocity)
567 debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
568 assert(note_num <= 127);
573 if (note_num < _lowest_note)
574 _lowest_note = note_num;
575 if (note_num > _highest_note)
576 _highest_note = note_num;
578 boost::shared_ptr<Note> new_note(new Note(chan, time, 0, note_num, velocity));
579 _notes.push_back(new_note);
581 debugout << "Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
582 _write_notes[chan].push_back(_notes.size() - 1);
584 debugout << "Percussive: NOT appending active note on" << endl;
589 Sequence::append_note_off_unlocked(uint8_t chan, EventTime time, uint8_t note_num)
591 debugout << this << " c" << (int)chan << " note " << (int)note_num << " off @ " << time << endl;
592 assert(note_num <= 127);
598 debugout << "Sequence Ignoring note off (percussive mode)" << endl;
602 /* FIXME: make _write_notes fixed size (127 noted) for speed */
604 /* FIXME: note off velocity for that one guy out there who actually has
605 * keys that send it */
607 bool resolved = false;
609 for (WriteNotes::iterator n = _write_notes[chan].begin(); n
610 != _write_notes[chan].end(); ++n) {
611 Note& note = *_notes[*n].get();
612 if (note.note() == note_num) {
613 assert(time >= note.time());
614 note.set_length(time - note.time());
615 _write_notes[chan].erase(n);
616 debugout << "resolved note, length: " << note.length() << endl;
623 errorout << this << " spurious note off chan " << (int)chan
624 << ", note " << (int)note_num << " @ " << time << endl;
629 Sequence::append_control_unlocked(const Parameter& param, EventTime time, double value)
631 debugout << this << " " << param.symbol() << " @ " << time << " \t= \t" << value
632 << " # controls: " << _controls.size() << endl;
633 control(param, true)->list()->rt_add(time, value);
638 Sequence::add_note_unlocked(const boost::shared_ptr<Note> note)
640 debugout << this << " add note " << (int)note->note() << " @ " << note->time() << endl;
642 Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note,
643 note_time_comparator);
644 _notes.insert(i, note);
648 Sequence::remove_note_unlocked(const boost::shared_ptr<const Note> note)
651 debugout << this << " remove note " << (int)note->note() << " @ " << note->time() << endl;
652 for (Notes::iterator n = _notes.begin(); n != _notes.end(); ++n) {
654 const Note& _note = *note;
655 // TODO: There is still the issue, that after restarting ardour
656 // persisted undo does not work, because of rounding errors in the
657 // event times after saving/restoring to/from MIDI files
658 /*cerr << "======================================= " << endl;
659 cerr << int(_n.note()) << "@" << int(_n.time()) << "[" << int(_n.channel()) << "] --" << int(_n.length()) << "-- #" << int(_n.velocity()) << endl;
660 cerr << int(_note.note()) << "@" << int(_note.time()) << "[" << int(_note.channel()) << "] --" << int(_note.length()) << "-- #" << int(_note.velocity()) << endl;
661 cerr << "Equal: " << bool(_n == _note) << endl;
662 cerr << endl << endl;*/
665 // we have to break here, because erase invalidates all iterators, ie. n itself
671 /** Slow! for debugging only. */
674 Sequence::is_sorted() const {
676 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
677 if ((*n)->time() < t)
686 } // namespace Evoral