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