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