Fixes for GCC 4.3.
[ardour.git] / libs / ardour / automation_event.cc
1 /*
2     Copyright (C) 2002 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <set>
21 #include <climits>
22 #include <float.h>
23 #include <cmath>
24 #include <sstream>
25 #include <algorithm>
26 #include <sigc++/bind.h>
27 #include <ardour/parameter.h>
28 #include <ardour/automation_event.h>
29 #include <ardour/curve.h>
30 #include <pbd/stacktrace.h>
31 #include <pbd/enumwriter.h>
32
33 #include "i18n.h"
34
35 using namespace std;
36 using namespace ARDOUR;
37 using namespace sigc;
38 using namespace PBD;
39
40 sigc::signal<void,AutomationList *> AutomationList::AutomationListCreated;
41
42 static bool sort_events_by_time (ControlEvent* a, ControlEvent* b)
43 {
44         return a->when < b->when;
45 }
46
47 #if 0
48 static void dumpit (const AutomationList& al, string prefix = "")
49 {
50         cerr << prefix << &al << endl;
51         for (AutomationList::const_iterator i = al.const_begin(); i != al.const_end(); ++i) {
52                 cerr << prefix << '\t' << (*i)->when << ',' << (*i)->value << endl;
53         }
54         cerr << "\n";
55 }
56 #endif
57
58 AutomationList::AutomationList (Parameter id, double min_val, double max_val, double default_val)
59         : _parameter(id)
60         , _interpolation(Linear)
61         , _curve(new Curve(*this))
62 {       
63         _parameter = id;
64         _frozen = 0;
65         _changed_when_thawed = false;
66         _state = Off;
67         _style = Absolute;
68         _min_yval = min_val;
69         _max_yval = max_val;
70         _touching = false;
71         _max_xval = 0; // means "no limit" 
72         _default_value = default_val;
73         _rt_insertion_point = _events.end();
74         _lookup_cache.left = -1;
75         _lookup_cache.range.first = _events.end();
76         _search_cache.left = -1;
77         _search_cache.range.first = _events.end();
78         _sort_pending = false;
79
80         assert(_parameter.type() != NullAutomation);
81         AutomationListCreated(this);
82 }
83
84 AutomationList::AutomationList (const AutomationList& other)
85         : _parameter(other._parameter)
86         , _interpolation(Linear)
87         , _curve(new Curve(*this))
88 {
89         _frozen = 0;
90         _changed_when_thawed = false;
91         _style = other._style;
92         _min_yval = other._min_yval;
93         _max_yval = other._max_yval;
94         _max_xval = other._max_xval;
95         _default_value = other._default_value;
96         _state = other._state;
97         _touching = other._touching;
98         _rt_insertion_point = _events.end();
99         _lookup_cache.range.first = _events.end();
100         _search_cache.range.first = _events.end();
101         _sort_pending = false;
102
103         for (const_iterator i = other._events.begin(); i != other._events.end(); ++i) {
104                 _events.push_back (new ControlEvent (**i));
105         }
106
107         mark_dirty ();
108         assert(_parameter.type() != NullAutomation);
109         AutomationListCreated(this);
110 }
111
112 AutomationList::AutomationList (const AutomationList& other, double start, double end)
113         : _parameter(other._parameter)
114         , _interpolation(Linear)
115         , _curve(new Curve(*this))
116 {
117         _frozen = 0;
118         _changed_when_thawed = false;
119         _style = other._style;
120         _min_yval = other._min_yval;
121         _max_yval = other._max_yval;
122         _max_xval = other._max_xval;
123         _default_value = other._default_value;
124         _state = other._state;
125         _touching = other._touching;
126         _rt_insertion_point = _events.end();
127         _lookup_cache.range.first = _events.end();
128         _search_cache.range.first = _events.end();
129         _sort_pending = false;
130
131         /* now grab the relevant points, and shift them back if necessary */
132
133         AutomationList* section = const_cast<AutomationList*>(&other)->copy (start, end);
134
135         if (!section->empty()) {
136                 for (iterator i = section->begin(); i != section->end(); ++i) {
137                         _events.push_back (new ControlEvent ((*i)->when, (*i)->value));
138                 }
139         }
140
141         delete section;
142
143         mark_dirty ();
144
145         assert(_parameter.type() != NullAutomation);
146         AutomationListCreated(this);
147 }
148
149 /** \a id is used for legacy sessions where the type is not present
150  * in or below the <AutomationList> node.  It is used if \a id is non-null.
151  */
152 AutomationList::AutomationList (const XMLNode& node, Parameter id)
153         : _interpolation(Linear)
154         , _curve(new Curve(*this))
155 {
156         _frozen = 0;
157         _changed_when_thawed = false;
158         _touching = false;
159         _min_yval = FLT_MIN;
160         _max_yval = FLT_MAX;
161         _max_xval = 0; // means "no limit" 
162         _state = Off;
163         _style = Absolute;
164         _rt_insertion_point = _events.end();
165         _lookup_cache.range.first = _events.end();
166         _search_cache.range.first = _events.end();
167         _sort_pending = false;
168         
169         set_state (node);
170
171         if (id)
172                 _parameter = id;
173
174         assert(_parameter.type() != NullAutomation);
175         AutomationListCreated(this);
176 }
177
178 AutomationList::~AutomationList()
179 {
180         GoingAway ();
181         
182         for (EventList::iterator x = _events.begin(); x != _events.end(); ++x) {
183                 delete (*x);
184         }
185 }
186
187 bool
188 AutomationList::operator== (const AutomationList& other)
189 {
190         return _events == other._events;
191 }
192
193 AutomationList&
194 AutomationList::operator= (const AutomationList& other)
195 {
196         if (this != &other) {
197                 
198                 _events.clear ();
199                 
200                 for (const_iterator i = other._events.begin(); i != other._events.end(); ++i) {
201                         _events.push_back (new ControlEvent (**i));
202                 }
203                 
204                 _min_yval = other._min_yval;
205                 _max_yval = other._max_yval;
206                 _max_xval = other._max_xval;
207                 _default_value = other._default_value;
208                 
209                 mark_dirty ();
210                 maybe_signal_changed ();
211         }
212
213         return *this;
214 }
215
216 void
217 AutomationList::maybe_signal_changed ()
218 {
219         mark_dirty ();
220
221         if (_frozen) {
222                 _changed_when_thawed = true;
223         } else {
224                 StateChanged ();
225         }
226 }
227
228 void
229 AutomationList::set_automation_state (AutoState s)
230 {
231         if (s != _state) {
232                 _state = s;
233                 automation_state_changed (); /* EMIT SIGNAL */
234         }
235 }
236
237 void
238 AutomationList::set_automation_style (AutoStyle s)
239 {
240         if (s != _style) {
241                 _style = s;
242                 automation_style_changed (); /* EMIT SIGNAL */
243         }
244 }
245
246 void
247 AutomationList::start_touch ()
248 {
249         _touching = true;
250         _new_touch = true;
251 }
252
253 void
254 AutomationList::stop_touch ()
255 {
256         _touching = false;
257         _new_touch = false;
258 }
259
260 void
261 AutomationList::clear ()
262 {
263         {
264                 Glib::Mutex::Lock lm (_lock);
265                 _events.clear ();
266                 mark_dirty ();
267         }
268
269         maybe_signal_changed ();
270 }
271
272 void
273 AutomationList::x_scale (double factor)
274 {
275         Glib::Mutex::Lock lm (_lock);
276         _x_scale (factor);
277 }
278
279 bool
280 AutomationList::extend_to (double when)
281 {
282         Glib::Mutex::Lock lm (_lock);
283         if (_events.empty() || _events.back()->when == when) {
284                 return false;
285         }
286         double factor = when / _events.back()->when;
287         _x_scale (factor);
288         return true;
289 }
290
291 void AutomationList::_x_scale (double factor)
292 {
293         for (iterator i = _events.begin(); i != _events.end(); ++i) {
294                 (*i)->when = floor ((*i)->when * factor);
295         }
296
297         mark_dirty ();
298 }
299
300 void
301 AutomationList::reposition_for_rt_add (double when)
302 {
303         _rt_insertion_point = _events.end();
304 }
305
306 void
307 AutomationList::rt_add (double when, double value)
308 {
309         /* this is for automation recording */
310
311         if ((_state & Touch) && !_touching) {
312                 return;
313         }
314
315         // cerr << "RT: alist @ " << this << " add " << value << " @ " << when << endl;
316
317         {
318                 Glib::Mutex::Lock lm (_lock);
319
320                 iterator where;
321                 ControlEvent cp (when, 0.0);
322                 bool done = false;
323
324                 if ((_rt_insertion_point != _events.end()) && ((*_rt_insertion_point)->when < when) ) {
325
326                         /* we have a previous insertion point, so we should delete
327                            everything between it and the position where we are going
328                            to insert this point.
329                         */
330
331                         iterator after = _rt_insertion_point;
332
333                         if (++after != _events.end()) {
334                                 iterator far = after;
335
336                                 while (far != _events.end()) {
337                                         if ((*far)->when > when) {
338                                                 break;
339                                         }
340                                         ++far;
341                                 }
342
343                                 if (_new_touch) {
344                                         where = far;
345                                         _rt_insertion_point = where;
346
347                                         if ((*where)->when == when) {
348                                                 (*where)->value = value;
349                                                 done = true;
350                                         }
351                                 } else {
352                                         where = _events.erase (after, far);
353                                 }
354
355                         } else {
356
357                                 where = after;
358
359                         }
360                         
361                         iterator previous = _rt_insertion_point;
362                         --previous;
363                         
364                         if (_rt_insertion_point != _events.begin() && (*_rt_insertion_point)->value == value && (*previous)->value == value) {
365                                 (*_rt_insertion_point)->when = when;
366                                 done = true;
367                                 
368                         }
369                         
370                 } else {
371
372                         where = lower_bound (_events.begin(), _events.end(), &cp, time_comparator);
373
374                         if (where != _events.end()) {
375                                 if ((*where)->when == when) {
376                                         (*where)->value = value;
377                                         done = true;
378                                 }
379                         }
380                 }
381
382                 if (!done) {
383                         _rt_insertion_point = _events.insert (where, new ControlEvent (when, value));
384                 }
385                 
386                 _new_touch = false;
387                 mark_dirty ();
388         }
389
390         maybe_signal_changed ();
391 }
392
393 void
394 AutomationList::fast_simple_add (double when, double value)
395 {
396         /* to be used only for loading pre-sorted data from saved state */
397         _events.insert (_events.end(), new ControlEvent (when, value));
398         assert(_events.back());
399 }
400
401 void
402 AutomationList::add (double when, double value)
403 {
404         /* this is for graphical editing */
405
406         {
407                 Glib::Mutex::Lock lm (_lock);
408                 ControlEvent cp (when, 0.0f);
409                 bool insert = true;
410                 iterator insertion_point;
411
412                 for (insertion_point = lower_bound (_events.begin(), _events.end(), &cp, time_comparator); insertion_point != _events.end(); ++insertion_point) {
413
414                         /* only one point allowed per time point */
415
416                         if ((*insertion_point)->when == when) {
417                                 (*insertion_point)->value = value;
418                                 insert = false;
419                                 break;
420                         } 
421
422                         if ((*insertion_point)->when >= when) {
423                                 break;
424                         }
425                 }
426
427                 if (insert) {
428                         
429                         _events.insert (insertion_point, new ControlEvent (when, value));
430                         reposition_for_rt_add (0);
431
432                 } 
433
434                 mark_dirty ();
435         }
436
437         maybe_signal_changed ();
438 }
439
440 void
441 AutomationList::erase (iterator i)
442 {
443         {
444                 Glib::Mutex::Lock lm (_lock);
445                 _events.erase (i);
446                 reposition_for_rt_add (0);
447                 mark_dirty ();
448         }
449         maybe_signal_changed ();
450 }
451
452 void
453 AutomationList::erase (iterator start, iterator end)
454 {
455         {
456                 Glib::Mutex::Lock lm (_lock);
457                 _events.erase (start, end);
458                 reposition_for_rt_add (0);
459                 mark_dirty ();
460         }
461         maybe_signal_changed ();
462 }       
463
464 void
465 AutomationList::reset_range (double start, double endt)
466 {
467         bool reset = false;
468
469         {
470         Glib::Mutex::Lock lm (_lock);
471                 ControlEvent cp (start, 0.0f);
472                 iterator s;
473                 iterator e;
474                 
475                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) != _events.end()) {
476
477                         cp.when = endt;
478                         e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
479
480                         for (iterator i = s; i != e; ++i) {
481                                 (*i)->value = _default_value;
482                         }
483                         
484                         reset = true;
485
486                         mark_dirty ();
487                 }
488         }
489
490         if (reset) {
491                 maybe_signal_changed ();
492         }
493 }
494
495 void
496 AutomationList::erase_range (double start, double endt)
497 {
498         bool erased = false;
499
500         {
501                 Glib::Mutex::Lock lm (_lock);
502                 ControlEvent cp (start, 0.0f);
503                 iterator s;
504                 iterator e;
505
506                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) != _events.end()) {
507                         cp.when = endt;
508                         e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
509                         _events.erase (s, e);
510                         reposition_for_rt_add (0);
511                         erased = true;
512                         mark_dirty ();
513                 }
514                 
515         }
516
517         if (erased) {
518                 maybe_signal_changed ();
519         }
520 }
521
522 void
523 AutomationList::move_range (iterator start, iterator end, double xdelta, double ydelta)
524 {
525         /* note: we assume higher level logic is in place to avoid this
526            reordering the time-order of control events in the list. ie. all
527            points after end are later than (end)->when.
528         */
529
530         {
531                 Glib::Mutex::Lock lm (_lock);
532
533                 while (start != end) {
534                         (*start)->when += xdelta;
535                         (*start)->value += ydelta;
536                         if (isnan ((*start)->value)) {
537                                 abort ();
538                         }
539                         ++start;
540                 }
541
542                 if (!_frozen) {
543                         _events.sort (sort_events_by_time);
544                 } else {
545                         _sort_pending = true;
546                 }
547
548                 mark_dirty ();
549         }
550
551         maybe_signal_changed ();
552 }
553
554 void
555 AutomationList::slide (iterator before, double distance)
556 {
557         {
558                 Glib::Mutex::Lock lm (_lock);
559
560                 if (before == _events.end()) {
561                         return;
562                 }
563                 
564                 while (before != _events.end()) {
565                         (*before)->when += distance;
566                         ++before;
567                 }
568         }
569
570         maybe_signal_changed ();
571 }
572
573 void
574 AutomationList::modify (iterator iter, double when, double val)
575 {
576         /* note: we assume higher level logic is in place to avoid this
577            reordering the time-order of control events in the list. ie. all
578            points after *iter are later than when.
579         */
580
581         {
582                 Glib::Mutex::Lock lm (_lock);
583
584                 (*iter)->when = when;
585                 (*iter)->value = val;
586
587                 if (isnan (val)) {
588                         abort ();
589                 }
590
591                 if (!_frozen) {
592                         _events.sort (sort_events_by_time);
593                 } else {
594                         _sort_pending = true;
595                 }
596
597                 mark_dirty ();
598         }
599
600         maybe_signal_changed ();
601 }
602
603 std::pair<AutomationList::iterator,AutomationList::iterator>
604 AutomationList::control_points_adjacent (double xval)
605 {
606         Glib::Mutex::Lock lm (_lock);
607         iterator i;
608         ControlEvent cp (xval, 0.0f);
609         std::pair<iterator,iterator> ret;
610
611         ret.first = _events.end();
612         ret.second = _events.end();
613
614         for (i = lower_bound (_events.begin(), _events.end(), &cp, time_comparator); i != _events.end(); ++i) {
615                 
616                 if (ret.first == _events.end()) {
617                         if ((*i)->when >= xval) {
618                                 if (i != _events.begin()) {
619                                         ret.first = i;
620                                         --ret.first;
621                                 } else {
622                                         return ret;
623                                 }
624                         }
625                 } 
626                 
627                 if ((*i)->when > xval) {
628                         ret.second = i;
629                         break;
630                 }
631         }
632
633         return ret;
634 }
635
636 void
637 AutomationList::freeze ()
638 {
639         _frozen++;
640 }
641
642 void
643 AutomationList::thaw ()
644 {
645         if (_frozen == 0) {
646                 PBD::stacktrace (cerr);
647                 fatal << string_compose (_("programming error: %1"), X_("AutomationList::thaw() called while not frozen")) << endmsg;
648                 /*NOTREACHED*/
649         }
650
651         if (--_frozen > 0) {
652                 return;
653         }
654
655         {
656                 Glib::Mutex::Lock lm (_lock);
657
658                 if (_sort_pending) {
659                         _events.sort (sort_events_by_time);
660                         _sort_pending = false;
661                 }
662         }
663
664         if (_changed_when_thawed) {
665                 StateChanged(); /* EMIT SIGNAL */
666         }
667 }
668
669 void
670 AutomationList::set_max_xval (double x)
671 {
672         _max_xval = x;
673 }
674
675 void 
676 AutomationList::mark_dirty ()
677 {
678         _lookup_cache.left = -1;
679         _search_cache.left = -1;
680         Dirty (); /* EMIT SIGNAL */
681 }
682
683 void
684 AutomationList::truncate_end (double last_coordinate)
685 {
686         {
687                 Glib::Mutex::Lock lm (_lock);
688                 ControlEvent cp (last_coordinate, 0);
689                 AutomationList::reverse_iterator i;
690                 double last_val;
691
692                 if (_events.empty()) {
693                         return;
694                 }
695
696                 if (last_coordinate == _events.back()->when) {
697                         return;
698                 }
699
700                 if (last_coordinate > _events.back()->when) {
701                         
702                         /* extending end:
703                         */
704
705                         iterator foo = _events.begin();
706                         bool lessthantwo;
707
708                         if (foo == _events.end()) {
709                                 lessthantwo = true;
710                         } else if (++foo == _events.end()) {
711                                 lessthantwo = true;
712                         } else {
713                                 lessthantwo = false;
714                         }
715
716                         if (lessthantwo) {
717                                 /* less than 2 points: add a new point */
718                                 _events.push_back (new ControlEvent (last_coordinate, _events.back()->value));
719                         } else {
720
721                                 /* more than 2 points: check to see if the last 2 values
722                                    are equal. if so, just move the position of the
723                                    last point. otherwise, add a new point.
724                                 */
725
726                                 iterator penultimate = _events.end();
727                                 --penultimate; /* points at last point */
728                                 --penultimate; /* points at the penultimate point */
729                                 
730                                 if (_events.back()->value == (*penultimate)->value) {
731                                         _events.back()->when = last_coordinate;
732                                 } else {
733                                         _events.push_back (new ControlEvent (last_coordinate, _events.back()->value));
734                                 }
735                         }
736
737                 } else {
738
739                         /* shortening end */
740
741                         last_val = unlocked_eval (last_coordinate);
742                         last_val = max ((double) _min_yval, last_val);
743                         last_val = min ((double) _max_yval, last_val);
744                         
745                         i = _events.rbegin();
746                         
747                         /* make i point to the last control point */
748                         
749                         ++i;
750                         
751                         /* now go backwards, removing control points that are
752                            beyond the new last coordinate.
753                         */
754
755                         uint32_t sz = _events.size();
756                         
757                         while (i != _events.rend() && sz > 2) {
758                                 AutomationList::reverse_iterator tmp;
759                                 
760                                 tmp = i;
761                                 ++tmp;
762                                 
763                                 if ((*i)->when < last_coordinate) {
764                                         break;
765                                 }
766                                 
767                                 _events.erase (i.base());
768                                 --sz;
769
770                                 i = tmp;
771                         }
772                         
773                         _events.back()->when = last_coordinate;
774                         _events.back()->value = last_val;
775                 }
776
777                 reposition_for_rt_add (0);
778                 mark_dirty();
779         }
780
781         maybe_signal_changed ();
782 }
783
784 void
785 AutomationList::truncate_start (double overall_length)
786 {
787         {
788                 Glib::Mutex::Lock lm (_lock);
789                 iterator i;
790                 double first_legal_value;
791                 double first_legal_coordinate;
792
793                 if (_events.empty()) {
794                         fatal << _("programming error:")
795                               << "AutomationList::truncate_start() called on an empty list"
796                               << endmsg;
797                         /*NOTREACHED*/
798                         return;
799                 }
800                 
801                 if (overall_length == _events.back()->when) {
802                         /* no change in overall length */
803                         return;
804                 }
805                 
806                 if (overall_length > _events.back()->when) {
807                         
808                         /* growing at front: duplicate first point. shift all others */
809
810                         double shift = overall_length - _events.back()->when;
811                         uint32_t np;
812
813                         for (np = 0, i = _events.begin(); i != _events.end(); ++i, ++np) {
814                                 (*i)->when += shift;
815                         }
816
817                         if (np < 2) {
818
819                                 /* less than 2 points: add a new point */
820                                 _events.push_front (new ControlEvent (0, _events.front()->value));
821
822                         } else {
823
824                                 /* more than 2 points: check to see if the first 2 values
825                                    are equal. if so, just move the position of the
826                                    first point. otherwise, add a new point.
827                                 */
828
829                                 iterator second = _events.begin();
830                                 ++second; /* points at the second point */
831                                 
832                                 if (_events.front()->value == (*second)->value) {
833                                         /* first segment is flat, just move start point back to zero */
834                                         _events.front()->when = 0;
835                                 } else {
836                                         /* leave non-flat segment in place, add a new leading point. */
837                                         _events.push_front (new ControlEvent (0, _events.front()->value));
838                                 }
839                         }
840
841                 } else {
842
843                         /* shrinking at front */
844                         
845                         first_legal_coordinate = _events.back()->when - overall_length;
846                         first_legal_value = unlocked_eval (first_legal_coordinate);
847                         first_legal_value = max (_min_yval, first_legal_value);
848                         first_legal_value = min (_max_yval, first_legal_value);
849
850                         /* remove all events earlier than the new "front" */
851
852                         i = _events.begin();
853                         
854                         while (i != _events.end() && !_events.empty()) {
855                                 AutomationList::iterator tmp;
856                                 
857                                 tmp = i;
858                                 ++tmp;
859                                 
860                                 if ((*i)->when > first_legal_coordinate) {
861                                         break;
862                                 }
863                                 
864                                 _events.erase (i);
865                                 
866                                 i = tmp;
867                         }
868                         
869
870                         /* shift all remaining points left to keep their same
871                            relative position
872                         */
873                         
874                         for (i = _events.begin(); i != _events.end(); ++i) {
875                                 (*i)->when -= first_legal_coordinate;
876                         }
877
878                         /* add a new point for the interpolated new value */
879                         
880                         _events.push_front (new ControlEvent (0, first_legal_value));
881                 }           
882
883                 reposition_for_rt_add (0);
884
885                 mark_dirty();
886         }
887
888         maybe_signal_changed ();
889 }
890
891 double
892 AutomationList::unlocked_eval (double x) const
893 {
894         pair<EventList::iterator,EventList::iterator> range;
895         int32_t npoints;
896         double lpos, upos;
897         double lval, uval;
898         double fraction;
899
900         npoints = _events.size();
901
902         switch (npoints) {
903         case 0:
904                 return _default_value;
905
906         case 1:
907                 if (x >= _events.front()->when) {
908                         return _events.front()->value;
909                 } else {
910                         // return _default_value;
911                         return _events.front()->value;
912                 } 
913                 
914         case 2:
915                 if (x >= _events.back()->when) {
916                         return _events.back()->value;
917                 } else if (x == _events.front()->when) {
918                         return _events.front()->value;
919                 } else if (x < _events.front()->when) {
920                         // return _default_value;
921                         return _events.front()->value;
922                 }
923
924                 lpos = _events.front()->when;
925                 lval = _events.front()->value;
926                 upos = _events.back()->when;
927                 uval = _events.back()->value;
928                 
929                 if (_interpolation == Discrete)
930                         return lval;
931
932                 /* linear interpolation betweeen the two points
933                 */
934
935                 fraction = (double) (x - lpos) / (double) (upos - lpos);
936                 return lval + (fraction * (uval - lval));
937
938         default:
939
940                 if (x >= _events.back()->when) {
941                         return _events.back()->value;
942                 } else if (x == _events.front()->when) {
943                         return _events.front()->value;
944                 } else if (x < _events.front()->when) {
945                         // return _default_value;
946                         return _events.front()->value;
947                 }
948
949                 return multipoint_eval (x);
950                 break;
951         }
952
953         /*NOTREACHED*/ /* stupid gcc */
954         return 0.0;
955 }
956
957 double
958 AutomationList::multipoint_eval (double x) const
959 {
960         double upos, lpos;
961         double uval, lval;
962         double fraction;
963         
964         /* "Stepped" lookup (no interpolation) */
965         /* FIXME: no cache.  significant? */
966         if (_interpolation == Discrete) {
967                 const ControlEvent cp (x, 0);
968                 EventList::const_iterator i = lower_bound (_events.begin(), _events.end(), &cp, time_comparator);
969
970                 // shouldn't have made it to multipoint_eval
971                 assert(i != _events.end());
972
973                 if (i == _events.begin() || (*i)->when == x)
974                         return (*i)->value;
975                 else
976                         return (*(--i))->value;
977         }
978
979         /* Only do the range lookup if x is in a different range than last time
980          * this was called (or if the lookup cache has been marked "dirty" (left<0) */
981         if ((_lookup_cache.left < 0) ||
982             ((_lookup_cache.left > x) || 
983              (_lookup_cache.range.first == _events.end()) || 
984              ((*_lookup_cache.range.second)->when < x))) {
985
986                 const ControlEvent cp (x, 0);
987                 
988                 _lookup_cache.range = equal_range (_events.begin(), _events.end(), &cp, time_comparator);
989         }
990         
991         pair<const_iterator,const_iterator> range = _lookup_cache.range;
992
993         if (range.first == range.second) {
994
995                 /* x does not exist within the list as a control point */
996
997                 _lookup_cache.left = x;
998
999                 if (range.first != _events.begin()) {
1000                         --range.first;
1001                         lpos = (*range.first)->when;
1002                         lval = (*range.first)->value;
1003                 }  else {
1004                         /* we're before the first point */
1005                         // return _default_value;
1006                         return _events.front()->value;
1007                 }
1008                 
1009                 if (range.second == _events.end()) {
1010                         /* we're after the last point */
1011                         return _events.back()->value;
1012                 }
1013
1014                 upos = (*range.second)->when;
1015                 uval = (*range.second)->value;
1016                 
1017                 /* linear interpolation betweeen the two points
1018                    on either side of x
1019                 */
1020
1021                 fraction = (double) (x - lpos) / (double) (upos - lpos);
1022                 return lval + (fraction * (uval - lval));
1023
1024         } 
1025
1026         /* x is a control point in the data */
1027         _lookup_cache.left = -1;
1028         return (*range.first)->value;
1029 }
1030
1031 void
1032 AutomationList::build_search_cache_if_necessary(double start, double end) const
1033 {
1034         /* Only do the range lookup if x is in a different range than last time
1035          * this was called (or if the search cache has been marked "dirty" (left<0) */
1036         if (!_events.empty() && ((_search_cache.left < 0) ||
1037                         ((_search_cache.left > start) ||
1038                          (_search_cache.right < end)))) {
1039
1040                 const ControlEvent start_point (start, 0);
1041                 const ControlEvent end_point (end, 0);
1042
1043                 //cerr << "REBUILD: (" << _search_cache.left << ".." << _search_cache.right << ") := ("
1044                 //      << start << ".." << end << ")" << endl;
1045
1046                 _search_cache.range.first = lower_bound (_events.begin(), _events.end(), &start_point, time_comparator);
1047                 _search_cache.range.second = upper_bound (_events.begin(), _events.end(), &end_point, time_comparator);
1048
1049                 _search_cache.left = start;
1050                 _search_cache.right = end;
1051         }
1052 }
1053
1054 /** Get the earliest event between \a start and \a end, using the current interpolation style.
1055  *
1056  * If an event is found, \a x and \a y are set to its coordinates.
1057  *
1058  * \param inclusive Include events with timestamp exactly equal to \a start
1059  * \return true if event is found (and \a x and \a y are valid).
1060  */
1061 bool
1062 AutomationList::rt_safe_earliest_event(double start, double end, double& x, double& y, bool inclusive) const
1063 {
1064         // FIXME: It would be nice if this was unnecessary..
1065         Glib::Mutex::Lock lm(_lock, Glib::TRY_LOCK);
1066         if (!lm.locked()) {
1067                 return false;
1068         }
1069
1070         return rt_safe_earliest_event_unlocked(start, end, x, y, inclusive);
1071
1072
1073
1074 /** Get the earliest event between \a start and \a end, using the current interpolation style.
1075  *
1076  * If an event is found, \a x and \a y are set to its coordinates.
1077  *
1078  * \param inclusive Include events with timestamp exactly equal to \a start
1079  * \return true if event is found (and \a x and \a y are valid).
1080  */
1081 bool
1082 AutomationList::rt_safe_earliest_event_unlocked(double start, double end, double& x, double& y, bool inclusive) const
1083 {
1084         if (_interpolation == Discrete)
1085                 return rt_safe_earliest_event_discrete_unlocked(start, end, x, y, inclusive);
1086         else
1087                 return rt_safe_earliest_event_linear_unlocked(start, end, x, y, inclusive);
1088
1089
1090
1091 /** Get the earliest event between \a start and \a end (Discrete (lack of) interpolation)
1092  *
1093  * If an event is found, \a x and \a y are set to its coordinates.
1094  *
1095  * \param inclusive Include events with timestamp exactly equal to \a start
1096  * \return true if event is found (and \a x and \a y are valid).
1097  */
1098 bool
1099 AutomationList::rt_safe_earliest_event_discrete_unlocked (double start, double end, double& x, double& y, bool inclusive) const
1100 {
1101         build_search_cache_if_necessary(start, end);
1102
1103         const pair<const_iterator,const_iterator>& range = _search_cache.range;
1104
1105         if (range.first != _events.end()) {
1106                 const ControlEvent* const first = *range.first;
1107
1108                 const bool past_start = (inclusive ? first->when >= start : first->when > start);
1109
1110                 /* Earliest points is in range, return it */
1111                 if (past_start >= start && first->when < end) {
1112
1113                         x = first->when;
1114                         y = first->value;
1115
1116                         /* Move left of cache to this point
1117                          * (Optimize for immediate call this cycle within range) */
1118                         _search_cache.left = x;
1119                         ++_search_cache.range.first;
1120
1121                         assert(x >= start);
1122                         assert(x < end);
1123                         return true;
1124
1125                 } else {
1126                         return false;
1127                 }
1128         
1129         /* No points in range */
1130         } else {
1131                 return false;
1132         }
1133 }
1134
1135 /** Get the earliest time the line crosses an integer (Linear interpolation).
1136  *
1137  * If an event is found, \a x and \a y are set to its coordinates.
1138  *
1139  * \param inclusive Include events with timestamp exactly equal to \a start
1140  * \return true if event is found (and \a x and \a y are valid).
1141  */
1142 bool
1143 AutomationList::rt_safe_earliest_event_linear_unlocked (double start, double end, double& x, double& y, bool inclusive) const
1144 {
1145         //cerr << "earliest_event(" << start << ", " << end << ", " << x << ", " << y << ", " << inclusive << endl;
1146
1147         if (_events.size() == 0)
1148                 return false;
1149         else if (_events.size() == 1)
1150                 return rt_safe_earliest_event_discrete_unlocked(start, end, x, y, inclusive);
1151
1152         // Hack to avoid infinitely repeating the same event
1153         build_search_cache_if_necessary(start, end);
1154         
1155         pair<const_iterator,const_iterator> range = _search_cache.range;
1156
1157         if (range.first != _events.end()) {
1158
1159                 const ControlEvent* first = NULL;
1160                 const ControlEvent* next = NULL;
1161
1162                 /* Step is after first */
1163                 if (range.first == _events.begin() || (*range.first)->when == start) {
1164                         first = *range.first;
1165                         next = *(++range.first);
1166                         ++_search_cache.range.first;
1167
1168                 /* Step is before first */
1169                 } else {
1170                         const_iterator prev = range.first;
1171                         --prev;
1172                         first = *prev;
1173                         next = *range.first;
1174                 }
1175                 
1176                 if (inclusive && first->when == start) {
1177                         x = first->when;
1178                         y = first->value;
1179                         /* Move left of cache to this point
1180                          * (Optimize for immediate call this cycle within range) */
1181                         _search_cache.left = x;
1182                         //++_search_cache.range.first;
1183                         return true;
1184                 }
1185                         
1186                 if (abs(first->value - next->value) <= 1) {
1187                         if (next->when <= end && (!inclusive || next->when > start)) {
1188                                 x = next->when;
1189                                 y = next->value;
1190                                 /* Move left of cache to this point
1191                                  * (Optimize for immediate call this cycle within range) */
1192                                 _search_cache.left = x;
1193                                 //++_search_cache.range.first;
1194                                 return true;
1195                         } else {
1196                                 return false;
1197                         }
1198                 }
1199
1200                 const double slope = (next->value - first->value) / (double)(next->when - first->when);
1201                 //cerr << "start y: " << start_y << endl;
1202
1203                 //y = first->value + (slope * fabs(start - first->when));
1204                 y = first->value;
1205
1206                 if (first->value < next->value) // ramping up
1207                         y = ceil(y);
1208                 else // ramping down
1209                         y = floor(y);
1210
1211                 x = first->when + (y - first->value) / (double)slope;
1212                 
1213                 while ((inclusive && x < start) || (x <= start && y != next->value)) {
1214                         
1215                         if (first->value < next->value) // ramping up
1216                                 y += 1.0;
1217                         else // ramping down
1218                                 y -= 1.0;
1219
1220                         x = first->when + (y - first->value) / (double)slope;
1221                 }
1222
1223                 /*cerr << first->value << " @ " << first->when << " ... "
1224                                 << next->value << " @ " << next->when
1225                                 << " = " << y << " @ " << x << endl;*/
1226
1227                 assert(    (y >= first->value && y <= next->value)
1228                                 || (y <= first->value && y >= next->value) );
1229
1230                 
1231                 const bool past_start = (inclusive ? x >= start : x > start);
1232                 if (past_start && x < end) {
1233                         /* Move left of cache to this point
1234                          * (Optimize for immediate call this cycle within range) */
1235                         _search_cache.left = x;
1236
1237                         return true;
1238
1239                 } else {
1240                         return false;
1241                 }
1242         
1243         /* No points in the future, so no steps (towards them) in the future */
1244         } else {
1245                 return false;
1246         }
1247 }
1248
1249 AutomationList*
1250 AutomationList::cut (iterator start, iterator end)
1251 {
1252         AutomationList* nal = new AutomationList (_parameter, _min_yval, _max_yval, _default_value);
1253
1254         {
1255                 Glib::Mutex::Lock lm (_lock);
1256
1257                 for (iterator x = start; x != end; ) {
1258                         iterator tmp;
1259                         
1260                         tmp = x;
1261                         ++tmp;
1262                         
1263                         nal->_events.push_back (new ControlEvent (**x));
1264                         _events.erase (x);
1265                         
1266                         reposition_for_rt_add (0);
1267
1268                         x = tmp;
1269                 }
1270
1271                 mark_dirty ();
1272         }
1273
1274         maybe_signal_changed ();
1275
1276         return nal;
1277 }
1278
1279 AutomationList*
1280 AutomationList::cut_copy_clear (double start, double end, int op)
1281 {
1282         AutomationList* nal = new AutomationList (_parameter, _min_yval, _max_yval, _default_value);
1283         iterator s, e;
1284         ControlEvent cp (start, 0.0);
1285         bool changed = false;
1286         
1287         {
1288                 Glib::Mutex::Lock lm (_lock);
1289
1290                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) == _events.end()) {
1291                         return nal;
1292                 }
1293
1294                 cp.when = end;
1295                 e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
1296
1297                 if (op != 2 && (*s)->when != start) {
1298                         nal->_events.push_back (new ControlEvent (0, unlocked_eval (start)));
1299                 }
1300
1301                 for (iterator x = s; x != e; ) {
1302                         iterator tmp;
1303                         
1304                         tmp = x;
1305                         ++tmp;
1306
1307                         changed = true;
1308                         
1309                         /* adjust new points to be relative to start, which
1310                            has been set to zero.
1311                         */
1312                         
1313                         if (op != 2) {
1314                                 nal->_events.push_back (new ControlEvent ((*x)->when - start, (*x)->value));
1315                         }
1316
1317                         if (op != 1) {
1318                                 _events.erase (x);
1319                         }
1320                         
1321                         x = tmp;
1322                 }
1323
1324                 if (op != 2 && nal->_events.back()->when != end - start) {
1325                         nal->_events.push_back (new ControlEvent (end - start, unlocked_eval (end)));
1326                 }
1327
1328                 if (changed) {
1329                         reposition_for_rt_add (0);
1330                 }
1331
1332                 mark_dirty ();
1333         }
1334
1335         maybe_signal_changed ();
1336
1337         return nal;
1338
1339 }
1340
1341 AutomationList*
1342 AutomationList::copy (iterator start, iterator end)
1343 {
1344         AutomationList* nal = new AutomationList (_parameter, _min_yval, _max_yval, _default_value);
1345
1346         {
1347                 Glib::Mutex::Lock lm (_lock);
1348                 
1349                 for (iterator x = start; x != end; ) {
1350                         iterator tmp;
1351                         
1352                         tmp = x;
1353                         ++tmp;
1354                         
1355                         nal->_events.push_back (new ControlEvent (**x));
1356                         
1357                         x = tmp;
1358                 }
1359         }
1360
1361         return nal;
1362 }
1363
1364 AutomationList*
1365 AutomationList::cut (double start, double end)
1366 {
1367         return cut_copy_clear (start, end, 0);
1368 }
1369
1370 AutomationList*
1371 AutomationList::copy (double start, double end)
1372 {
1373         return cut_copy_clear (start, end, 1);
1374 }
1375
1376 void
1377 AutomationList::clear (double start, double end)
1378 {
1379         (void) cut_copy_clear (start, end, 2);
1380 }
1381
1382 bool
1383 AutomationList::paste (AutomationList& alist, double pos, float times)
1384 {
1385         if (alist._events.empty()) {
1386                 return false;
1387         }
1388
1389         {
1390                 Glib::Mutex::Lock lm (_lock);
1391                 iterator where;
1392                 iterator prev;
1393                 double end = 0;
1394                 ControlEvent cp (pos, 0.0);
1395
1396                 where = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
1397
1398                 for (iterator i = alist.begin();i != alist.end(); ++i) {
1399                         _events.insert (where, new ControlEvent( (*i)->when+pos,( *i)->value));
1400                         end = (*i)->when + pos;
1401                 }
1402         
1403         
1404                 /* move all  points after the insertion along the timeline by 
1405                    the correct amount.
1406                 */
1407
1408                 while (where != _events.end()) {
1409                         iterator tmp;
1410                         if ((*where)->when <= end) {
1411                                 tmp = where;
1412                                 ++tmp;
1413                                 _events.erase(where);
1414                                 where = tmp;
1415
1416                         } else {
1417                                 break;
1418                         }
1419                 }
1420
1421                 reposition_for_rt_add (0);
1422                 mark_dirty ();
1423         }
1424
1425         maybe_signal_changed ();
1426         return true;
1427 }
1428
1429 XMLNode&
1430 AutomationList::get_state ()
1431 {
1432         return state (true);
1433 }
1434
1435 XMLNode&
1436 AutomationList::state (bool full)
1437 {
1438         XMLNode* root = new XMLNode (X_("AutomationList"));
1439         char buf[64];
1440         LocaleGuard lg (X_("POSIX"));
1441
1442         root->add_property ("automation-id", _parameter.to_string());
1443
1444         root->add_property ("id", _id.to_s());
1445
1446         snprintf (buf, sizeof (buf), "%.12g", _default_value);
1447         root->add_property ("default", buf);
1448         snprintf (buf, sizeof (buf), "%.12g", _min_yval);
1449         root->add_property ("min_yval", buf);
1450         snprintf (buf, sizeof (buf), "%.12g", _max_yval);
1451         root->add_property ("max_yval", buf);
1452         snprintf (buf, sizeof (buf), "%.12g", _max_xval);
1453         root->add_property ("max_xval", buf);
1454         
1455         root->add_property ("interpolation-style", enum_2_string (_interpolation));
1456
1457         if (full) {
1458                 root->add_property ("state", auto_state_to_string (_state));
1459         } else {
1460                 /* never save anything but Off for automation state to a template */
1461                 root->add_property ("state", auto_state_to_string (Off));
1462         }
1463
1464         root->add_property ("style", auto_style_to_string (_style));
1465
1466         if (!_events.empty()) {
1467                 root->add_child_nocopy (serialize_events());
1468         }
1469
1470         return *root;
1471 }
1472
1473 XMLNode&
1474 AutomationList::serialize_events ()
1475 {
1476         XMLNode* node = new XMLNode (X_("events"));
1477         stringstream str;
1478
1479         for (iterator xx = _events.begin(); xx != _events.end(); ++xx) {
1480                 str << (double) (*xx)->when;
1481                 str << ' ';
1482                 str <<(double) (*xx)->value;
1483                 str << '\n';
1484         }
1485
1486         /* XML is a bit wierd */
1487
1488         XMLNode* content_node = new XMLNode (X_("foo")); /* it gets renamed by libxml when we set content */
1489         content_node->set_content (str.str());
1490
1491         node->add_child_nocopy (*content_node);
1492
1493         return *node;
1494 }
1495
1496 int
1497 AutomationList::deserialize_events (const XMLNode& node)
1498 {
1499         if (node.children().empty()) {
1500                 return -1;
1501         }
1502
1503         XMLNode* content_node = node.children().front();
1504
1505         if (content_node->content().empty()) {
1506                 return -1;
1507         }
1508
1509         freeze ();
1510         clear ();
1511         
1512         stringstream str (content_node->content());
1513         
1514         double x;
1515         double y;
1516         bool ok = true;
1517         
1518         while (str) {
1519                 str >> x;
1520                 if (!str) {
1521                         break;
1522                 }
1523                 str >> y;
1524                 if (!str) {
1525                         ok = false;
1526                         break;
1527                 }
1528                 fast_simple_add (x, y);
1529         }
1530         
1531         if (!ok) {
1532                 clear ();
1533                 error << _("automation list: cannot load coordinates from XML, all points ignored") << endmsg;
1534         } else {
1535                 mark_dirty ();
1536                 reposition_for_rt_add (0);
1537                 maybe_signal_changed ();
1538         }
1539
1540         thaw ();
1541
1542         return 0;
1543 }
1544
1545 int
1546 AutomationList::set_state (const XMLNode& node)
1547 {
1548         XMLNodeList nlist = node.children();
1549         XMLNode* nsos;
1550         XMLNodeIterator niter;
1551         const XMLProperty* prop;
1552
1553         if (node.name() == X_("events")) {
1554                 /* partial state setting*/
1555                 return deserialize_events (node);
1556         }
1557         
1558         if (node.name() == X_("Envelope") || node.name() == X_("FadeOut") || node.name() == X_("FadeIn")) {
1559
1560                 if ((nsos = node.child (X_("AutomationList")))) {
1561                         /* new school in old school clothing */
1562                         return set_state (*nsos);
1563                 }
1564
1565                 /* old school */
1566
1567                 const XMLNodeList& elist = node.children();
1568                 XMLNodeConstIterator i;
1569                 XMLProperty* prop;
1570                 nframes_t x;
1571                 double y;
1572                 
1573                 freeze ();
1574                 clear ();
1575                 
1576                 for (i = elist.begin(); i != elist.end(); ++i) {
1577                         
1578                         if ((prop = (*i)->property ("x")) == 0) {
1579                                 error << _("automation list: no x-coordinate stored for control point (point ignored)") << endmsg;
1580                                 continue;
1581                         }
1582                         x = atoi (prop->value().c_str());
1583                         
1584                         if ((prop = (*i)->property ("y")) == 0) {
1585                                 error << _("automation list: no y-coordinate stored for control point (point ignored)") << endmsg;
1586                                 continue;
1587                         }
1588                         y = atof (prop->value().c_str());
1589                         
1590                         fast_simple_add (x, y);
1591                 }
1592                 
1593                 thaw ();
1594
1595                 return 0;
1596         }
1597
1598         if (node.name() != X_("AutomationList") ) {
1599                 error << string_compose (_("AutomationList: passed XML node called %1, not \"AutomationList\" - ignored"), node.name()) << endmsg;
1600                 return -1;
1601         }
1602
1603         if ((prop = node.property ("id")) != 0) {
1604                 _id = prop->value ();
1605                 /* update session AL list */
1606                 AutomationListCreated(this);
1607         }
1608         
1609         if ((prop = node.property (X_("automation-id"))) != 0){ 
1610                 _parameter = Parameter(prop->value());
1611         } else {
1612                 warning << "Legacy session: automation list has no automation-id property.";
1613         }
1614         
1615         if ((prop = node.property (X_("interpolation-style"))) != 0) {
1616                 _interpolation = (InterpolationStyle)string_2_enum(prop->value(), _interpolation);
1617         } else {
1618                 _interpolation = Linear;
1619         }
1620         
1621         if ((prop = node.property (X_("default"))) != 0){ 
1622                 _default_value = atof (prop->value().c_str());
1623         } else {
1624                 _default_value = 0.0;
1625         }
1626
1627         if ((prop = node.property (X_("style"))) != 0) {
1628                 _style = string_to_auto_style (prop->value());
1629         } else {
1630                 _style = Absolute;
1631         }
1632
1633         if ((prop = node.property (X_("state"))) != 0) {
1634                 _state = string_to_auto_state (prop->value());
1635         } else {
1636                 _state = Off;
1637         }
1638
1639         if ((prop = node.property (X_("min_yval"))) != 0) {
1640                 _min_yval = atof (prop->value ().c_str());
1641         } else {
1642                 _min_yval = FLT_MIN;
1643         }
1644
1645         if ((prop = node.property (X_("max_yval"))) != 0) {
1646                 _max_yval = atof (prop->value ().c_str());
1647         } else {
1648                 _max_yval = FLT_MAX;
1649         }
1650
1651         if ((prop = node.property (X_("max_xval"))) != 0) {
1652                 _max_xval = atof (prop->value ().c_str());
1653         } else {
1654                 _max_xval = 0; // means "no limit ;
1655         }
1656
1657         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1658                 if ((*niter)->name() == X_("events")) {
1659                         deserialize_events (*(*niter));
1660                 }
1661         }
1662
1663         return 0;
1664 }
1665