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