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