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