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