1 /*
2  * Copyright (C) 2008-2012 Hans Baier <hansfbaier@googlemail.com>
3  * Copyright (C) 2008-2016 David Robillard <d@drobilla.net>
4  * Copyright (C) 2008-2017 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2009-2011 Carl Hetherington <carl@carlh.net>
6  * Copyright (C) 2014-2019 Robin Gareus <robin@gareus.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22 
23 #include <algorithm>
24 #include <cmath>
25 #include <iostream>
26 #include <limits>
27 #include <stdexcept>
28 #include <stdint.h>
29 #include <cstdio>
30 
31 #if __clang__
32 #include "evoral/Note.h"
33 #endif
34 
35 #include "pbd/compose.h"
36 #include "pbd/error.h"
37 
38 #include "temporal/beats.h"
39 
40 #include "evoral/Control.h"
41 #include "evoral/ControlList.h"
42 #include "evoral/ControlSet.h"
43 #include "evoral/EventSink.h"
44 #include "evoral/ParameterDescriptor.h"
45 #include "evoral/Sequence.h"
46 #include "evoral/TypeMap.h"
47 #include "evoral/midi_util.h"
48 
49 #include "pbd/i18n.h"
50 
51 using namespace std;
52 using namespace PBD;
53 
54 /** Minimum time between MIDI outputs from a single interpolated controller,
55     expressed in beats.  This is to limit the rate at which MIDI messages
56     are generated.  It is only applied to interpolated controllers.
57 
58     XXX: This is a hack.  The time should probably be expressed in
59     seconds rather than beats, and should be configurable etc. etc.
60 */
61 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
62 
63 namespace Evoral {
64 
65 // Read iterator (const_iterator)
66 
67 template<typename Time>
const_iterator()68 Sequence<Time>::const_iterator::const_iterator()
69 	: _seq(NULL)
70 	, _event(boost::shared_ptr< Event<Time> >(new Event<Time>()))
71 	, _active_patch_change_message (NO_EVENT)
72 	, _type(NIL)
73 	, _is_end(true)
74 	, _control_iter(_control_iters.end())
75 	, _force_discrete(false)
76 {
77 }
78 
79 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
80 template<typename Time>
const_iterator(const Sequence<Time> & seq,Time t,bool force_discrete,const std::set<Evoral::Parameter> & filtered,const std::set<WeakNotePtr> * active_notes)81 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>&              seq,
82                                                Time                               t,
83                                                bool                               force_discrete,
84                                                const std::set<Evoral::Parameter>& filtered,
85                                                const std::set<WeakNotePtr>*       active_notes)
86 	: _seq(&seq)
87 	, _active_patch_change_message (0)
88 	, _type(NIL)
89 	, _is_end((t == DBL_MAX) || seq.empty())
90 	, _note_iter(seq.notes().end())
91 	, _sysex_iter(seq.sysexes().end())
92 	, _patch_change_iter(seq.patch_changes().end())
93 	, _control_iter(_control_iters.end())
94 	, _force_discrete (force_discrete)
95 {
96 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
97 
98 	if (_is_end) {
99 		return;
100 	}
101 
102 	_lock = seq.read_lock();
103 
104 	// Add currently active notes, if given
105 	if (active_notes) {
106 		for (typename std::set<WeakNotePtr>::const_iterator i = active_notes->begin();
107 		     i != active_notes->end(); ++i) {
108 			NotePtr note = i->lock();
109 			if (note && note->time() <= t && note->end_time() > t) {
110 				_active_notes.push(note);
111 			}
112 		}
113 	}
114 
115 	// Find first note which begins at or after t
116 	_note_iter = seq.note_lower_bound(t);
117 
118 	// Find first sysex event at or after t
119 	for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
120 	     i != seq.sysexes().end(); ++i) {
121 		if ((*i)->time() >= t) {
122 			_sysex_iter = i;
123 			break;
124 		}
125 	}
126 	assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
127 
128 	// Find first patch event at or after t
129 	for (typename Sequence<Time>::PatchChanges::const_iterator i = seq.patch_changes().begin(); i != seq.patch_changes().end(); ++i) {
130 		if ((*i)->time() >= t) {
131 			_patch_change_iter = i;
132 			break;
133 		}
134 	}
135 	assert (_patch_change_iter == seq.patch_changes().end() || (*_patch_change_iter)->time() >= t);
136 
137 	// Find first control event after t
138 	_control_iters.reserve(seq._controls.size());
139 	bool   found                  = false;
140 	size_t earliest_control_index = 0;
141 	double earliest_control_x     = DBL_MAX;
142 	for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
143 
144 		if (filtered.find (i->first) != filtered.end()) {
145 			/* this parameter is filtered, so don't bother setting up an iterator for it */
146 			continue;
147 		}
148 
149 		DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
150 		double x, y;
151 		bool ret;
152 		if (_force_discrete || i->second->list()->interpolation() == ControlList::Discrete) {
153 			ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t.to_double(), x, y, true);
154 		} else {
155 			ret = i->second->list()->rt_safe_earliest_event_linear_unlocked(t.to_double(), x, y, true);
156 		}
157 		if (!ret) {
158 			DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
159 			                                              i->first.id(), i->second->list()->size(), t));
160 			continue;
161 		}
162 
163 		assert(x >= 0);
164 
165 		const ParameterDescriptor& desc = seq.type_map().descriptor(i->first);
166 		if (y < desc.lower || y > desc.upper) {
167 			cerr << "ERROR: Controller value " << y
168 			     << " out of range [" << desc.lower << "," << desc.upper
169 			     << "], event ignored" << endl;
170 			continue;
171 		}
172 
173 		DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
174 
175 		const ControlIterator new_iter(i->second->list(), x, y);
176 		_control_iters.push_back(new_iter);
177 
178 		// Found a new earliest_control
179 		if (x < earliest_control_x) {
180 			earliest_control_x     = x;
181 			earliest_control_index = _control_iters.size() - 1;
182 			found                  = true;
183 		}
184 	}
185 
186 	if (found) {
187 		_control_iter = _control_iters.begin() + earliest_control_index;
188 		assert(_control_iter != _control_iters.end());
189 		assert(_control_iter->list);
190 	} else {
191 		_control_iter = _control_iters.end();
192 	}
193 
194 	// Choose the earliest event overall to point to
195 	choose_next(t);
196 
197 	// Allocate a new event for storing the current event in MIDI format
198 	_event = boost::shared_ptr< Event<Time> >(
199 		new Event<Time>(NO_EVENT, Time(), 4, NULL, true));
200 
201 	// Set event from chosen sub-iterator
202 	set_event();
203 
204 	if (_is_end) {
205 		DEBUG_TRACE(DEBUG::Sequence,
206 		            string_compose("Starting at end @ %1\n", t));
207 	} else {
208 		DEBUG_TRACE(DEBUG::Sequence,
209 		            string_compose("Starting at type 0x%1 : 0x%2 @ %3\n",
210 		                           (int)_event->event_type(),
211 		                           (int)_event->buffer()[0],
212 		                           _event->time()));
213 	}
214 }
215 
216 template<typename Time>
217 void
invalidate(std::set<boost::weak_ptr<Note<Time>>> * notes)218 Sequence<Time>::const_iterator::invalidate(std::set< boost::weak_ptr< Note<Time> > >* notes)
219 {
220 	while (!_active_notes.empty()) {
221 		if (notes) {
222 			notes->insert(_active_notes.top());
223 		}
224 		_active_notes.pop();
225 	}
226 	_type = NIL;
227 	_is_end = true;
228 	if (_seq) {
229 		_note_iter = _seq->notes().end();
230 		_sysex_iter = _seq->sysexes().end();
231 		_patch_change_iter = _seq->patch_changes().end();
232 		_active_patch_change_message = 0;
233 	}
234 	_control_iters.clear();
235 	_control_iter = _control_iters.end();
236 	_lock.reset();
237 }
238 
239 template<typename Time>
240 Time
choose_next(Time earliest_t)241 Sequence<Time>::const_iterator::choose_next(Time earliest_t)
242 {
243 	_type = NIL;
244 
245 	// Next earliest note on, if any
246 	if (_note_iter != _seq->notes().end()) {
247 		_type      = NOTE_ON;
248 		earliest_t = (*_note_iter)->time();
249 	}
250 
251 	/* Use the next earliest patch change iff it is earlier or coincident with the note-on.
252 	 * A patch-change with the same time-stamp applies to the concurrent note-on */
253 	if (_patch_change_iter != _seq->patch_changes().end()) {
254 		if (_type == NIL || (*_patch_change_iter)->time() <= earliest_t) {
255 			_type      = PATCH_CHANGE;
256 			earliest_t = (*_patch_change_iter)->time();
257 		}
258 	}
259 
260 	/* Use the next earliest controller iff it's earlier or coincident with the note-on
261 	 * or patch-change. Bank-select (CC0, CC32) needs to be sent before the PGM. */
262 	if (_control_iter != _control_iters.end() &&
263 	    _control_iter->list && _control_iter->x != DBL_MAX) {
264 		if (_type == NIL || _control_iter->x <= earliest_t.to_double()) {
265 			_type      = CONTROL;
266 			earliest_t = Time(_control_iter->x);
267 		}
268 	}
269 
270 	/* .. but prefer to send any Note-off first */
271 	if ((!_active_notes.empty())) {
272 		if (_type == NIL || _active_notes.top()->end_time().to_double() <= earliest_t.to_double()) {
273 			_type      = NOTE_OFF;
274 			earliest_t = _active_notes.top()->end_time();
275 		}
276 	}
277 
278 	/* SysEx is last, always sent after any other concurrent 3 byte event */
279 	if (_sysex_iter != _seq->sysexes().end()) {
280 		if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
281 			_type      = SYSEX;
282 			earliest_t = (*_sysex_iter)->time();
283 		}
284 	}
285 
286 	return earliest_t;
287 }
288 
289 template<typename Time>
290 void
set_event()291 Sequence<Time>::const_iterator::set_event()
292 {
293 	switch (_type) {
294 	case NOTE_ON:
295 		DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
296 		_event->assign ((*_note_iter)->on_event());
297 		_active_notes.push(*_note_iter);
298 		break;
299 	case NOTE_OFF:
300 		DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
301 		assert(!_active_notes.empty());
302 		_event->assign (_active_notes.top()->off_event());
303 		// We don't pop the active note until we increment past it
304 		break;
305 	case SYSEX:
306 		DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
307 		_event->assign (*(*_sysex_iter));
308 		break;
309 	case CONTROL:
310 		DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
311 		_seq->control_to_midi_event(_event, *_control_iter);
312 		break;
313 	case PATCH_CHANGE:
314 		DEBUG_TRACE(DEBUG::Sequence, "iterator = program change\n");
315 		_event->assign ((*_patch_change_iter)->message (_active_patch_change_message));
316 		break;
317 	default:
318 		_is_end = true;
319 		break;
320 	}
321 
322 	if (_type == NIL || !_event || _event->size() == 0) {
323 		DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
324 		_type   = NIL;
325 		_is_end = true;
326 	} else {
327 		assert(midi_event_is_valid(_event->buffer(), _event->size()));
328 	}
329 }
330 
331 template<typename Time>
332 const typename Sequence<Time>::const_iterator&
operator ++()333 Sequence<Time>::const_iterator::operator++()
334 {
335 	if (_is_end) {
336 		throw std::logic_error("Attempt to iterate past end of Sequence");
337 	}
338 
339 	assert(_event && _event->buffer() && _event->size() > 0);
340 
341 	const Event<Time>& ev = *_event.get();
342 
343 	if (!(     ev.is_note()
344 	           || ev.is_cc()
345 	           || ev.is_pgm_change()
346 	           || ev.is_pitch_bender()
347 	           || ev.is_channel_pressure()
348 	           || ev.is_poly_pressure()
349 	           || ev.is_sysex()) ) {
350 		cerr << "WARNING: Unknown event (type " << _type << "): " << hex
351 		     << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
352 	}
353 
354 	double x   = 0.0;
355 	double y   = 0.0;
356 	bool   ret = false;
357 
358 	// Increment past current event
359 	switch (_type) {
360 	case NOTE_ON:
361 		++_note_iter;
362 		break;
363 	case NOTE_OFF:
364 		_active_notes.pop();
365 		break;
366 	case CONTROL:
367 		// Increment current controller iterator
368 		if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
369 			ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
370 				_control_iter->x, x, y, false);
371 		} else {
372 			ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
373 				_control_iter->x, x, y, false, time_between_interpolated_controller_outputs);
374 		}
375 		assert(!ret || x > _control_iter->x);
376 		if (ret) {
377 			_control_iter->x = x;
378 			_control_iter->y = y;
379 		} else {
380 			_control_iter->list.reset();
381 			_control_iter->x = DBL_MAX;
382 			_control_iter->y = DBL_MAX;
383 		}
384 
385 		// Find the controller with the next earliest event time
386 		_control_iter = _control_iters.begin();
387 		for (ControlIterators::iterator i = _control_iters.begin();
388 		     i != _control_iters.end(); ++i) {
389 			if (i->x < _control_iter->x) {
390 				_control_iter = i;
391 			}
392 		}
393 		break;
394 	case SYSEX:
395 		++_sysex_iter;
396 		break;
397 	case PATCH_CHANGE:
398 		++_active_patch_change_message;
399 		if (_active_patch_change_message == (*_patch_change_iter)->messages()) {
400 			++_patch_change_iter;
401 			_active_patch_change_message = 0;
402 		}
403 		break;
404 	default:
405 		assert(false);
406 	}
407 
408 	// Choose the earliest event overall to point to
409 	choose_next(std::numeric_limits<Time>::max());
410 
411 	// Set event from chosen sub-iterator
412 	set_event();
413 
414 	assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
415 
416 	return *this;
417 }
418 
419 template<typename Time>
420 bool
operator ==(const const_iterator & other) const421 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
422 {
423 	if (_seq != other._seq) {
424 		return false;
425 	} else if (_is_end || other._is_end) {
426 		return (_is_end == other._is_end);
427 	} else if (_type != other._type) {
428 		return false;
429 	} else {
430 		return (_event == other._event);
431 	}
432 }
433 
434 template<typename Time>
435 typename Sequence<Time>::const_iterator&
operator =(const const_iterator & other)436 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
437 {
438 	_seq           = other._seq;
439 	_event         = other._event;
440 	_active_notes  = other._active_notes;
441 	_type          = other._type;
442 	_is_end        = other._is_end;
443 	_note_iter     = other._note_iter;
444 	_sysex_iter    = other._sysex_iter;
445 	_patch_change_iter = other._patch_change_iter;
446 	_control_iters = other._control_iters;
447 	_force_discrete = other._force_discrete;
448 	_active_patch_change_message = other._active_patch_change_message;
449 
450 	if (other._lock) {
451 		_lock = _seq->read_lock();
452 	} else {
453 		_lock.reset();
454 	}
455 
456 	if (other._control_iter == other._control_iters.end()) {
457 		_control_iter = _control_iters.end();
458 	} else {
459 		const size_t index = other._control_iter - other._control_iters.begin();
460 		_control_iter  = _control_iters.begin() + index;
461 	}
462 
463 	return *this;
464 }
465 
466 // Sequence
467 
468 template<typename Time>
Sequence(const TypeMap & type_map)469 Sequence<Time>::Sequence(const TypeMap& type_map)
470 	: _edited(false)
471 	, _overlapping_pitches_accepted (true)
472 	, _overlap_pitch_resolution (FirstOnFirstOff)
473 	, _writing(false)
474 	, _type_map(type_map)
475 	, _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
476 	, _percussive(false)
477 	, _lowest_note(127)
478 	, _highest_note(0)
479 {
480 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
481 	assert(_end_iter._is_end);
482 	assert( ! _end_iter._lock);
483 
484 	for (int i = 0; i < 16; ++i) {
485 		_bank[i] = 0;
486 	}
487 }
488 
489 template<typename Time>
Sequence(const Sequence<Time> & other)490 Sequence<Time>::Sequence(const Sequence<Time>& other)
491 	: ControlSet (other)
492 	, _edited(false)
493 	, _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
494 	, _overlap_pitch_resolution (other._overlap_pitch_resolution)
495 	, _writing(false)
496 	, _type_map(other._type_map)
497 	, _end_iter(*this, std::numeric_limits<Time>::max(), false, std::set<Evoral::Parameter> ())
498 	, _percussive(other._percussive)
499 	, _lowest_note(other._lowest_note)
500 	, _highest_note(other._highest_note)
501 {
502 	for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
503 		NotePtr n (new Note<Time> (**i));
504 		_notes.insert (n);
505 	}
506 
507 	for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
508 		boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
509 		_sysexes.insert (n);
510 	}
511 
512 	for (typename PatchChanges::const_iterator i = other._patch_changes.begin(); i != other._patch_changes.end(); ++i) {
513 		PatchChangePtr n (new PatchChange<Time> (**i));
514 		_patch_changes.insert (n);
515 	}
516 
517 	for (int i = 0; i < 16; ++i) {
518 		_bank[i] = other._bank[i];
519 	}
520 
521 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
522 	assert(_end_iter._is_end);
523 	assert(! _end_iter._lock);
524 }
525 
526 /** Write the controller event pointed to by `iter` to `ev`.
527  * The buffer of `ev` will be allocated or resized as necessary.
528  * \return true on success
529  */
530 template<typename Time>
531 bool
control_to_midi_event(boost::shared_ptr<Event<Time>> & ev,const ControlIterator & iter) const532 Sequence<Time>::control_to_midi_event(
533 	boost::shared_ptr< Event<Time> >& ev,
534 	const ControlIterator&            iter) const
535 {
536 	assert(iter.list.get());
537 
538 	// initialize the event pointer with a new event, if necessary
539 	if (!ev) {
540 		ev = boost::shared_ptr< Event<Time> >(new Event<Time>(NO_EVENT, Time(), 3, NULL, true));
541 	}
542 
543 	const uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
544 	ev->set_event_type(MIDI_EVENT);
545 	ev->set_id(-1);
546 	switch (midi_type) {
547 	case MIDI_CMD_CONTROL:
548 		assert(iter.list.get());
549 		assert(iter.list->parameter().channel() < 16);
550 		assert(iter.list->parameter().id() <= INT8_MAX);
551 		assert(iter.y <= INT8_MAX);
552 
553 		ev->set_time(Time(iter.x));
554 		ev->realloc(3);
555 		ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
556 		ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
557 		ev->buffer()[2] = (uint8_t)iter.y;
558 		break;
559 
560 	case MIDI_CMD_PGM_CHANGE:
561 		assert(iter.list.get());
562 		assert(iter.list->parameter().channel() < 16);
563 		assert(iter.y <= INT8_MAX);
564 
565 		ev->set_time(Time(iter.x));
566 		ev->realloc(2);
567 		ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
568 		ev->buffer()[1] = (uint8_t)iter.y;
569 		break;
570 
571 	case MIDI_CMD_BENDER:
572 		assert(iter.list.get());
573 		assert(iter.list->parameter().channel() < 16);
574 		assert(iter.y < (1<<14));
575 
576 		ev->set_time(Time(iter.x));
577 		ev->realloc(3);
578 		ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
579 		ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
580 		ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
581 		break;
582 
583 	case MIDI_CMD_NOTE_PRESSURE:
584 		assert(iter.list.get());
585 		assert(iter.list->parameter().channel() < 16);
586 		assert(iter.list->parameter().id() <= INT8_MAX);
587 		assert(iter.y <= INT8_MAX);
588 
589 		ev->set_time(Time(iter.x));
590 		ev->realloc(3);
591 		ev->buffer()[0] = MIDI_CMD_NOTE_PRESSURE + iter.list->parameter().channel();
592 		ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
593 		ev->buffer()[2] = (uint8_t)iter.y;
594 		break;
595 
596 	case MIDI_CMD_CHANNEL_PRESSURE:
597 		assert(iter.list.get());
598 		assert(iter.list->parameter().channel() < 16);
599 		assert(iter.y <= INT8_MAX);
600 
601 		ev->set_time(Time(iter.x));
602 		ev->realloc(2);
603 		ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
604 		ev->buffer()[1] = (uint8_t)iter.y;
605 		break;
606 
607 	default:
608 		return false;
609 	}
610 
611 	return true;
612 }
613 
614 /** Clear all events from the model.
615  */
616 template<typename Time>
617 void
clear()618 Sequence<Time>::clear()
619 {
620 	WriteLock lock(write_lock());
621 	_notes.clear();
622 	for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
623 		li->second->list()->clear();
624 }
625 
626 /** Begin a write of events to the model.
627  *
628  * If \a mode is Sustained, complete notes with length are constructed as note
629  * on/off events are received.  Otherwise (Percussive), only note on events are
630  * stored; note off events are discarded entirely and all contained notes will
631  * have length 0.
632  */
633 template<typename Time>
634 void
start_write()635 Sequence<Time>::start_write()
636 {
637 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
638 	WriteLock lock(write_lock());
639 	_writing = true;
640 	for (int i = 0; i < 16; ++i) {
641 		_write_notes[i].clear();
642 	}
643 }
644 
645 /** Finish a write of events to the model.
646  *
647  * If \a delete_stuck is true and the current mode is Sustained, note on events
648  * that were never resolved with a corresonding note off will be deleted.
649  * Otherwise they will remain as notes with length 0.
650  */
651 template<typename Time>
652 void
end_write(StuckNoteOption option,Time when)653 Sequence<Time>::end_write (StuckNoteOption option, Time when)
654 {
655 	WriteLock lock(write_lock());
656 
657 	if (!_writing) {
658 		return;
659 	}
660 
661 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes) delete stuck option %3 @ %4\n", this, _notes.size(), option, when));
662 
663 	for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
664 		typename Notes::iterator next = n;
665 		++next;
666 
667 		if ((*n)->end_time() == std::numeric_limits<Temporal::Beats>::max()) {
668 			switch (option) {
669 			case Relax:
670 				break;
671 			case DeleteStuckNotes:
672 				cerr << "WARNING: Stuck note lost (end was " << when << "): " << (**n) << endl;
673 				_notes.erase(n);
674 				break;
675 			case ResolveStuckNotes:
676 				if (when <= (*n)->time()) {
677 					cerr << "WARNING: Stuck note resolution - end time @ "
678 					     << when << " is before note on: " << (**n) << endl;
679 					_notes.erase (n);
680 				} else {
681 					(*n)->set_length (when - (*n)->time());
682 					cerr << "WARNING: resolved note-on with no note-off to generate " << (**n) << endl;
683 				}
684 				break;
685 			}
686 		}
687 
688 		n = next;
689 	}
690 
691 	for (int i = 0; i < 16; ++i) {
692 		_write_notes[i].clear();
693 	}
694 
695 	_writing = false;
696 }
697 
698 
699 template<typename Time>
700 bool
add_note_unlocked(const NotePtr note,void * arg)701 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
702 {
703 	/* This is the core method to add notes to a Sequence
704 	 */
705 
706 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3 dur %4\n", this, (int)note->note(), note->time(), note->length()));
707 
708 	if (resolve_overlaps_unlocked (note, arg)) {
709 		DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
710 		return false;
711 	}
712 
713 	if (note->id() < 0) {
714 		note->set_id (Evoral::next_event_id());
715 	}
716 
717 	if (note->note() < _lowest_note)
718 		_lowest_note = note->note();
719 	if (note->note() > _highest_note)
720 		_highest_note = note->note();
721 
722 	_notes.insert (note);
723 	_pitches[note->channel()].insert (note);
724 
725 	_edited = true;
726 
727 	return true;
728 }
729 
730 template<typename Time>
731 void
remove_note_unlocked(const constNotePtr note)732 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
733 {
734 	bool erased = false;
735 	bool id_matched = false;
736 
737 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
738 
739 	/* first try searching for the note using the time index, which is
740 	 * faster since the container is "indexed" by time. (technically, this
741 	 * means that lower_bound() can do a binary search rather than linear)
742 	 *
743 	 * this may not work, for reasons explained below.
744 	 */
745 
746 	typename Sequence<Time>::Notes::iterator i;
747 
748 	for (i = note_lower_bound(note->time()); i != _notes.end() && (*i)->time() == note->time(); ++i) {
749 
750 		if (*i == note) {
751 
752 			DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
753 			_notes.erase (i);
754 
755 			if (note->note() == _lowest_note || note->note() == _highest_note) {
756 
757 				_lowest_note = 127;
758 				_highest_note = 0;
759 
760 				for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
761 					if ((*ii)->note() < _lowest_note)
762 						_lowest_note = (*ii)->note();
763 					if ((*ii)->note() > _highest_note)
764 						_highest_note = (*ii)->note();
765 				}
766 			}
767 
768 			erased = true;
769 			break;
770 		}
771 	}
772 
773 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\ttime-based lookup did not find note #%2 %3 @ %4\n", this, note->id(), (int)note->note(), note->time()));
774 
775 	if (!erased) {
776 
777 		/* if the note's time property was changed in tandem with some
778 		 * other property as the next operation after it was added to
779 		 * the sequence, then at the point where we call this to undo
780 		 * the add, the note we are targetting currently has a
781 		 * different time property than the one we we passed via
782 		 * the argument.
783 		 *
784 		 * in this scenario, we have no choice other than to linear
785 		 * search the list of notes and find the note by ID.
786 		 */
787 
788 		for (i = _notes.begin(); i != _notes.end(); ++i) {
789 
790 			if ((*i)->id() == note->id()) {
791 
792 				DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\tID-based pass, erasing note #%2 %3 @ %4\n", this, (*i)->id(), (int)(*i)->note(), (*i)->time()));
793 				_notes.erase (i);
794 
795 				if (note->note() == _lowest_note || note->note() == _highest_note) {
796 
797 					_lowest_note = 127;
798 					_highest_note = 0;
799 
800 					for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
801 						if ((*ii)->note() < _lowest_note)
802 							_lowest_note = (*ii)->note();
803 						if ((*ii)->note() > _highest_note)
804 							_highest_note = (*ii)->note();
805 					}
806 				}
807 
808 				erased = true;
809 				id_matched = true;
810 				break;
811 			}
812 		}
813 	}
814 
815 	if (erased) {
816 
817 		Pitches& p (pitches (note->channel()));
818 
819 		typename Pitches::iterator j;
820 
821 		/* if we had to ID-match above, we can't expect to find it in
822 		 * pitches via note comparison either. so do another linear
823 		 * search to locate it. otherwise, we can use the note index
824 		 * to potentially speed things up.
825 		 */
826 
827 		if (id_matched) {
828 
829 			for (j = p.begin(); j != p.end(); ++j) {
830 				if ((*j)->id() == note->id()) {
831 					p.erase (j);
832 					break;
833 				}
834 			}
835 
836 		} else {
837 
838 			/* Now find the same note in the "pitches" list (which indexes
839 			 * notes by channel+time. We care only about its note number
840 			 * so the search_note has all other properties unset.
841 			 */
842 
843 			NotePtr search_note (new Note<Time>(0, Time(), Time(), note->note(), 0));
844 
845 			for (j = p.lower_bound (search_note); j != p.end() && (*j)->note() == note->note(); ++j) {
846 
847 				if ((*j) == note) {
848 					DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*j)->note(), (*j)->time()));
849 					p.erase (j);
850 					break;
851 				}
852 			}
853 		}
854 
855 		if (j == p.end()) {
856 			warning << string_compose ("erased note %1 not found in pitches for channel %2", *note, (int) note->channel()) << endmsg;
857 		}
858 
859 		_edited = true;
860 
861 	} else {
862 		cerr << "Unable to find note to erase matching " << *note.get() << endmsg;
863 	}
864 }
865 
866 template<typename Time>
867 void
remove_patch_change_unlocked(const constPatchChangePtr p)868 Sequence<Time>::remove_patch_change_unlocked (const constPatchChangePtr p)
869 {
870 	typename Sequence<Time>::PatchChanges::iterator i = patch_change_lower_bound (p->time ());
871 
872 	while (i != _patch_changes.end() && ((*i)->time() == p->time())) {
873 
874 		typename Sequence<Time>::PatchChanges::iterator tmp = i;
875 		++tmp;
876 
877 		if (**i == *p) {
878 			_patch_changes.erase (i);
879 		}
880 
881 		i = tmp;
882 	}
883 }
884 
885 template<typename Time>
886 void
remove_sysex_unlocked(const SysExPtr sysex)887 Sequence<Time>::remove_sysex_unlocked (const SysExPtr sysex)
888 {
889 	typename Sequence<Time>::SysExes::iterator i = sysex_lower_bound (sysex->time ());
890 	while (i != _sysexes.end() && (*i)->time() == sysex->time()) {
891 
892 		typename Sequence<Time>::SysExes::iterator tmp = i;
893 		++tmp;
894 
895 		if (*i == sysex) {
896 			_sysexes.erase (i);
897 		}
898 
899 		i = tmp;
900 	}
901 }
902 
903 /** Append \a ev to model.  NOT realtime safe.
904  *
905  * The timestamp of event is expected to be relative to
906  * the start of this model (t=0) and MUST be monotonically increasing
907  * and MUST be >= the latest event currently in the model.
908  */
909 template<typename Time>
910 void
append(const Event<Time> & ev,event_id_t evid)911 Sequence<Time>::append(const Event<Time>& ev, event_id_t evid)
912 {
913 	WriteLock lock(write_lock());
914 
915 	assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
916 	assert(_writing);
917 
918 	if (!midi_event_is_valid(ev.buffer(), ev.size())) {
919 		cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
920 		return;
921 	}
922 
923 	if (ev.is_note_on() && ev.velocity() > 0) {
924 		append_note_on_unlocked (ev, evid);
925 	} else if (ev.is_note_off() || (ev.is_note_on() && ev.velocity() == 0)) {
926 		/* XXX note: event ID is discarded because we merge the on+off events into
927 		   a single note object
928 		*/
929 		append_note_off_unlocked (ev);
930 	} else if (ev.is_sysex()) {
931 		append_sysex_unlocked(ev, evid);
932 	} else if (ev.is_cc() && (ev.cc_number() == MIDI_CTL_MSB_BANK || ev.cc_number() == MIDI_CTL_LSB_BANK)) {
933 		/* note bank numbers in our _bank[] array, so that we can write an event when the program change arrives */
934 		if (ev.cc_number() == MIDI_CTL_MSB_BANK) {
935 			_bank[ev.channel()] &= ~(0x7f << 7);
936 			_bank[ev.channel()] |= ev.cc_value() << 7;
937 		} else {
938 			_bank[ev.channel()] &= ~0x7f;
939 			_bank[ev.channel()] |= ev.cc_value();
940 		}
941 	} else if (ev.is_cc()) {
942 		const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
943 		append_control_unlocked(
944 			Parameter(ptype, ev.channel(), ev.cc_number()),
945 			ev.time(), ev.cc_value(), evid);
946 	} else if (ev.is_pgm_change()) {
947 		/* write a patch change with this program change and any previously set-up bank number */
948 		append_patch_change_unlocked (
949 			PatchChange<Time> (ev.time(), ev.channel(),
950 			                   ev.pgm_number(), _bank[ev.channel()]), evid);
951 	} else if (ev.is_pitch_bender()) {
952 		const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
953 		append_control_unlocked(
954 			Parameter(ptype, ev.channel()),
955 			ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
956 			                   | (0x7F & ev.pitch_bender_lsb())),
957 			evid);
958 	} else if (ev.is_poly_pressure()) {
959 		const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
960 		append_control_unlocked (Parameter (ptype, ev.channel(), ev.poly_note()), ev.time(), ev.poly_pressure(), evid);
961 	} else if (ev.is_channel_pressure()) {
962 		const ParameterType ptype = _type_map.midi_parameter_type(ev.buffer(), ev.size());
963 		append_control_unlocked(
964 			Parameter(ptype, ev.channel()),
965 			ev.time(), ev.channel_pressure(), evid);
966 	} else if (!_type_map.type_is_midi(ev.event_type())) {
967 		printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
968 		for (size_t i=0; i < ev.size(); ++i) {
969 			printf("%X ", ev.buffer()[i]);
970 		}
971 		printf("\n");
972 	} else {
973 		printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
974 	}
975 
976 	_edited = true;
977 }
978 
979 template<typename Time>
980 void
append_note_on_unlocked(const Event<Time> & ev,event_id_t evid)981 Sequence<Time>::append_note_on_unlocked (const Event<Time>& ev, event_id_t evid)
982 {
983 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this,
984 	                                              (int)ev.channel(), (int)ev.note(),
985 	                                              ev.time(), (int)ev.velocity()));
986 	assert(_writing);
987 
988 	if (ev.note() > 127) {
989 		error << string_compose (_("invalid note on number (%1) ignored"), (int) ev.note()) << endmsg;
990 		return;
991 	} else if (ev.channel() >= 16) {
992 		error << string_compose (_("invalid note on channel (%1) ignored"), (int) ev.channel()) << endmsg;
993 		return;
994 	} else if (ev.velocity() == 0) {
995 		// Note on with velocity 0 handled as note off by caller
996 		error << string_compose (_("invalid note on velocity (%1) ignored"), (int) ev.velocity()) << endmsg;
997 		return;
998 	}
999 
1000 	/* nascent (incoming notes without a note-off ...yet) have a duration
1001 	   that extends to Beats::max()
1002 	*/
1003 	NotePtr note(new Note<Time>(ev.channel(), ev.time(), std::numeric_limits<Temporal::Beats>::max() - ev.time(), ev.note(), ev.velocity()));
1004 	assert (note->end_time() == std::numeric_limits<Temporal::Beats>::max());
1005 	note->set_id (evid);
1006 
1007 	add_note_unlocked (note);
1008 
1009 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("Appending active note on %1 channel %2\n",
1010 	                                              (unsigned)(uint8_t)note->note(), note->channel()));
1011 	_write_notes[note->channel()].insert (note);
1012 
1013 }
1014 
1015 template<typename Time>
1016 void
append_note_off_unlocked(const Event<Time> & ev)1017 Sequence<Time>::append_note_off_unlocked (const Event<Time>& ev)
1018 {
1019 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 OFF @ %4 v=%5\n",
1020 	                                              this, (int)ev.channel(),
1021 	                                              (int)ev.note(), ev.time(), (int)ev.velocity()));
1022 	assert(_writing);
1023 
1024 	if (ev.note() > 127) {
1025 		error << string_compose (_("invalid note off number (%1) ignored"), (int) ev.note()) << endmsg;
1026 		return;
1027 	} else if (ev.channel() >= 16) {
1028 		error << string_compose (_("invalid note off channel (%1) ignored"), (int) ev.channel()) << endmsg;
1029 		return;
1030 	}
1031 
1032 	_edited = true;
1033 
1034 	bool resolved = false;
1035 
1036 	/* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
1037 	   matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
1038 	   whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
1039 	   format.
1040 	*/
1041 
1042 	/* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
1043 
1044 	for (typename WriteNotes::iterator n = _write_notes[ev.channel()].begin(); n != _write_notes[ev.channel()].end(); ) {
1045 
1046 		typename WriteNotes::iterator tmp = n;
1047 		++tmp;
1048 
1049 		NotePtr nn = *n;
1050 		if (ev.note() == nn->note() && nn->channel() == ev.channel()) {
1051 			assert(ev.time() >= nn->time());
1052 
1053 			nn->set_length (ev.time() - nn->time());
1054 			nn->set_off_velocity (ev.velocity());
1055 
1056 			_write_notes[ev.channel()].erase(n);
1057 			DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note @ %2 length: %1\n", nn->length(), nn->time()));
1058 			resolved = true;
1059 			break;
1060 		}
1061 
1062 		n = tmp;
1063 	}
1064 
1065 	if (!resolved) {
1066 		cerr << this << " spurious note off chan " << (int)ev.channel()
1067 		     << ", note " << (int)ev.note() << " @ " << ev.time() << endl;
1068 	}
1069 }
1070 
1071 template<typename Time>
1072 void
append_control_unlocked(const Parameter & param,Time time,double value,event_id_t)1073 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
1074 {
1075 	DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3 = %4 # controls: %5\n",
1076 	                                              this, _type_map.to_symbol(param), time, value, _controls.size()));
1077 	boost::shared_ptr<Control> c = control(param, true);
1078 	c->list()->add (time.to_double(), value, true, false);
1079 	/* XXX control events should use IDs */
1080 }
1081 
1082 template<typename Time>
1083 void
append_sysex_unlocked(const Event<Time> & ev,event_id_t)1084 Sequence<Time>::append_sysex_unlocked(const Event<Time>& ev, event_id_t /* evid */)
1085 {
1086 #ifdef DEBUG_SEQUENCE
1087 	cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
1088 	for (size_t i=0; i < ev.size(); ++i) {
1089 		cerr << int(ev.buffer()[i]) << " ";
1090 	} cerr << "]" << endl;
1091 #endif
1092 
1093 	boost::shared_ptr< Event<Time> > event(new Event<Time>(ev, true));
1094 	/* XXX sysex events should use IDs */
1095 	_sysexes.insert(event);
1096 }
1097 
1098 template<typename Time>
1099 void
append_patch_change_unlocked(const PatchChange<Time> & ev,event_id_t id)1100 Sequence<Time>::append_patch_change_unlocked (const PatchChange<Time>& ev, event_id_t id)
1101 {
1102 	PatchChangePtr p (new PatchChange<Time> (ev));
1103 
1104 	if (p->id() < 0) {
1105 		p->set_id (id);
1106 	}
1107 
1108 	_patch_changes.insert (p);
1109 }
1110 
1111 template<typename Time>
1112 void
add_patch_change_unlocked(PatchChangePtr p)1113 Sequence<Time>::add_patch_change_unlocked (PatchChangePtr p)
1114 {
1115 	if (p->id () < 0) {
1116 		p->set_id (Evoral::next_event_id ());
1117 	}
1118 
1119 	_patch_changes.insert (p);
1120 }
1121 
1122 template<typename Time>
1123 void
add_sysex_unlocked(SysExPtr s)1124 Sequence<Time>::add_sysex_unlocked (SysExPtr s)
1125 {
1126 	if (s->id () < 0) {
1127 		s->set_id (Evoral::next_event_id ());
1128 	}
1129 
1130 	_sysexes.insert (s);
1131 }
1132 
1133 template<typename Time>
1134 bool
contains(const NotePtr & note) const1135 Sequence<Time>::contains (const NotePtr& note) const
1136 {
1137 	ReadLock lock (read_lock());
1138 	return contains_unlocked (note);
1139 }
1140 
1141 template<typename Time>
1142 bool
contains_unlocked(const NotePtr & note) const1143 Sequence<Time>::contains_unlocked (const NotePtr& note) const
1144 {
1145 	const Pitches& p (pitches (note->channel()));
1146 	NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1147 
1148 	for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1149 	     i != p.end() && (*i)->note() == note->note(); ++i) {
1150 
1151 		if (**i == *note) {
1152 			return true;
1153 		}
1154 	}
1155 
1156 	return false;
1157 }
1158 
1159 template<typename Time>
1160 bool
overlaps(const NotePtr & note,const NotePtr & without) const1161 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
1162 {
1163 	ReadLock lock (read_lock());
1164 	return overlaps_unlocked (note, without);
1165 }
1166 
1167 template<typename Time>
1168 bool
overlaps_unlocked(const NotePtr & note,const NotePtr & without) const1169 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
1170 {
1171 	Time sa = note->time();
1172 	Time ea  = note->end_time();
1173 
1174 	const Pitches& p (pitches (note->channel()));
1175 	NotePtr search_note(new Note<Time>(0, Time(), Time(), note->note()));
1176 
1177 	for (typename Pitches::const_iterator i = p.lower_bound (search_note);
1178 	     i != p.end() && (*i)->note() == note->note(); ++i) {
1179 
1180 		if (without && (**i) == *without) {
1181 			continue;
1182 		}
1183 
1184 		Time sb = (*i)->time();
1185 		Time eb = (*i)->end_time();
1186 
1187 		if (((sb > sa) && (eb <= ea)) ||
1188 		    ((eb >= sa) && (eb <= ea)) ||
1189 		    ((sb > sa) && (sb <= ea)) ||
1190 		    ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
1191 			return true;
1192 		}
1193 	}
1194 
1195 	return false;
1196 }
1197 
1198 template<typename Time>
1199 void
set_notes(const typename Sequence<Time>::Notes & n)1200 Sequence<Time>::set_notes (const typename Sequence<Time>::Notes& n)
1201 {
1202 	_notes = n;
1203 }
1204 
1205 // CONST iterator implementations (x3)
1206 
1207 /** Return the earliest note with time >= t */
1208 template<typename Time>
1209 typename Sequence<Time>::Notes::const_iterator
note_lower_bound(Time t) const1210 Sequence<Time>::note_lower_bound (Time t) const
1211 {
1212 	NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1213 	typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
1214 	assert(i == _notes.end() || (*i)->time() >= t);
1215 	return i;
1216 }
1217 
1218 /** Return the earliest patch change with time >= t */
1219 template<typename Time>
1220 typename Sequence<Time>::PatchChanges::const_iterator
patch_change_lower_bound(Time t) const1221 Sequence<Time>::patch_change_lower_bound (Time t) const
1222 {
1223 	PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1224 	typename Sequence<Time>::PatchChanges::const_iterator i = _patch_changes.lower_bound (search);
1225 	assert (i == _patch_changes.end() || (*i)->time() >= t);
1226 	return i;
1227 }
1228 
1229 /** Return the earliest sysex with time >= t */
1230 template<typename Time>
1231 typename Sequence<Time>::SysExes::const_iterator
sysex_lower_bound(Time t) const1232 Sequence<Time>::sysex_lower_bound (Time t) const
1233 {
1234 	SysExPtr search (new Event<Time> (NO_EVENT, t));
1235 	typename Sequence<Time>::SysExes::const_iterator i = _sysexes.lower_bound (search);
1236 	assert (i == _sysexes.end() || (*i)->time() >= t);
1237 	return i;
1238 }
1239 
1240 // NON-CONST iterator implementations (x3)
1241 
1242 /** Return the earliest note with time >= t */
1243 template<typename Time>
1244 typename Sequence<Time>::Notes::iterator
note_lower_bound(Time t)1245 Sequence<Time>::note_lower_bound (Time t)
1246 {
1247 	NotePtr search_note(new Note<Time>(0, t, Time(), 0, 0));
1248 	typename Sequence<Time>::Notes::iterator i = _notes.lower_bound(search_note);
1249 	assert(i == _notes.end() || (*i)->time() >= t);
1250 	return i;
1251 }
1252 
1253 /** Return the earliest patch change with time >= t */
1254 template<typename Time>
1255 typename Sequence<Time>::PatchChanges::iterator
patch_change_lower_bound(Time t)1256 Sequence<Time>::patch_change_lower_bound (Time t)
1257 {
1258 	PatchChangePtr search (new PatchChange<Time> (t, 0, 0, 0));
1259 	typename Sequence<Time>::PatchChanges::iterator i = _patch_changes.lower_bound (search);
1260 	assert (i == _patch_changes.end() || (*i)->time() >= t);
1261 	return i;
1262 }
1263 
1264 /** Return the earliest sysex with time >= t */
1265 template<typename Time>
1266 typename Sequence<Time>::SysExes::iterator
sysex_lower_bound(Time t)1267 Sequence<Time>::sysex_lower_bound (Time t)
1268 {
1269 	SysExPtr search (new Event<Time> (NO_EVENT, t));
1270 	typename Sequence<Time>::SysExes::iterator i = _sysexes.lower_bound (search);
1271 	assert (i == _sysexes.end() || (*i)->time() >= t);
1272 	return i;
1273 }
1274 
1275 template<typename Time>
1276 void
get_notes(Notes & n,NoteOperator op,uint8_t val,int chan_mask) const1277 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1278 {
1279 	switch (op) {
1280 	case PitchEqual:
1281 	case PitchLessThan:
1282 	case PitchLessThanOrEqual:
1283 	case PitchGreater:
1284 	case PitchGreaterThanOrEqual:
1285 		get_notes_by_pitch (n, op, val, chan_mask);
1286 		break;
1287 
1288 	case VelocityEqual:
1289 	case VelocityLessThan:
1290 	case VelocityLessThanOrEqual:
1291 	case VelocityGreater:
1292 	case VelocityGreaterThanOrEqual:
1293 		get_notes_by_velocity (n, op, val, chan_mask);
1294 		break;
1295 	}
1296 }
1297 
1298 template<typename Time>
1299 void
get_notes_by_pitch(Notes & n,NoteOperator op,uint8_t val,int chan_mask) const1300 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1301 {
1302 	for (uint8_t c = 0; c < 16; ++c) {
1303 
1304 		if (chan_mask != 0 && !((1<<c) & chan_mask)) {
1305 			continue;
1306 		}
1307 
1308 		const Pitches& p (pitches (c));
1309 		NotePtr search_note(new Note<Time>(0, Time(), Time(), val, 0));
1310 		typename Pitches::const_iterator i;
1311 		switch (op) {
1312 		case PitchEqual:
1313 			i = p.lower_bound (search_note);
1314 			while (i != p.end() && (*i)->note() == val) {
1315 				n.insert (*i);
1316 			}
1317 			break;
1318 		case PitchLessThan:
1319 			i = p.upper_bound (search_note);
1320 			while (i != p.end() && (*i)->note() < val) {
1321 				n.insert (*i);
1322 			}
1323 			break;
1324 		case PitchLessThanOrEqual:
1325 			i = p.upper_bound (search_note);
1326 			while (i != p.end() && (*i)->note() <= val) {
1327 				n.insert (*i);
1328 			}
1329 			break;
1330 		case PitchGreater:
1331 			i = p.lower_bound (search_note);
1332 			while (i != p.end() && (*i)->note() > val) {
1333 				n.insert (*i);
1334 			}
1335 			break;
1336 		case PitchGreaterThanOrEqual:
1337 			i = p.lower_bound (search_note);
1338 			while (i != p.end() && (*i)->note() >= val) {
1339 				n.insert (*i);
1340 			}
1341 			break;
1342 
1343 		default:
1344 			//fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1345 			abort(); /* NOTREACHED*/
1346 		}
1347 	}
1348 }
1349 
1350 template<typename Time>
1351 void
get_notes_by_velocity(Notes & n,NoteOperator op,uint8_t val,int chan_mask) const1352 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1353 {
1354 	ReadLock lock (read_lock());
1355 
1356 	for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1357 
1358 		if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1359 			continue;
1360 		}
1361 
1362 		switch (op) {
1363 		case VelocityEqual:
1364 			if ((*i)->velocity() == val) {
1365 				n.insert (*i);
1366 			}
1367 			break;
1368 		case VelocityLessThan:
1369 			if ((*i)->velocity() < val) {
1370 				n.insert (*i);
1371 			}
1372 			break;
1373 		case VelocityLessThanOrEqual:
1374 			if ((*i)->velocity() <= val) {
1375 				n.insert (*i);
1376 			}
1377 			break;
1378 		case VelocityGreater:
1379 			if ((*i)->velocity() > val) {
1380 				n.insert (*i);
1381 			}
1382 			break;
1383 		case VelocityGreaterThanOrEqual:
1384 			if ((*i)->velocity() >= val) {
1385 				n.insert (*i);
1386 			}
1387 			break;
1388 		default:
1389 			// fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1390 			abort(); /* NOTREACHED*/
1391 
1392 		}
1393 	}
1394 }
1395 
1396 template<typename Time>
1397 void
set_overlap_pitch_resolution(OverlapPitchResolution opr)1398 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1399 {
1400 	_overlap_pitch_resolution = opr;
1401 
1402 	/* XXX todo: clean up existing overlaps in source data? */
1403 }
1404 
1405 template<typename Time>
1406 void
control_list_marked_dirty()1407 Sequence<Time>::control_list_marked_dirty ()
1408 {
1409 	set_edited (true);
1410 }
1411 
1412 template<typename Time>
1413 void
dump(ostream & str) const1414 Sequence<Time>::dump (ostream& str) const
1415 {
1416 	typename Sequence<Time>::const_iterator i;
1417 	str << "+++ dump\n";
1418 	for (i = begin(); i != end(); ++i) {
1419 		str << *i << endl;
1420 	}
1421 	str << "--- dump\n";
1422 }
1423 
1424 template class Sequence<Temporal::Beats>;
1425 
1426 } // namespace Evoral
1427