Revert previous ill-thought-out patch.
[ardour.git] / libs / evoral / src / Sequence.cpp
1 /* This file is part of Evoral.
2  * Copyright (C) 2008 Dave Robillard <http://drobilla.net>
3  * Copyright (C) 2000-2008 Paul Davis
4  *
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
8  * version.
9  *
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.
13  *
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
17  */
18
19 #include <algorithm>
20 #include <cmath>
21 #include <iostream>
22 #include <limits>
23 #include <stdexcept>
24 #include <stdint.h>
25 #include <cstdio>
26
27 #include "pbd/compose.h"
28
29 #include "evoral/Control.hpp"
30 #include "evoral/ControlList.hpp"
31 #include "evoral/ControlSet.hpp"
32 #include "evoral/EventSink.hpp"
33 #include "evoral/MIDIParameters.hpp"
34 #include "evoral/Sequence.hpp"
35 #include "evoral/TypeMap.hpp"
36 #include "evoral/midi_util.h"
37
38 using namespace std;
39 using namespace PBD;
40
41 /** Minimum time between MIDI outputs from a single interpolated controller,
42     expressed in beats.  This is to limit the rate at which MIDI messages
43     are generated.  It is only applied to interpolated controllers.
44
45     XXX: This is a hack.  The time should probably be expressed in
46     seconds rather than beats, and should be configurable etc. etc.
47 */
48 static double const time_between_interpolated_controller_outputs = 1.0 / 256;
49
50 namespace Evoral {
51
52 // Read iterator (const_iterator)
53
54 template<typename Time>
55 Sequence<Time>::const_iterator::const_iterator()
56         : _seq(NULL)
57         , _is_end(true)
58         , _control_iter(_control_iters.end())
59 {
60         _event = boost::shared_ptr< Event<Time> >(new Event<Time>());
61 }
62
63 /** @param force_discrete true to force ControlLists to use discrete evaluation, otherwise false to get them to use their configured mode */
64 template<typename Time>
65 Sequence<Time>::const_iterator::const_iterator(const Sequence<Time>& seq, Time t, bool force_discrete, std::set<Evoral::Parameter> const & filtered)
66         : _seq(&seq)
67         , _type(NIL)
68         , _is_end((t == DBL_MAX) || seq.empty())
69         , _note_iter(seq.notes().end())
70         , _sysex_iter(seq.sysexes().end())
71         , _control_iter(_control_iters.end())
72         , _force_discrete (force_discrete)
73 {
74         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Created Iterator @ %1 (is end: %2)\n)", t, _is_end));
75
76         if (!_is_end) {
77                 _lock = seq.read_lock();
78         } else {
79                 return;
80         }
81
82         typename Sequence<Time>::ReadLock lock(seq.read_lock());
83
84         // Find first note which begins at or after t
85         _note_iter = seq.note_lower_bound(t);
86
87         // Find first sysex event at or after t
88         for (typename Sequence<Time>::SysExes::const_iterator i = seq.sysexes().begin();
89                         i != seq.sysexes().end(); ++i) {
90                 if ((*i)->time() >= t) {
91                         _sysex_iter = i;
92                         break;
93                 }
94         }
95         assert(_sysex_iter == seq.sysexes().end() || (*_sysex_iter)->time() >= t);
96
97         // Find first control event after t
98         ControlIterator earliest_control(boost::shared_ptr<ControlList>(), DBL_MAX, 0.0);
99         _control_iters.reserve(seq._controls.size());
100         bool   found                  = false;
101         size_t earliest_control_index = 0;
102         for (Controls::const_iterator i = seq._controls.begin(); i != seq._controls.end(); ++i) {
103
104                 if (filtered.find (i->first) != filtered.end()) {
105                         /* this parameter is filtered, so don't bother setting up an iterator for it */
106                         continue;
107                 }
108                 
109                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: control: %1\n", seq._type_map.to_symbol(i->first)));
110                 double x, y;
111                 bool ret;
112                 if (_force_discrete) {
113                         ret = i->second->list()->rt_safe_earliest_event_discrete_unlocked (t, x, y, true);
114                 } else {
115                         ret = i->second->list()->rt_safe_earliest_event_unlocked(t, x, y, true);
116                 }
117                 if (!ret) {
118                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 (size %2) has no events past %3\n",
119                                                                       i->first.id(), i->second->list()->size(), t));
120                         continue;
121                 }
122
123                 assert(x >= 0);
124
125                 if (y < i->first.min() || y > i->first.max()) {
126                         cerr << "ERROR: Controller value " << y
127                                 << " out of range [" << i->first.min() << "," << i->first.max()
128                                 << "], event ignored" << endl;
129                         continue;
130                 }
131
132                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Iterator: CC %1 added (%2, %3)\n", i->first.id(), x, y));
133
134                 const ControlIterator new_iter(i->second->list(), x, y);
135                 _control_iters.push_back(new_iter);
136
137                 // Found a new earliest_control
138                 if (x < earliest_control.x) {
139                         earliest_control = new_iter;
140                         earliest_control_index = _control_iters.size() - 1;
141                         found = true;
142                 }
143         }
144
145         if (found) {
146                 _control_iter = _control_iters.begin() + earliest_control_index;
147                 assert(_control_iter != _control_iters.end());
148         } else {
149                 _control_iter = _control_iters.end();
150         }
151
152         // Now find the earliest event overall and point to it
153         Time earliest_t = t;
154
155         if (_note_iter != seq.notes().end()) {
156                 _type = NOTE_ON;
157                 earliest_t = (*_note_iter)->time();
158         }
159
160         if (_sysex_iter != seq.sysexes().end()
161                         && ((*_sysex_iter)->time() < earliest_t || _type == NIL)) {
162                 _type = SYSEX;
163                 earliest_t = (*_sysex_iter)->time();
164         }
165
166         if (_control_iter != _control_iters.end()
167                         && earliest_control.list && earliest_control.x >= t
168                         && (earliest_control.x < earliest_t || _type == NIL)) {
169                 _type = CONTROL;
170                 earliest_t = earliest_control.x;
171         }
172
173         switch (_type) {
174         case NOTE_ON:
175                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at note on event @ %1\n", earliest_t));
176                 _event = boost::shared_ptr<Event<Time> > (new Event<Time> ((*_note_iter)->on_event(), true));
177                 _active_notes.push(*_note_iter);
178                 break;
179         case SYSEX:
180                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at sysex event @ %1\n", earliest_t));
181                 _event = boost::shared_ptr< Event<Time> >(
182                                 new Event<Time>(*(*_sysex_iter), true));
183                 break;
184         case CONTROL:
185                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at control event @ %1\n", earliest_t));
186                 seq.control_to_midi_event(_event, earliest_control);
187                 break;
188         default:
189                 break;
190         }
191
192         if (_type == NIL || !_event || _event->size() == 0) {
193                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Starting at end @ %1\n", t));
194                 _type   = NIL;
195                 _is_end = true;
196         } else {
197                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("New iterator = 0x%x : 0x%x @ %f\n",
198                                                               (int)_event->event_type(),
199                                                               (int)((MIDIEvent<Time>*)_event.get())->type(),
200                                                               _event->time()));
201                 assert(midi_event_is_valid(_event->buffer(), _event->size()));
202         }
203 }
204
205 template<typename Time>
206 Sequence<Time>::const_iterator::~const_iterator()
207 {
208 }
209
210 template<typename Time>
211 void
212 Sequence<Time>::const_iterator::invalidate()
213 {
214         while (!_active_notes.empty()) {
215                 _active_notes.pop();
216         }
217         _type = NIL;
218         _is_end = true;
219         if (_seq) {
220                 _note_iter = _seq->notes().end();
221                 _sysex_iter = _seq->sysexes().end();
222         }
223         _control_iter = _control_iters.end();
224         _lock.reset();
225 }
226
227 template<typename Time>
228 const typename Sequence<Time>::const_iterator&
229 Sequence<Time>::const_iterator::operator++()
230 {
231         if (_is_end) {
232                 throw std::logic_error("Attempt to iterate past end of Sequence");
233         }
234
235         DEBUG_TRACE(DEBUG::Sequence, "Sequence::const_iterator++\n");
236         assert(_event && _event->buffer() && _event->size() > 0);
237
238         const MIDIEvent<Time>& ev = *((MIDIEvent<Time>*)_event.get());
239
240         if (!(     ev.is_note()
241                         || ev.is_cc()
242                         || ev.is_pgm_change()
243                         || ev.is_pitch_bender()
244                         || ev.is_channel_pressure()
245                         || ev.is_sysex()) ) {
246                 cerr << "WARNING: Unknown event (type " << _type << "): " << hex
247                         << int(ev.buffer()[0]) << int(ev.buffer()[1]) << int(ev.buffer()[2]) << endl;
248         }
249
250         double x   = 0.0;
251         double y   = 0.0;
252         bool   ret = false;
253
254         // Increment past current event
255         switch (_type) {
256         case NOTE_ON:
257                 ++_note_iter;
258                 break;
259         case NOTE_OFF:
260                 break;
261         case CONTROL:
262                 // Increment current controller iterator
263                 if (_force_discrete || _control_iter->list->interpolation() == ControlList::Discrete) {
264                         ret = _control_iter->list->rt_safe_earliest_event_discrete_unlocked (
265                                 _control_iter->x, x, y, false
266                                 );
267                 } else {
268                         ret = _control_iter->list->rt_safe_earliest_event_linear_unlocked (
269                                 _control_iter->x + time_between_interpolated_controller_outputs, x, y, false
270                                 );
271                 }
272                 assert(!ret || x > _control_iter->x);
273                 if (ret) {
274                         _control_iter->x = x;
275                         _control_iter->y = y;
276                 } else {
277                         _control_iter->list.reset();
278                         _control_iter->x = DBL_MAX;
279                         _control_iter->y = DBL_MAX;
280                 }
281
282                 // Find the controller with the next earliest event time
283                 _control_iter = _control_iters.begin();
284                 for (ControlIterators::iterator i = _control_iters.begin();
285                                 i != _control_iters.end(); ++i) {
286                         if (i->x < _control_iter->x) {
287                                 _control_iter = i;
288                         }
289                 }
290                 break;
291         case SYSEX:
292                 ++_sysex_iter;
293                 break;
294         default:
295                 assert(false);
296         }
297
298         // Now find the earliest event overall and point to it
299         _type = NIL;
300         Time earliest_t = std::numeric_limits<Time>::max();
301
302         // Next earliest note on
303         if (_note_iter != _seq->notes().end()) {
304                 _type = NOTE_ON;
305                 earliest_t = (*_note_iter)->time();
306         }
307
308         // Use the next note off iff it's earlier or the same time as the note on
309         if (!_seq->percussive() && (!_active_notes.empty())) {
310                 if (_type == NIL || _active_notes.top()->end_time() <= earliest_t) {
311                         _type = NOTE_OFF;
312                         earliest_t = _active_notes.top()->end_time();
313                 }
314         }
315
316         // Use the next earliest controller iff it's earlier than the note event
317         if (_control_iter != _control_iters.end() && _control_iter->x != DBL_MAX) {
318                 if (_type == NIL || _control_iter->x < earliest_t) {
319                         _type = CONTROL;
320                         earliest_t = _control_iter->x;
321                 }
322         }
323
324         // Use the next earliest SysEx iff it's earlier than the controller
325         if (_sysex_iter != _seq->sysexes().end()) {
326                 if (_type == NIL || (*_sysex_iter)->time() < earliest_t) {
327                         _type = SYSEX;
328                         earliest_t = (*_sysex_iter)->time();
329                 }
330         }
331
332         // Set event to reflect new position
333         switch (_type) {
334         case NOTE_ON:
335                 DEBUG_TRACE(DEBUG::Sequence, "iterator = note on\n");
336                 *_event = (*_note_iter)->on_event();
337                 _active_notes.push(*_note_iter);
338                 break;
339         case NOTE_OFF:
340                 DEBUG_TRACE(DEBUG::Sequence, "iterator = note off\n");
341                 assert(!_active_notes.empty());
342                 *_event = _active_notes.top()->off_event();
343                 _active_notes.pop();
344                 break;
345         case CONTROL:
346                 DEBUG_TRACE(DEBUG::Sequence, "iterator = control\n");
347                 _seq->control_to_midi_event(_event, *_control_iter);
348                 break;
349         case SYSEX:
350                 DEBUG_TRACE(DEBUG::Sequence, "iterator = sysex\n");
351                 *_event = *(*_sysex_iter);
352                 break;
353         default:
354                 DEBUG_TRACE(DEBUG::Sequence, "iterator = end\n");
355                 _is_end = true;
356         }
357
358         assert(_is_end || (_event->size() > 0 && _event->buffer() && _event->buffer()[0] != '\0'));
359
360         return *this;
361 }
362
363 template<typename Time>
364 bool
365 Sequence<Time>::const_iterator::operator==(const const_iterator& other) const
366 {
367         if (_seq != other._seq) {
368                 return false;
369         } else if (_is_end || other._is_end) {
370                 return (_is_end == other._is_end);
371         } else if (_type != other._type) {
372                 return false;
373         } else {
374                 return (_event == other._event);
375         }
376 }
377
378 template<typename Time>
379 typename Sequence<Time>::const_iterator&
380 Sequence<Time>::const_iterator::operator=(const const_iterator& other)
381 {
382         _seq           = other._seq;
383         _event         = other._event;
384         _active_notes  = other._active_notes;
385         _type          = other._type;
386         _is_end        = other._is_end;
387         _note_iter     = other._note_iter;
388         _sysex_iter    = other._sysex_iter;
389         _control_iters = other._control_iters;
390         _force_discrete = other._force_discrete;
391
392         if (other._lock)
393                 _lock = _seq->read_lock();
394         else
395                 _lock.reset();
396
397         if (other._control_iter == other._control_iters.end()) {
398                 _control_iter = _control_iters.end();
399         } else {
400                 const size_t index = other._control_iter - other._control_iters.begin();
401                 _control_iter  = _control_iters.begin() + index;
402         }
403
404         return *this;
405 }
406
407 // Sequence
408
409 template<typename Time>
410 Sequence<Time>::Sequence(const TypeMap& type_map)
411         : _edited(false)
412         , _overlapping_pitches_accepted (true)
413         , _overlap_pitch_resolution (FirstOnFirstOff)
414         , _writing(false)
415         , _type_map(type_map)
416         , _end_iter(*this, DBL_MAX, false, std::set<Evoral::Parameter> ())
417         , _percussive(false)
418         , _lowest_note(127)
419         , _highest_note(0)
420 {
421         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence constructed: %1\n", this));
422         assert(_end_iter._is_end);
423         assert( ! _end_iter._lock);
424 }
425
426 template<typename Time>
427 Sequence<Time>::Sequence(const Sequence<Time>& other)
428         : ControlSet (other)
429         , _edited(false)
430         , _overlapping_pitches_accepted (other._overlapping_pitches_accepted)
431         , _overlap_pitch_resolution (other._overlap_pitch_resolution)
432         , _writing(false)
433         , _type_map(other._type_map)
434         , _end_iter(*this, DBL_MAX, false, std::set<Evoral::Parameter> ())
435         , _percussive(other._percussive)
436         , _lowest_note(other._lowest_note)
437         , _highest_note(other._highest_note)
438 {
439         for (typename Notes::const_iterator i = other._notes.begin(); i != other._notes.end(); ++i) {
440                 NotePtr n (new Note<Time> (**i));
441                 _notes.insert (n);
442         }
443
444         for (typename SysExes::const_iterator i = other._sysexes.begin(); i != other._sysexes.end(); ++i) {
445                 boost::shared_ptr<Event<Time> > n (new Event<Time> (**i, true));
446                 _sysexes.push_back (n);
447         }
448
449         DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sequence copied: %1\n", this));
450         assert(_end_iter._is_end);
451         assert(! _end_iter._lock);
452 }
453
454 /** Write the controller event pointed to by \a iter to \a ev.
455  * The buffer of \a ev will be allocated or resized as necessary.
456  * The event_type of \a ev should be set to the expected output type.
457  * \return true on success
458  */
459 template<typename Time>
460 bool
461 Sequence<Time>::control_to_midi_event(
462                 boost::shared_ptr< Event<Time> >& ev,
463                 const ControlIterator&            iter) const
464 {
465         assert(iter.list.get());
466         const uint32_t event_type = iter.list->parameter().type();
467
468         // initialize the event pointer with a new event, if necessary
469         if (!ev) {
470                 ev = boost::shared_ptr< Event<Time> >(new Event<Time>(event_type, 0, 3, NULL, true));
471         }
472
473         uint8_t midi_type = _type_map.parameter_midi_type(iter.list->parameter());
474         ev->set_event_type(_type_map.midi_event_type(midi_type));
475         switch (midi_type) {
476         case MIDI_CMD_CONTROL:
477                 assert(iter.list.get());
478                 assert(iter.list->parameter().channel() < 16);
479                 assert(iter.list->parameter().id() <= INT8_MAX);
480                 assert(iter.y <= INT8_MAX);
481
482                 ev->time() = iter.x;
483                 ev->realloc(3);
484                 ev->buffer()[0] = MIDI_CMD_CONTROL + iter.list->parameter().channel();
485                 ev->buffer()[1] = (uint8_t)iter.list->parameter().id();
486                 ev->buffer()[2] = (uint8_t)iter.y;
487                 break;
488
489         case MIDI_CMD_PGM_CHANGE:
490                 assert(iter.list.get());
491                 assert(iter.list->parameter().channel() < 16);
492                 assert(iter.y <= INT8_MAX);
493
494                 ev->time() = iter.x;
495                 ev->realloc(2);
496                 ev->buffer()[0] = MIDI_CMD_PGM_CHANGE + iter.list->parameter().channel();
497                 ev->buffer()[1] = (uint8_t)iter.y;
498                 break;
499
500         case MIDI_CMD_BENDER:
501                 assert(iter.list.get());
502                 assert(iter.list->parameter().channel() < 16);
503                 assert(iter.y < (1<<14));
504
505                 ev->time() = iter.x;
506                 ev->realloc(3);
507                 ev->buffer()[0] = MIDI_CMD_BENDER + iter.list->parameter().channel();
508                 ev->buffer()[1] = uint16_t(iter.y) & 0x7F; // LSB
509                 ev->buffer()[2] = (uint16_t(iter.y) >> 7) & 0x7F; // MSB
510                 break;
511
512         case MIDI_CMD_CHANNEL_PRESSURE:
513                 assert(iter.list.get());
514                 assert(iter.list->parameter().channel() < 16);
515                 assert(iter.y <= INT8_MAX);
516
517                 ev->time() = iter.x;
518                 ev->realloc(2);
519                 ev->buffer()[0] = MIDI_CMD_CHANNEL_PRESSURE + iter.list->parameter().channel();
520                 ev->buffer()[1] = (uint8_t)iter.y;
521                 break;
522
523         default:
524                 return false;
525         }
526
527         return true;
528 }
529
530 /** Clear all events from the model.
531  */
532 template<typename Time>
533 void
534 Sequence<Time>::clear()
535 {
536         WriteLock lock(write_lock());
537         _notes.clear();
538         for (Controls::iterator li = _controls.begin(); li != _controls.end(); ++li)
539                 li->second->list()->clear();
540 }
541
542 /** Begin a write of events to the model.
543  *
544  * If \a mode is Sustained, complete notes with length are constructed as note
545  * on/off events are received.  Otherwise (Percussive), only note on events are
546  * stored; note off events are discarded entirely and all contained notes will
547  * have length 0.
548  */
549 template<typename Time>
550 void
551 Sequence<Time>::start_write()
552 {
553         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : start_write (percussive = %2)\n", this, _percussive));
554         WriteLock lock(write_lock());
555         _writing = true;
556         for (int i = 0; i < 16; ++i) {
557                 _write_notes[i].clear();
558         }
559 }
560
561 /** Finish a write of events to the model.
562  *
563  * If \a delete_stuck is true and the current mode is Sustained, note on events
564  * that were never resolved with a corresonding note off will be deleted.
565  * Otherwise they will remain as notes with length 0.
566  */
567 template<typename Time>
568 void
569 Sequence<Time>::end_write (bool delete_stuck)
570 {
571         WriteLock lock(write_lock());
572
573         if (!_writing) {
574                 return;
575         }
576
577         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 : end_write (%2 notes)\n", this, _notes.size()));
578
579         if (!_percussive && delete_stuck) {
580                 for (typename Notes::iterator n = _notes.begin(); n != _notes.end() ;) {
581                         typename Notes::iterator next = n;
582                         ++next;
583                         if ((*n)->length() == 0) {
584                                 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
585                                 _notes.erase(n);
586                         }
587                         
588                         n = next;
589                 }
590         }
591
592         for (int i = 0; i < 16; ++i) {
593                 if (!_write_notes[i].empty()) {
594                         cerr << "WARNING: Sequence<Time>::end_write: Channel " << i << " has "
595                                         << _write_notes[i].size() << " stuck notes" << endl;
596                 }
597                 _write_notes[i].clear();
598         }
599
600         _writing = false;
601 }
602
603
604 template<typename Time>
605 bool
606 Sequence<Time>::add_note_unlocked(const NotePtr note, void* arg)
607 {
608         /* This is the core method to add notes to a Sequence 
609          */
610
611         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 add note %2 @ %3\n", this, (int)note->note(), note->time()));
612
613         if (resolve_overlaps_unlocked (note, arg)) {
614                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 DISALLOWED: note %2 @ %3\n", this, (int)note->note(), note->time()));
615                 return false;
616         }
617
618         if (note->id() < 0) {
619                 note->set_id (Evoral::next_event_id());
620         } 
621
622         if (note->note() < _lowest_note)
623                 _lowest_note = note->note();
624         if (note->note() > _highest_note)
625                 _highest_note = note->note();
626
627         _notes.insert (note);
628         _pitches[note->channel()].insert (note);
629  
630         _edited = true;
631
632        return true;
633 }
634
635 template<typename Time>
636 void
637 Sequence<Time>::remove_note_unlocked(const constNotePtr note)
638 {
639         bool erased = false;
640
641         _edited = true;
642
643         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 remove note %2 @ %3\n", this, (int)note->note(), note->time()));
644
645         for (typename Sequence<Time>::Notes::iterator i = note_lower_bound(note->time()); 
646              i != _notes.end() && (*i)->time() == note->time(); ++i) {
647
648                 if (*i == note) {
649                         
650                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing note %2 @ %3\n", this, (int)(*i)->note(), (*i)->time()));
651                         _notes.erase (i);
652
653                         if ((*i)->note() == _lowest_note || (*i)->note() == _highest_note) {
654
655                                 _lowest_note = 127;
656                                 _highest_note = 0;
657
658                                 for (typename Sequence<Time>::Notes::iterator ii = _notes.begin(); ii != _notes.end(); ++ii) {
659                                         if ((*ii)->note() < _lowest_note)
660                                                 _lowest_note = (*ii)->note();
661                                         if ((*ii)->note() > _highest_note)
662                                                 _highest_note = (*ii)->note();
663                                 }
664                         }
665                         
666                         erased = true;
667                 }
668         }
669
670         Pitches& p (pitches (note->channel()));
671         
672         NotePtr search_note(new Note<Time>(0, 0, 0, note->note(), 0));
673
674         for (typename Pitches::iterator i = p.lower_bound (search_note); 
675              i != p.end() && (*i)->note() == note->note(); ++i) {
676                 if (*i == note) {
677                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1\terasing pitch %2 @ %3\n", this, (int)(*i)->note(), (*i)->time()));
678                         p.erase (i);
679                 }
680         }
681         
682         if (!erased) {
683                 cerr << "Unable to find note to erase" << endl;
684         }
685 }
686
687 /** Append \a ev to model.  NOT realtime safe.
688  *
689  * The timestamp of event is expected to be relative to
690  * the start of this model (t=0) and MUST be monotonically increasing
691  * and MUST be >= the latest event currently in the model.
692  */
693 template<typename Time>
694 void
695 Sequence<Time>::append(const Event<Time>& event, event_id_t evid)
696 {
697         WriteLock lock(write_lock());
698
699         const MIDIEvent<Time>& ev = (const MIDIEvent<Time>&)event;
700
701         assert(_notes.empty() || ev.time() >= (*_notes.rbegin())->time());
702         assert(_writing);
703
704         if (!midi_event_is_valid(ev.buffer(), ev.size())) {
705                 cerr << "WARNING: Sequence ignoring illegal MIDI event" << endl;
706                 return;
707         }
708
709         if (ev.is_note_on()) {
710                 NotePtr note(new Note<Time>(ev.channel(), ev.time(), 0, ev.note(), ev.velocity()));
711                 append_note_on_unlocked (note, evid);
712         } else if (ev.is_note_off()) {
713                 NotePtr note(new Note<Time>(ev.channel(), ev.time(), 0, ev.note(), ev.velocity()));
714                 /* XXX note: event ID is discarded because we merge the on+off events into
715                    a single note object
716                 */
717                 append_note_off_unlocked (note);
718         } else if (ev.is_sysex()) {
719                 append_sysex_unlocked(ev, evid);
720         } else if (ev.is_cc()) {
721                 append_control_unlocked(
722                         Evoral::MIDI::ContinuousController(ev.event_type(), ev.channel(), ev.cc_number()),
723                         ev.time(), ev.cc_value(), evid);
724         } else if (ev.is_pgm_change()) {
725                 append_control_unlocked(
726                         Evoral::MIDI::ProgramChange(ev.event_type(), ev.channel()),
727                         ev.time(), ev.pgm_number(), evid);
728         } else if (ev.is_pitch_bender()) {
729                 append_control_unlocked(
730                         Evoral::MIDI::PitchBender(ev.event_type(), ev.channel()),
731                         ev.time(), double ((0x7F & ev.pitch_bender_msb()) << 7
732                                            | (0x7F & ev.pitch_bender_lsb())),
733                         evid);
734         } else if (ev.is_channel_pressure()) {
735                 append_control_unlocked(
736                         Evoral::MIDI::ChannelPressure(ev.event_type(), ev.channel()),
737                         ev.time(), ev.channel_pressure(), evid);
738         } else if (!_type_map.type_is_midi(ev.event_type())) {
739                 printf("WARNING: Sequence: Unknown event type %X: ", ev.event_type());
740                 for (size_t i=0; i < ev.size(); ++i) {
741                         printf("%X ", ev.buffer()[i]);
742                 }
743                 printf("\n");
744         } else {
745                 printf("WARNING: Sequence: Unknown MIDI event type %X\n", ev.type());
746         }
747
748         _edited = true;
749 }
750
751 template<typename Time>
752 void
753 Sequence<Time>::append_note_on_unlocked (NotePtr note, event_id_t evid)
754 {
755         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n", this, 
756                                                       (int) note->channel(), (int) note->note(), 
757                                                       note->time(), (int) note->velocity()));
758         assert(note->note() <= 127);
759         assert(note->channel() < 16);
760         assert(_writing);
761
762         if (note->id() < 0) {
763                 note->set_id (evid);
764         }
765
766         if (note->velocity() == 0) {
767                 append_note_off_unlocked (note);
768                 return;
769         }
770
771         add_note_unlocked (note);
772         
773         if (!_percussive) {
774                 DEBUG_TRACE (DEBUG::Sequence, string_compose ("Sustained: Appending active note on %1 channel %2\n",
775                                                               (unsigned)(uint8_t)note->note(), note->channel()));
776                 _write_notes[note->channel()].insert (note);
777         } else {
778                 DEBUG_TRACE(DEBUG::Sequence, "Percussive: NOT appending active note on\n");
779         }
780 }
781
782 template<typename Time>
783 void
784 Sequence<Time>::append_note_off_unlocked (NotePtr note)
785 {
786         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 c=%2 note %3 on @ %4 v=%5\n",
787                                                       this, (int)note->channel(), 
788                                                       (int)note->note(), note->time(), (int)note->velocity()));
789         assert(note->note() <= 127);
790         assert(note->channel() < 16);
791         assert(_writing);
792         _edited = true;
793
794         if (_percussive) {
795                 DEBUG_TRACE(DEBUG::Sequence, "Sequence Ignoring note off (percussive mode)\n");
796                 return;
797         }
798
799         bool resolved = false;
800
801         /* _write_notes is sorted earliest-latest, so this will find the first matching note (FIFO) that
802            matches this note (by pitch & channel). the MIDI specification doesn't provide any guidance
803            whether to use FIFO or LIFO for this matching process, so SMF is fundamentally a lossy
804            format.
805         */
806
807         /* XXX use _overlap_pitch_resolution to determine FIFO/LIFO ... */
808
809         for (typename WriteNotes::iterator n = _write_notes[note->channel()].begin(); n != _write_notes[note->channel()].end(); ++n) {
810                 NotePtr nn = *n;
811                 if (note->note() == nn->note() && nn->channel() == note->channel()) {
812                         assert(note->time() >= nn->time());
813
814                         nn->set_length (note->time() - nn->time());
815                         nn->set_off_velocity (note->velocity());
816
817                         _write_notes[note->channel()].erase(n);
818                         DEBUG_TRACE (DEBUG::Sequence, string_compose ("resolved note, length: %1\n", note->length()));
819                         resolved = true;
820                         break;
821                 }
822         }
823
824         if (!resolved) {
825                 cerr << this << " spurious note off chan " << (int)note->channel()
826                      << ", note " << (int)note->note() << " @ " << note->time() << endl;
827         }
828 }
829
830 template<typename Time>
831 void
832 Sequence<Time>::append_control_unlocked(const Parameter& param, Time time, double value, event_id_t /* evid */)
833 {
834         DEBUG_TRACE (DEBUG::Sequence, string_compose ("%1 %2 @ %3\t=\t%4 # controls: %5\n",
835                                                       this, _type_map.to_symbol(param), time, value, _controls.size()));
836         boost::shared_ptr<Control> c = control(param, true);
837         c->list()->add (time, value);
838         /* XXX control events should use IDs */
839 }
840
841 template<typename Time>
842 void
843 Sequence<Time>::append_sysex_unlocked(const MIDIEvent<Time>& ev, event_id_t /* evid */)
844 {
845 #ifdef DEBUG_SEQUENCE
846         cerr << this << " SysEx @ " << ev.time() << " \t= \t [ " << hex;
847         for (size_t i=0; i < ev.size(); ++i) {
848                 cerr << int(ev.buffer()[i]) << " ";
849         } cerr << "]" << endl;
850 #endif
851
852         boost::shared_ptr<MIDIEvent<Time> > event(new MIDIEvent<Time>(ev, true));
853         /* XXX sysex events should use IDs */
854         _sysexes.push_back(event);
855 }
856
857 template<typename Time>
858 bool
859 Sequence<Time>::contains (const NotePtr& note) const
860 {
861         ReadLock lock (read_lock());
862         return contains_unlocked (note);
863 }
864
865 template<typename Time>
866 bool
867 Sequence<Time>::contains_unlocked (const NotePtr& note) const
868 {
869         const Pitches& p (pitches (note->channel()));
870         NotePtr search_note(new Note<Time>(0, 0, 0, note->note()));
871
872         for (typename Pitches::const_iterator i = p.lower_bound (search_note); 
873              i != p.end() && (*i)->note() == note->note(); ++i) {
874
875                 if (**i == *note) {
876                         return true;
877                 }
878         }
879
880         return false;
881 }
882
883 template<typename Time>
884 bool
885 Sequence<Time>::overlaps (const NotePtr& note, const NotePtr& without) const
886 {
887         ReadLock lock (read_lock());
888         return overlaps_unlocked (note, without);
889 }
890
891 template<typename Time>
892 bool
893 Sequence<Time>::overlaps_unlocked (const NotePtr& note, const NotePtr& without) const
894 {
895         Time sa = note->time();
896         Time ea  = note->end_time();
897          
898         const Pitches& p (pitches (note->channel()));
899         NotePtr search_note(new Note<Time>(0, 0, 0, note->note()));
900
901         for (typename Pitches::const_iterator i = p.lower_bound (search_note); 
902              i != p.end() && (*i)->note() == note->note(); ++i) {
903
904                 if (without && (**i) == *without) {
905                         continue;
906                 }
907
908                 Time sb = (*i)->time();
909                 Time eb = (*i)->end_time();
910
911                 if (((sb > sa) && (eb <= ea)) ||
912                     ((eb >= sa) && (eb <= ea)) ||
913                     ((sb > sa) && (sb <= ea)) ||
914                     ((sa >= sb) && (sa <= eb) && (ea <= eb))) {
915                         return true;
916                 }
917         }
918
919         return false;
920 }
921
922 template<typename Time>
923 void
924 Sequence<Time>::set_notes (const Sequence<Time>::Notes& n)
925 {
926         _notes = n;
927 }
928
929 /** Return the earliest note with time >= t */
930 template<typename Time>
931 typename Sequence<Time>::Notes::const_iterator
932 Sequence<Time>::note_lower_bound (Time t) const
933 {
934         NotePtr search_note(new Note<Time>(0, t, 0, 0, 0));
935         typename Sequence<Time>::Notes::const_iterator i = _notes.lower_bound(search_note);
936         assert(i == _notes.end() || (*i)->time() >= t);
937         return i;
938 }
939
940 template<typename Time>
941 void
942 Sequence<Time>::get_notes (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
943 {
944         switch (op) {
945         case PitchEqual:
946         case PitchLessThan:
947         case PitchLessThanOrEqual:
948         case PitchGreater:
949         case PitchGreaterThanOrEqual:
950                 get_notes_by_pitch (n, op, val, chan_mask);
951                 break;
952                 
953         case VelocityEqual:
954         case VelocityLessThan:
955         case VelocityLessThanOrEqual:
956         case VelocityGreater:
957         case VelocityGreaterThanOrEqual:
958                 get_notes_by_velocity (n, op, val, chan_mask);
959                 break;
960         }
961 }
962
963 template<typename Time>
964 void
965 Sequence<Time>::get_notes_by_pitch (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
966 {
967         for (uint8_t c = 0; c < 16; ++c) {
968
969                 if (chan_mask != 0 && !((1<<c) & chan_mask)) {
970                         continue;
971                 }
972
973                 const Pitches& p (pitches (c));
974                 NotePtr search_note(new Note<Time>(0, 0, 0, val, 0));
975                 typename Pitches::const_iterator i;
976                 switch (op) {
977                 case PitchEqual:
978                         i = p.lower_bound (search_note);
979                         while (i != p.end() && (*i)->note() == val) {
980                                 n.insert (*i);
981                         }
982                         break;
983                 case PitchLessThan:
984                         i = p.upper_bound (search_note);
985                         while (i != p.end() && (*i)->note() < val) {
986                                 n.insert (*i);
987                         }
988                         break;
989                 case PitchLessThanOrEqual:
990                         i = p.upper_bound (search_note);
991                         while (i != p.end() && (*i)->note() <= val) {
992                                 n.insert (*i);
993                         }
994                         break;
995                 case PitchGreater:
996                         i = p.lower_bound (search_note);
997                         while (i != p.end() && (*i)->note() > val) {
998                                 n.insert (*i);
999                         }
1000                         break;
1001                 case PitchGreaterThanOrEqual:
1002                         i = p.lower_bound (search_note);
1003                         while (i != p.end() && (*i)->note() >= val) {
1004                                 n.insert (*i);
1005                         }
1006                         break;
1007                         
1008                 default:
1009                         //fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_pitch() called with illegal operator"), op)) << endmsg;
1010                         abort ();
1011                         /* NOTREACHED*/
1012                 }
1013         }
1014 }
1015
1016 template<typename Time>
1017 void
1018 Sequence<Time>::get_notes_by_velocity (Notes& n, NoteOperator op, uint8_t val, int chan_mask) const
1019 {
1020         ReadLock lock (read_lock());
1021         
1022         for (typename Notes::const_iterator i = _notes.begin(); i != _notes.end(); ++i) {
1023
1024                 if (chan_mask != 0 && !((1<<((*i)->channel())) & chan_mask)) {
1025                         continue;
1026                 }
1027
1028                 switch (op) {
1029                 case VelocityEqual:
1030                         if ((*i)->velocity() == val) {
1031                                 n.insert (*i);
1032                         }
1033                         break;
1034                 case VelocityLessThan:
1035                         if ((*i)->velocity() < val) {
1036                                 n.insert (*i);
1037                         }
1038                         break;
1039                 case VelocityLessThanOrEqual:
1040                         if ((*i)->velocity() <= val) {
1041                                 n.insert (*i);
1042                         }
1043                         break;
1044                 case VelocityGreater:
1045                         if ((*i)->velocity() > val) {
1046                                 n.insert (*i);
1047                         }
1048                         break;
1049                 case VelocityGreaterThanOrEqual:
1050                         if ((*i)->velocity() >= val) {
1051                                 n.insert (*i);
1052                         }
1053                         break;
1054                 default:
1055                         // fatal << string_compose (_("programming error: %1 %2", X_("get_notes_by_velocity() called with illegal operator"), op)) << endmsg;
1056                         abort ();
1057                         /* NOTREACHED*/
1058
1059                 }
1060         }
1061 }
1062
1063 template<typename Time>
1064 void
1065 Sequence<Time>::set_overlap_pitch_resolution (OverlapPitchResolution opr)
1066 {
1067         _overlap_pitch_resolution = opr;
1068
1069         /* XXX todo: clean up existing overlaps in source data? */
1070 }
1071
1072 template<typename Time>
1073 void
1074 Sequence<Time>::control_list_marked_dirty ()
1075 {
1076         set_edited (true);
1077 }
1078
1079 template class Sequence<Evoral::MusicalTime>;
1080
1081 } // namespace Evoral
1082