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