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