* MIDI control lanes: Set Interpolationtype according to Parameter
[ardour.git] / libs / evoral / src / ControlList.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 #include <cmath>
20 #include <cassert>
21 #include <utility>
22 #include <iostream>
23 #include "evoral/ControlList.hpp"
24
25 using namespace std;
26
27 namespace Evoral {
28
29
30 inline bool event_time_less_than (ControlEvent* a, ControlEvent* b)
31 {
32         return a->when < b->when;
33 }
34
35
36 ControlList::ControlList (const Parameter& id)
37         : _parameter(id)
38         , _interpolation(Linear)
39         , _curve(new Curve(*this))
40 {       
41         _frozen = 0;
42         _changed_when_thawed = false;
43         _min_yval = id.min();
44         _max_yval = id.max();
45         _max_xval = 0; // means "no limit" 
46         _rt_insertion_point = _events.end();
47         _lookup_cache.left = -1;
48         _lookup_cache.range.first = _events.end();
49         _search_cache.left = -1;
50         _search_cache.range.first = _events.end();
51         _sort_pending = false;
52 }
53
54 ControlList::ControlList (const ControlList& other)
55         : _parameter(other._parameter)
56         , _interpolation(Linear)
57         , _curve(new Curve(*this))
58 {
59         _frozen = 0;
60         _changed_when_thawed = false;
61         _min_yval = other._min_yval;
62         _max_yval = other._max_yval;
63         _max_xval = other._max_xval;
64         _default_value = other._default_value;
65         _rt_insertion_point = _events.end();
66         _lookup_cache.range.first = _events.end();
67         _search_cache.range.first = _events.end();
68         _sort_pending = false;
69
70         for (const_iterator i = other._events.begin(); i != other._events.end(); ++i) {
71                 _events.push_back (new ControlEvent (**i));
72         }
73
74         mark_dirty ();
75 }
76
77 ControlList::ControlList (const ControlList& other, double start, double end)
78         : _parameter(other._parameter)
79         , _interpolation(Linear)
80         , _curve(new Curve(*this))
81 {
82         _frozen = 0;
83         _changed_when_thawed = false;
84         _min_yval = other._min_yval;
85         _max_yval = other._max_yval;
86         _max_xval = other._max_xval;
87         _default_value = other._default_value;
88         _rt_insertion_point = _events.end();
89         _lookup_cache.range.first = _events.end();
90         _search_cache.range.first = _events.end();
91         _sort_pending = false;
92
93         /* now grab the relevant points, and shift them back if necessary */
94
95         boost::shared_ptr<ControlList> section = const_cast<ControlList*>(&other)->copy (start, end);
96
97         if (!section->empty()) {
98                 for (iterator i = section->begin(); i != section->end(); ++i) {
99                         _events.push_back (new ControlEvent ((*i)->when, (*i)->value));
100                 }
101         }
102
103         mark_dirty ();
104 }
105
106 ControlList::~ControlList()
107 {
108         for (EventList::iterator x = _events.begin(); x != _events.end(); ++x) {
109                 delete (*x);
110         }
111 }
112
113 boost::shared_ptr<ControlList>
114 ControlList::create(Parameter id)
115 {
116         return boost::shared_ptr<ControlList>(new ControlList(id));
117 }
118
119 bool
120 ControlList::operator== (const ControlList& other)
121 {
122         return _events == other._events;
123 }
124
125 ControlList&
126 ControlList::operator= (const ControlList& other)
127 {
128         if (this != &other) {
129                 
130                 _events.clear ();
131                 
132                 for (const_iterator i = other._events.begin(); i != other._events.end(); ++i) {
133                         _events.push_back (new ControlEvent (**i));
134                 }
135                 
136                 _min_yval = other._min_yval;
137                 _max_yval = other._max_yval;
138                 _max_xval = other._max_xval;
139                 _default_value = other._default_value;
140                 
141                 mark_dirty ();
142                 maybe_signal_changed ();
143         }
144
145         return *this;
146 }
147
148 void
149 ControlList::maybe_signal_changed ()
150 {
151         mark_dirty ();
152         
153         if (_frozen)
154                 _changed_when_thawed = true;
155 }
156
157 void
158 ControlList::clear ()
159 {
160         {
161                 Glib::Mutex::Lock lm (_lock);
162                 _events.clear ();
163                 mark_dirty ();
164         }
165
166         maybe_signal_changed ();
167 }
168
169 void
170 ControlList::x_scale (double factor)
171 {
172         Glib::Mutex::Lock lm (_lock);
173         _x_scale (factor);
174 }
175
176 bool
177 ControlList::extend_to (double when)
178 {
179         Glib::Mutex::Lock lm (_lock);
180         if (_events.empty() || _events.back()->when == when) {
181                 return false;
182         }
183         double factor = when / _events.back()->when;
184         _x_scale (factor);
185         return true;
186 }
187
188 void ControlList::_x_scale (double factor)
189 {
190         for (iterator i = _events.begin(); i != _events.end(); ++i) {
191                 (*i)->when = floor ((*i)->when * factor);
192         }
193
194         mark_dirty ();
195 }
196
197 void
198 ControlList::reposition_for_rt_add (double when)
199 {
200         _rt_insertion_point = _events.end();
201 }
202
203 void
204 ControlList::rt_add (double when, double value)
205 {
206         //cerr << "RT: alist " << this << " add " << value << " @ " << when << endl;
207
208         {
209                 Glib::Mutex::Lock lm (_lock);
210
211                 iterator where;
212                 ControlEvent cp (when, 0.0);
213                 bool done = false;
214
215                 if ((_rt_insertion_point != _events.end()) && ((*_rt_insertion_point)->when < when) ) {
216
217                         /* we have a previous insertion point, so we should delete
218                            everything between it and the position where we are going
219                            to insert this point.
220                         */
221
222                         iterator after = _rt_insertion_point;
223
224                         if (++after != _events.end()) {
225                                 iterator far = after;
226
227                                 while (far != _events.end()) {
228                                         if ((*far)->when > when) {
229                                                 break;
230                                         }
231                                         ++far;
232                                 }
233
234                                 if (_new_value) {
235                                         where = far;
236                                         _rt_insertion_point = where;
237
238                                         if ((*where)->when == when) {
239                                                 (*where)->value = value;
240                                                 done = true;
241                                         }
242                                 } else {
243                                         where = _events.erase (after, far);
244                                 }
245
246                         } else {
247
248                                 where = after;
249
250                         }
251                         
252                         iterator previous = _rt_insertion_point;
253                         --previous;
254                         
255                         if (_rt_insertion_point != _events.begin() && (*_rt_insertion_point)->value == value && (*previous)->value == value) {
256                                 (*_rt_insertion_point)->when = when;
257                                 done = true;
258                                 
259                         }
260                         
261                 } else {
262
263                         where = lower_bound (_events.begin(), _events.end(), &cp, time_comparator);
264
265                         if (where != _events.end()) {
266                                 if ((*where)->when == when) {
267                                         (*where)->value = value;
268                                         done = true;
269                                 }
270                         }
271                 }
272
273                 if (!done) {
274                         _rt_insertion_point = _events.insert (where, new ControlEvent (when, value));
275                 }
276                 
277                 _new_value = false;
278                 mark_dirty ();
279         }
280
281         maybe_signal_changed ();
282 }
283
284 void
285 ControlList::fast_simple_add (double when, double value)
286 {
287         /* to be used only for loading pre-sorted data from saved state */
288         _events.insert (_events.end(), new ControlEvent (when, value));
289         assert(_events.back());
290 }
291
292 void
293 ControlList::add (double when, double value)
294 {
295         /* this is for graphical editing */
296
297         {
298                 Glib::Mutex::Lock lm (_lock);
299                 ControlEvent cp (when, 0.0f);
300                 bool insert = true;
301                 iterator insertion_point;
302
303                 for (insertion_point = lower_bound (_events.begin(), _events.end(), &cp, time_comparator); insertion_point != _events.end(); ++insertion_point) {
304
305                         /* only one point allowed per time point */
306
307                         if ((*insertion_point)->when == when) {
308                                 (*insertion_point)->value = value;
309                                 insert = false;
310                                 break;
311                         } 
312
313                         if ((*insertion_point)->when >= when) {
314                                 break;
315                         }
316                 }
317
318                 if (insert) {
319                         
320                         _events.insert (insertion_point, new ControlEvent (when, value));
321                         reposition_for_rt_add (0);
322
323                 } 
324
325                 mark_dirty ();
326         }
327
328         maybe_signal_changed ();
329 }
330
331 void
332 ControlList::erase (iterator i)
333 {
334         {
335                 Glib::Mutex::Lock lm (_lock);
336                 _events.erase (i);
337                 reposition_for_rt_add (0);
338                 mark_dirty ();
339         }
340         maybe_signal_changed ();
341 }
342
343 void
344 ControlList::erase (iterator start, iterator end)
345 {
346         {
347                 Glib::Mutex::Lock lm (_lock);
348                 _events.erase (start, end);
349                 reposition_for_rt_add (0);
350                 mark_dirty ();
351         }
352         maybe_signal_changed ();
353 }       
354
355 void
356 ControlList::reset_range (double start, double endt)
357 {
358         bool reset = false;
359
360         {
361         Glib::Mutex::Lock lm (_lock);
362                 ControlEvent cp (start, 0.0f);
363                 iterator s;
364                 iterator e;
365                 
366                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) != _events.end()) {
367
368                         cp.when = endt;
369                         e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
370
371                         for (iterator i = s; i != e; ++i) {
372                                 (*i)->value = _default_value;
373                         }
374                         
375                         reset = true;
376
377                         mark_dirty ();
378                 }
379         }
380
381         if (reset) {
382                 maybe_signal_changed ();
383         }
384 }
385
386 void
387 ControlList::erase_range (double start, double endt)
388 {
389         bool erased = false;
390
391         {
392                 Glib::Mutex::Lock lm (_lock);
393                 erased = erase_range_internal (start, endt, _events);
394
395                 if (erased) {
396                         reposition_for_rt_add (0);
397                         mark_dirty ();
398                 }
399                 
400         }
401
402         if (erased) {
403                 maybe_signal_changed ();
404         }
405 }
406
407 bool
408 ControlList::erase_range_internal (double start, double endt, EventList & events)
409 {
410         bool erased = false;
411         ControlEvent cp (start, 0.0f);
412         iterator s;
413         iterator e;
414
415         if ((s = lower_bound (events.begin(), events.end(), &cp, time_comparator)) != events.end()) {
416                 cp.when = endt;
417                 e = upper_bound (events.begin(), events.end(), &cp, time_comparator);
418                 events.erase (s, e);
419                 erased = true;
420         }
421
422         return erased;
423 }
424
425 void
426 ControlList::slide (iterator before, double distance)
427 {
428         {
429                 Glib::Mutex::Lock lm (_lock);
430
431                 if (before == _events.end()) {
432                         return;
433                 }
434                 
435                 while (before != _events.end()) {
436                         (*before)->when += distance;
437                         ++before;
438                 }
439         }
440
441         maybe_signal_changed ();
442 }
443
444 void
445 ControlList::modify (iterator iter, double when, double val)
446 {
447         /* note: we assume higher level logic is in place to avoid this
448            reordering the time-order of control events in the list. ie. all
449            points after *iter are later than when.
450         */
451
452         {
453                 Glib::Mutex::Lock lm (_lock);
454
455                 (*iter)->when = when;
456                 (*iter)->value = val;
457
458                 if (isnan (val)) {
459                         abort ();
460                 }
461
462                 if (!_frozen) {
463                         _events.sort (event_time_less_than);
464                 } else {
465                         _sort_pending = true;
466                 }
467
468                 mark_dirty ();
469         }
470
471         maybe_signal_changed ();
472 }
473
474 std::pair<ControlList::iterator,ControlList::iterator>
475 ControlList::control_points_adjacent (double xval)
476 {
477         Glib::Mutex::Lock lm (_lock);
478         iterator i;
479         ControlEvent cp (xval, 0.0f);
480         std::pair<iterator,iterator> ret;
481
482         ret.first = _events.end();
483         ret.second = _events.end();
484
485         for (i = lower_bound (_events.begin(), _events.end(), &cp, time_comparator); i != _events.end(); ++i) {
486                 
487                 if (ret.first == _events.end()) {
488                         if ((*i)->when >= xval) {
489                                 if (i != _events.begin()) {
490                                         ret.first = i;
491                                         --ret.first;
492                                 } else {
493                                         return ret;
494                                 }
495                         }
496                 } 
497                 
498                 if ((*i)->when > xval) {
499                         ret.second = i;
500                         break;
501                 }
502         }
503
504         return ret;
505 }
506
507 void
508 ControlList::set_max_xval (double x)
509 {
510         _max_xval = x;
511 }
512
513 void
514 ControlList::freeze ()
515 {
516         _frozen++;
517 }
518
519 void
520 ControlList::thaw ()
521 {
522         assert(_frozen > 0);
523
524         if (--_frozen > 0) {
525                 return;
526         }
527
528         {
529                 Glib::Mutex::Lock lm (_lock);
530
531                 if (_sort_pending) {
532                         _events.sort (event_time_less_than);
533                         _sort_pending = false;
534                 }
535         }
536 }
537
538 void 
539 ControlList::mark_dirty () const
540 {
541         _lookup_cache.left = -1;
542         _search_cache.left = -1;
543         if (_curve)
544                 _curve->mark_dirty();
545 }
546
547 void
548 ControlList::truncate_end (double last_coordinate)
549 {
550         {
551                 Glib::Mutex::Lock lm (_lock);
552                 ControlEvent cp (last_coordinate, 0);
553                 ControlList::reverse_iterator i;
554                 double last_val;
555
556                 if (_events.empty()) {
557                         return;
558                 }
559
560                 if (last_coordinate == _events.back()->when) {
561                         return;
562                 }
563
564                 if (last_coordinate > _events.back()->when) {
565                         
566                         /* extending end:
567                         */
568
569                         iterator foo = _events.begin();
570                         bool lessthantwo;
571
572                         if (foo == _events.end()) {
573                                 lessthantwo = true;
574                         } else if (++foo == _events.end()) {
575                                 lessthantwo = true;
576                         } else {
577                                 lessthantwo = false;
578                         }
579
580                         if (lessthantwo) {
581                                 /* less than 2 points: add a new point */
582                                 _events.push_back (new ControlEvent (last_coordinate, _events.back()->value));
583                         } else {
584
585                                 /* more than 2 points: check to see if the last 2 values
586                                    are equal. if so, just move the position of the
587                                    last point. otherwise, add a new point.
588                                 */
589
590                                 iterator penultimate = _events.end();
591                                 --penultimate; /* points at last point */
592                                 --penultimate; /* points at the penultimate point */
593                                 
594                                 if (_events.back()->value == (*penultimate)->value) {
595                                         _events.back()->when = last_coordinate;
596                                 } else {
597                                         _events.push_back (new ControlEvent (last_coordinate, _events.back()->value));
598                                 }
599                         }
600
601                 } else {
602
603                         /* shortening end */
604
605                         last_val = unlocked_eval (last_coordinate);
606                         last_val = max ((double) _min_yval, last_val);
607                         last_val = min ((double) _max_yval, last_val);
608                         
609                         i = _events.rbegin();
610                         
611                         /* make i point to the last control point */
612                         
613                         ++i;
614                         
615                         /* now go backwards, removing control points that are
616                            beyond the new last coordinate.
617                         */
618
619                         // FIXME: SLOW! (size() == O(n))
620
621                         uint32_t sz = _events.size();
622                         
623                         while (i != _events.rend() && sz > 2) {
624                                 ControlList::reverse_iterator tmp;
625                                 
626                                 tmp = i;
627                                 ++tmp;
628                                 
629                                 if ((*i)->when < last_coordinate) {
630                                         break;
631                                 }
632                                 
633                                 _events.erase (i.base());
634                                 --sz;
635
636                                 i = tmp;
637                         }
638                         
639                         _events.back()->when = last_coordinate;
640                         _events.back()->value = last_val;
641                 }
642
643                 reposition_for_rt_add (0);
644                 mark_dirty();
645         }
646
647         maybe_signal_changed ();
648 }
649
650 void
651 ControlList::truncate_start (double overall_length)
652 {
653         {
654                 Glib::Mutex::Lock lm (_lock);
655                 iterator i;
656                 double first_legal_value;
657                 double first_legal_coordinate;
658
659                 assert(!_events.empty());
660                 
661                 if (overall_length == _events.back()->when) {
662                         /* no change in overall length */
663                         return;
664                 }
665                 
666                 if (overall_length > _events.back()->when) {
667                         
668                         /* growing at front: duplicate first point. shift all others */
669
670                         double shift = overall_length - _events.back()->when;
671                         uint32_t np;
672
673                         for (np = 0, i = _events.begin(); i != _events.end(); ++i, ++np) {
674                                 (*i)->when += shift;
675                         }
676
677                         if (np < 2) {
678
679                                 /* less than 2 points: add a new point */
680                                 _events.push_front (new ControlEvent (0, _events.front()->value));
681
682                         } else {
683
684                                 /* more than 2 points: check to see if the first 2 values
685                                    are equal. if so, just move the position of the
686                                    first point. otherwise, add a new point.
687                                 */
688
689                                 iterator second = _events.begin();
690                                 ++second; /* points at the second point */
691                                 
692                                 if (_events.front()->value == (*second)->value) {
693                                         /* first segment is flat, just move start point back to zero */
694                                         _events.front()->when = 0;
695                                 } else {
696                                         /* leave non-flat segment in place, add a new leading point. */
697                                         _events.push_front (new ControlEvent (0, _events.front()->value));
698                                 }
699                         }
700
701                 } else {
702
703                         /* shrinking at front */
704                         
705                         first_legal_coordinate = _events.back()->when - overall_length;
706                         first_legal_value = unlocked_eval (first_legal_coordinate);
707                         first_legal_value = max (_min_yval, first_legal_value);
708                         first_legal_value = min (_max_yval, first_legal_value);
709
710                         /* remove all events earlier than the new "front" */
711
712                         i = _events.begin();
713                         
714                         while (i != _events.end() && !_events.empty()) {
715                                 ControlList::iterator tmp;
716                                 
717                                 tmp = i;
718                                 ++tmp;
719                                 
720                                 if ((*i)->when > first_legal_coordinate) {
721                                         break;
722                                 }
723                                 
724                                 _events.erase (i);
725                                 
726                                 i = tmp;
727                         }
728                         
729
730                         /* shift all remaining points left to keep their same
731                            relative position
732                         */
733                         
734                         for (i = _events.begin(); i != _events.end(); ++i) {
735                                 (*i)->when -= first_legal_coordinate;
736                         }
737
738                         /* add a new point for the interpolated new value */
739                         
740                         _events.push_front (new ControlEvent (0, first_legal_value));
741                 }           
742
743                 reposition_for_rt_add (0);
744
745                 mark_dirty();
746         }
747
748         maybe_signal_changed ();
749 }
750
751 double
752 ControlList::unlocked_eval (double x) const
753 {
754         pair<EventList::iterator,EventList::iterator> range;
755         int32_t npoints;
756         double lpos, upos;
757         double lval, uval;
758         double fraction;
759
760         const_iterator length_check_iter = _events.begin();
761         for (npoints = 0; npoints < 4; ++npoints, ++length_check_iter)
762                 if (length_check_iter == _events.end())
763                         break;
764
765         switch (npoints) {
766         case 0:
767                 return _default_value;
768
769         case 1:
770                 if (x >= _events.front()->when) {
771                         return _events.front()->value;
772                 } else {
773                         // hansfbaier: v--------- Why commented ??? 
774                         // return _default_value;
775                         return _events.front()->value;
776                 } 
777                 
778         case 2:
779                 if (x >= _events.back()->when) {
780                         return _events.back()->value;
781                 } else if (x == _events.front()->when) {
782                         return _events.front()->value;
783                 } else if (x < _events.front()->when) {
784                         // hansfbaier: v--------- Why commented ??? 
785                         // return _default_value;
786                         return _events.front()->value;
787                 }
788
789                 lpos = _events.front()->when;
790                 lval = _events.front()->value;
791                 upos = _events.back()->when;
792                 uval = _events.back()->value;
793                 
794                 if (_interpolation == Discrete) {
795                         return lval;
796                 }
797
798                 /* linear interpolation betweeen the two points
799                 */
800
801                 fraction = (double) (x - lpos) / (double) (upos - lpos);
802                 return lval + (fraction * (uval - lval));
803
804         default:
805
806                 if (x >= _events.back()->when) {
807                         return _events.back()->value;
808                 } else if (x == _events.front()->when) {
809                         return _events.front()->value;
810                 } else if (x < _events.front()->when) {
811                         // hansfbaier: v--------- Why commented ??? 
812                         // return _default_value;
813                         return _events.front()->value;
814                 }
815
816                 return multipoint_eval (x);
817                 break;
818         }
819
820         /*NOTREACHED*/ /* stupid gcc */
821         return 0.0;
822 }
823
824 double
825 ControlList::multipoint_eval (double x) const
826 {
827         double upos, lpos;
828         double uval, lval;
829         double fraction;
830         
831         /* "Stepped" lookup (no interpolation) */
832         /* FIXME: no cache.  significant? */
833         if (_interpolation == Discrete) {
834                 const ControlEvent cp (x, 0);
835                 EventList::const_iterator i = lower_bound (_events.begin(), _events.end(), &cp, time_comparator);
836
837                 // shouldn't have made it to multipoint_eval
838                 assert(i != _events.end());
839
840                 if (i == _events.begin() || (*i)->when == x)
841                         return (*i)->value;
842                 else
843                         return (*(--i))->value;
844         }
845
846         /* Only do the range lookup if x is in a different range than last time
847          * this was called (or if the lookup cache has been marked "dirty" (left<0) */
848         if ((_lookup_cache.left < 0) ||
849             ((_lookup_cache.left > x) || 
850              (_lookup_cache.range.first == _events.end()) || 
851              ((*_lookup_cache.range.second)->when < x))) {
852
853                 const ControlEvent cp (x, 0);
854                 
855                 _lookup_cache.range = equal_range (_events.begin(), _events.end(), &cp, time_comparator);
856         }
857         
858         pair<const_iterator,const_iterator> range = _lookup_cache.range;
859
860         if (range.first == range.second) {
861
862                 /* x does not exist within the list as a control point */
863
864                 _lookup_cache.left = x;
865
866                 if (range.first != _events.begin()) {
867                         --range.first;
868                         lpos = (*range.first)->when;
869                         lval = (*range.first)->value;
870                 }  else {
871                         /* we're before the first point */
872                         // return _default_value;
873                         return _events.front()->value;
874                 }
875                 
876                 if (range.second == _events.end()) {
877                         /* we're after the last point */
878                         return _events.back()->value;
879                 }
880
881                 upos = (*range.second)->when;
882                 uval = (*range.second)->value;
883                 
884                 /* linear interpolation betweeen the two points
885                    on either side of x
886                 */
887
888                 fraction = (double) (x - lpos) / (double) (upos - lpos);
889                 return lval + (fraction * (uval - lval));
890
891         } 
892
893         /* x is a control point in the data */
894         _lookup_cache.left = -1;
895         return (*range.first)->value;
896 }
897
898 void
899 ControlList::build_search_cache_if_necessary(double start, double end) const
900 {
901         /* Only do the range lookup if x is in a different range than last time
902          * this was called (or if the search cache has been marked "dirty" (left<0) */
903         if (!_events.empty() && ((_search_cache.left < 0) ||
904                         ((_search_cache.left > start) ||
905                          (_search_cache.right < end)))) {
906
907                 const ControlEvent start_point (start, 0);
908                 const ControlEvent end_point (end, 0);
909
910                 //cerr << "REBUILD: (" << _search_cache.left << ".." << _search_cache.right << ") := ("
911                 //      << start << ".." << end << ")" << endl;
912
913                 _search_cache.range.first = lower_bound (_events.begin(), _events.end(), &start_point, time_comparator);
914                 _search_cache.range.second = upper_bound (_events.begin(), _events.end(), &end_point, time_comparator);
915
916                 _search_cache.left = start;
917                 _search_cache.right = end;
918         }
919 }
920
921 /** Get the earliest event between \a start and \a end, using the current interpolation style.
922  *
923  * If an event is found, \a x and \a y are set to its coordinates.
924  *
925  * \param inclusive Include events with timestamp exactly equal to \a start
926  * \return true if event is found (and \a x and \a y are valid).
927  */
928 bool
929 ControlList::rt_safe_earliest_event(double start, double end, double& x, double& y, bool inclusive) const
930 {
931         // FIXME: It would be nice if this was unnecessary..
932         Glib::Mutex::Lock lm(_lock, Glib::TRY_LOCK);
933         if (!lm.locked()) {
934                 return false;
935         }
936
937         return rt_safe_earliest_event_unlocked(start, end, x, y, inclusive);
938
939
940
941 /** Get the earliest event between \a start and \a end, using the current interpolation style.
942  *
943  * If an event is found, \a x and \a y are set to its coordinates.
944  *
945  * \param inclusive Include events with timestamp exactly equal to \a start
946  * \return true if event is found (and \a x and \a y are valid).
947  */
948 bool
949 ControlList::rt_safe_earliest_event_unlocked(double start, double end, double& x, double& y, bool inclusive) const
950 {
951         if (_interpolation == Discrete)
952                 return rt_safe_earliest_event_discrete_unlocked(start, end, x, y, inclusive);
953         else
954                 return rt_safe_earliest_event_linear_unlocked(start, end, x, y, inclusive);
955
956
957
958 /** Get the earliest event between \a start and \a end (Discrete (lack of) interpolation)
959  *
960  * If an event is found, \a x and \a y are set to its coordinates.
961  *
962  * \param inclusive Include events with timestamp exactly equal to \a start
963  * \return true if event is found (and \a x and \a y are valid).
964  */
965 bool
966 ControlList::rt_safe_earliest_event_discrete_unlocked (double start, double end, double& x, double& y, bool inclusive) const
967 {
968         build_search_cache_if_necessary(start, end);
969
970         const pair<const_iterator,const_iterator>& range = _search_cache.range;
971
972         if (range.first != _events.end()) {
973                 const ControlEvent* const first = *range.first;
974
975                 const bool past_start = (inclusive ? first->when >= start : first->when > start);
976
977                 /* Earliest points is in range, return it */
978                 if (past_start >= start && first->when < end) {
979
980                         x = first->when;
981                         y = first->value;
982
983                         /* Move left of cache to this point
984                          * (Optimize for immediate call this cycle within range) */
985                         _search_cache.left = x;
986                         ++_search_cache.range.first;
987
988                         assert(x >= start);
989                         assert(x < end);
990                         cerr << "returned something" << endl;
991                         return true;
992
993                 } else {
994                         cerr << "not between start and end" << endl;
995                         return false;
996                 }
997         
998         /* No points in range */
999         } else {
1000                 cerr << "no points in range" << endl;
1001                 return false;
1002         }
1003 }
1004
1005 /** Get the earliest time the line crosses an integer (Linear interpolation).
1006  *
1007  * If an event is found, \a x and \a y are set to its coordinates.
1008  *
1009  * \param inclusive Include events with timestamp exactly equal to \a start
1010  * \return true if event is found (and \a x and \a y are valid).
1011  */
1012 bool
1013 ControlList::rt_safe_earliest_event_linear_unlocked (double start, double end, double& x, double& y, bool inclusive) const
1014 {
1015         //cerr << "earliest_event(" << start << ", " << end << ", " << x << ", " << y << ", " << inclusive << endl;
1016
1017         const_iterator length_check_iter = _events.begin();
1018         if (_events.empty()) // 0 events
1019                 return false;
1020         else if (_events.end() == ++length_check_iter) // 1 event
1021                 return rt_safe_earliest_event_discrete_unlocked(start, end, x, y, inclusive);
1022
1023         // Hack to avoid infinitely repeating the same event
1024         build_search_cache_if_necessary(start, end);
1025         
1026         pair<const_iterator,const_iterator> range = _search_cache.range;
1027
1028         if (range.first != _events.end()) {
1029
1030                 const ControlEvent* first = NULL;
1031                 const ControlEvent* next = NULL;
1032
1033                 /* No events past start (maybe?) */
1034                 if (next && next->when < start)
1035                         return false;
1036
1037                 /* Step is after first */
1038                 if (range.first == _events.begin() || (*range.first)->when == start) {
1039                         first = *range.first;
1040                         next = *(++range.first);
1041                         ++_search_cache.range.first;
1042
1043                 /* Step is before first */
1044                 } else {
1045                         const_iterator prev = range.first;
1046                         --prev;
1047                         first = *prev;
1048                         next = *range.first;
1049                 }
1050                 
1051                 if (inclusive && first->when == start) {
1052                         x = first->when;
1053                         y = first->value;
1054                         /* Move left of cache to this point
1055                          * (Optimize for immediate call this cycle within range) */
1056                         _search_cache.left = x;
1057                         //++_search_cache.range.first;
1058                         assert(inclusive ? x >= start : x > start);
1059                         return true;
1060                 }
1061                         
1062                 if (fabs(first->value - next->value) <= 1) {
1063                         if (next->when <= end && (!inclusive || next->when > start)) {
1064                                 x = next->when;
1065                                 y = next->value;
1066                                 /* Move left of cache to this point
1067                                  * (Optimize for immediate call this cycle within range) */
1068                                 _search_cache.left = x;
1069                                 //++_search_cache.range.first;
1070                                 assert(inclusive ? x >= start : x > start);
1071                                 return true;
1072                         } else {
1073                                 return false;
1074                         }
1075                 }
1076
1077                 const double slope = (next->value - first->value) / (double)(next->when - first->when);
1078                 //cerr << "start y: " << start_y << endl;
1079
1080                 //y = first->value + (slope * fabs(start - first->when));
1081                 y = first->value;
1082
1083                 if (first->value < next->value) // ramping up
1084                         y = ceil(y);
1085                 else // ramping down
1086                         y = floor(y);
1087
1088                 x = first->when + (y - first->value) / (double)slope;
1089                 
1090                 while ((inclusive && x < start) || (x <= start && y != next->value)) {
1091                         
1092                         if (first->value < next->value) // ramping up
1093                                 y += 1.0;
1094                         else // ramping down
1095                                 y -= 1.0;
1096
1097                         x = first->when + (y - first->value) / (double)slope;
1098                 }
1099
1100                 /*cerr << first->value << " @ " << first->when << " ... "
1101                                 << next->value << " @ " << next->when
1102                                 << " = " << y << " @ " << x << endl;*/
1103
1104                 assert(    (y >= first->value && y <= next->value)
1105                                 || (y <= first->value && y >= next->value) );
1106
1107                 
1108                 const bool past_start = (inclusive ? x >= start : x > start);
1109                 if (past_start && x < end) {
1110                         /* Move left of cache to this point
1111                          * (Optimize for immediate call this cycle within range) */
1112                         _search_cache.left = x;
1113                         assert(inclusive ? x >= start : x > start);
1114                         return true;
1115                 } else {
1116                         return false;
1117                 }
1118         
1119         /* No points in the future, so no steps (towards them) in the future */
1120         } else {
1121                 return false;
1122         }
1123 }
1124
1125 boost::shared_ptr<ControlList>
1126 ControlList::cut (iterator start, iterator end)
1127 {
1128         boost::shared_ptr<ControlList> nal = create (_parameter);
1129
1130         {
1131                 Glib::Mutex::Lock lm (_lock);
1132
1133                 for (iterator x = start; x != end; ) {
1134                         iterator tmp;
1135                         
1136                         tmp = x;
1137                         ++tmp;
1138                         
1139                         nal->_events.push_back (new ControlEvent (**x));
1140                         _events.erase (x);
1141                         
1142                         reposition_for_rt_add (0);
1143
1144                         x = tmp;
1145                 }
1146
1147                 mark_dirty ();
1148         }
1149
1150         maybe_signal_changed ();
1151
1152         return nal;
1153 }
1154
1155 boost::shared_ptr<ControlList>
1156 ControlList::cut_copy_clear (double start, double end, int op)
1157 {
1158         boost::shared_ptr<ControlList> nal = create (_parameter);
1159         iterator s, e;
1160         ControlEvent cp (start, 0.0);
1161         bool changed = false;
1162         
1163         {
1164                 Glib::Mutex::Lock lm (_lock);
1165
1166                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) == _events.end()) {
1167                         return nal;
1168                 }
1169
1170                 cp.when = end;
1171                 e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
1172
1173                 if (op != 2 && (*s)->when != start) {
1174                         nal->_events.push_back (new ControlEvent (0, unlocked_eval (start)));
1175                 }
1176
1177                 for (iterator x = s; x != e; ) {
1178                         iterator tmp;
1179                         
1180                         tmp = x;
1181                         ++tmp;
1182
1183                         changed = true;
1184                         
1185                         /* adjust new points to be relative to start, which
1186                            has been set to zero.
1187                         */
1188                         
1189                         if (op != 2) {
1190                                 nal->_events.push_back (new ControlEvent ((*x)->when - start, (*x)->value));
1191                         }
1192
1193                         if (op != 1) {
1194                                 _events.erase (x);
1195                         }
1196                         
1197                         x = tmp;
1198                 }
1199
1200                 if (op != 2 && nal->_events.back()->when != end - start) {
1201                         nal->_events.push_back (new ControlEvent (end - start, unlocked_eval (end)));
1202                 }
1203
1204                 if (changed) {
1205                         reposition_for_rt_add (0);
1206                 }
1207
1208                 mark_dirty ();
1209         }
1210
1211         maybe_signal_changed ();
1212
1213         return nal;
1214
1215 }
1216
1217 boost::shared_ptr<ControlList>
1218 ControlList::copy (iterator start, iterator end)
1219 {
1220         boost::shared_ptr<ControlList> nal = create (_parameter);
1221
1222         {
1223                 Glib::Mutex::Lock lm (_lock);
1224                 
1225                 for (iterator x = start; x != end; ) {
1226                         iterator tmp;
1227                         
1228                         tmp = x;
1229                         ++tmp;
1230                         
1231                         nal->_events.push_back (new ControlEvent (**x));
1232                         
1233                         x = tmp;
1234                 }
1235         }
1236
1237         return nal;
1238 }
1239
1240 boost::shared_ptr<ControlList>
1241 ControlList::cut (double start, double end)
1242 {
1243         return cut_copy_clear (start, end, 0);
1244 }
1245
1246 boost::shared_ptr<ControlList>
1247 ControlList::copy (double start, double end)
1248 {
1249         return cut_copy_clear (start, end, 1);
1250 }
1251
1252 void
1253 ControlList::clear (double start, double end)
1254 {
1255         (void) cut_copy_clear (start, end, 2);
1256 }
1257
1258 bool
1259 ControlList::paste (ControlList& alist, double pos, float times)
1260 {
1261         if (alist._events.empty()) {
1262                 return false;
1263         }
1264
1265         {
1266                 Glib::Mutex::Lock lm (_lock);
1267                 iterator where;
1268                 iterator prev;
1269                 double end = 0;
1270                 ControlEvent cp (pos, 0.0);
1271
1272                 where = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
1273
1274                 for (iterator i = alist.begin();i != alist.end(); ++i) {
1275                         _events.insert (where, new ControlEvent( (*i)->when+pos,( *i)->value));
1276                         end = (*i)->when + pos;
1277                 }
1278         
1279         
1280                 /* move all  points after the insertion along the timeline by 
1281                    the correct amount.
1282                 */
1283
1284                 while (where != _events.end()) {
1285                         iterator tmp;
1286                         if ((*where)->when <= end) {
1287                                 tmp = where;
1288                                 ++tmp;
1289                                 _events.erase(where);
1290                                 where = tmp;
1291
1292                         } else {
1293                                 break;
1294                         }
1295                 }
1296
1297                 reposition_for_rt_add (0);
1298                 mark_dirty ();
1299         }
1300
1301         maybe_signal_changed ();
1302         return true;
1303 }
1304
1305 /** Move automation around according to a list of region movements */
1306 void
1307 ControlList::move_ranges (RangeMoveList const & movements)
1308 {
1309         {
1310                 Glib::Mutex::Lock lm (_lock);
1311
1312                 /* a copy of the events list before we started moving stuff around */
1313                 EventList old_events = _events;
1314
1315                 /* clear the source and destination ranges in the new list */
1316                 for (RangeMoveList::const_iterator i = movements.begin (); i != movements.end (); ++i) {
1317
1318                         erase_range_internal (i->from, i->from + i->length, _events);
1319                         erase_range_internal (i->to, i->to + i->length, _events);
1320
1321                 }
1322
1323                 /* copy the events into the new list */
1324                 for (RangeMoveList::const_iterator i = movements.begin (); i != movements.end (); ++i) {
1325                         iterator j = old_events.begin ();
1326                         EventTime const limit = i->from + i->length;
1327                         EventTime const dx = i->to - i->from;
1328                         while (j != old_events.end () && (*j)->when <= limit) {
1329                                 if ((*j)->when >= i->from) {
1330                                         ControlEvent* ev = new ControlEvent (**j);
1331                                         ev->when += dx;
1332                                         _events.push_back (ev);
1333                                 }
1334                                 ++j;
1335                         }
1336                 }
1337
1338                 if (!_frozen) {
1339                         _events.sort (event_time_less_than);
1340                 } else {
1341                         _sort_pending = true;
1342                 }
1343
1344                 reposition_for_rt_add (0);
1345                 mark_dirty ();
1346         }
1347
1348         maybe_signal_changed ();
1349 }
1350
1351 } // namespace Evoral
1352