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