Trimmed some code by removing silly Java-isms.
[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 }
399
400 void
401 AutomationList::add (double when, double value)
402 {
403         /* this is for graphical editing */
404
405         {
406                 Glib::Mutex::Lock lm (_lock);
407                 ControlEvent cp (when, 0.0f);
408                 bool insert = true;
409                 iterator insertion_point;
410
411                 for (insertion_point = lower_bound (_events.begin(), _events.end(), &cp, time_comparator); insertion_point != _events.end(); ++insertion_point) {
412
413                         /* only one point allowed per time point */
414
415                         if ((*insertion_point)->when == when) {
416                                 (*insertion_point)->value = value;
417                                 insert = false;
418                                 break;
419                         } 
420
421                         if ((*insertion_point)->when >= when) {
422                                 break;
423                         }
424                 }
425
426                 if (insert) {
427                         
428                         _events.insert (insertion_point, new ControlEvent (when, value));
429                         reposition_for_rt_add (0);
430
431                 } 
432
433                 mark_dirty ();
434         }
435
436         maybe_signal_changed ();
437 }
438
439 void
440 AutomationList::erase (iterator i)
441 {
442         {
443                 Glib::Mutex::Lock lm (_lock);
444                 _events.erase (i);
445                 reposition_for_rt_add (0);
446                 mark_dirty ();
447         }
448         maybe_signal_changed ();
449 }
450
451 void
452 AutomationList::erase (iterator start, iterator end)
453 {
454         {
455                 Glib::Mutex::Lock lm (_lock);
456                 _events.erase (start, end);
457                 reposition_for_rt_add (0);
458                 mark_dirty ();
459         }
460         maybe_signal_changed ();
461 }       
462
463 void
464 AutomationList::reset_range (double start, double endt)
465 {
466         bool reset = false;
467
468         {
469         Glib::Mutex::Lock lm (_lock);
470                 ControlEvent cp (start, 0.0f);
471                 iterator s;
472                 iterator e;
473                 
474                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) != _events.end()) {
475
476                         cp.when = endt;
477                         e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
478
479                         for (iterator i = s; i != e; ++i) {
480                                 (*i)->value = _default_value;
481                         }
482                         
483                         reset = true;
484
485                         mark_dirty ();
486                 }
487         }
488
489         if (reset) {
490                 maybe_signal_changed ();
491         }
492 }
493
494 void
495 AutomationList::erase_range (double start, double endt)
496 {
497         bool erased = false;
498
499         {
500                 Glib::Mutex::Lock lm (_lock);
501                 ControlEvent cp (start, 0.0f);
502                 iterator s;
503                 iterator e;
504
505                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) != _events.end()) {
506                         cp.when = endt;
507                         e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
508                         _events.erase (s, e);
509                         reposition_for_rt_add (0);
510                         erased = true;
511                         mark_dirty ();
512                 }
513                 
514         }
515
516         if (erased) {
517                 maybe_signal_changed ();
518         }
519 }
520
521 void
522 AutomationList::move_range (iterator start, iterator end, double xdelta, double ydelta)
523 {
524         /* note: we assume higher level logic is in place to avoid this
525            reordering the time-order of control events in the list. ie. all
526            points after end are later than (end)->when.
527         */
528
529         {
530                 Glib::Mutex::Lock lm (_lock);
531
532                 while (start != end) {
533                         (*start)->when += xdelta;
534                         (*start)->value += ydelta;
535                         if (isnan ((*start)->value)) {
536                                 abort ();
537                         }
538                         ++start;
539                 }
540
541                 if (!_frozen) {
542                         _events.sort (sort_events_by_time);
543                 } else {
544                         _sort_pending = true;
545                 }
546
547                 mark_dirty ();
548         }
549
550         maybe_signal_changed ();
551 }
552
553 void
554 AutomationList::slide (iterator before, double distance)
555 {
556         {
557                 Glib::Mutex::Lock lm (_lock);
558
559                 if (before == _events.end()) {
560                         return;
561                 }
562                 
563                 while (before != _events.end()) {
564                         (*before)->when += distance;
565                         ++before;
566                 }
567         }
568
569         maybe_signal_changed ();
570 }
571
572 void
573 AutomationList::modify (iterator iter, double when, double val)
574 {
575         /* note: we assume higher level logic is in place to avoid this
576            reordering the time-order of control events in the list. ie. all
577            points after *iter are later than when.
578         */
579
580         {
581                 Glib::Mutex::Lock lm (_lock);
582
583                 (*iter)->when = when;
584                 (*iter)->value = val;
585
586                 if (isnan (val)) {
587                         abort ();
588                 }
589
590                 if (!_frozen) {
591                         _events.sort (sort_events_by_time);
592                 } else {
593                         _sort_pending = true;
594                 }
595
596                 mark_dirty ();
597         }
598
599         maybe_signal_changed ();
600 }
601
602 std::pair<AutomationList::iterator,AutomationList::iterator>
603 AutomationList::control_points_adjacent (double xval)
604 {
605         Glib::Mutex::Lock lm (_lock);
606         iterator i;
607         ControlEvent cp (xval, 0.0f);
608         std::pair<iterator,iterator> ret;
609
610         ret.first = _events.end();
611         ret.second = _events.end();
612
613         for (i = lower_bound (_events.begin(), _events.end(), &cp, time_comparator); i != _events.end(); ++i) {
614                 
615                 if (ret.first == _events.end()) {
616                         if ((*i)->when >= xval) {
617                                 if (i != _events.begin()) {
618                                         ret.first = i;
619                                         --ret.first;
620                                 } else {
621                                         return ret;
622                                 }
623                         }
624                 } 
625                 
626                 if ((*i)->when > xval) {
627                         ret.second = i;
628                         break;
629                 }
630         }
631
632         return ret;
633 }
634
635 void
636 AutomationList::freeze ()
637 {
638         _frozen++;
639 }
640
641 void
642 AutomationList::thaw ()
643 {
644         if (_frozen == 0) {
645                 PBD::stacktrace (cerr);
646                 fatal << string_compose (_("programming error: %1"), X_("AutomationList::thaw() called while not frozen")) << endmsg;
647                 /*NOTREACHED*/
648         }
649
650         if (--_frozen > 0) {
651                 return;
652         }
653
654         {
655                 Glib::Mutex::Lock lm (_lock);
656
657                 if (_sort_pending) {
658                         _events.sort (sort_events_by_time);
659                         _sort_pending = false;
660                 }
661         }
662
663         if (_changed_when_thawed) {
664                 StateChanged(); /* EMIT SIGNAL */
665         }
666 }
667
668 void
669 AutomationList::set_max_xval (double x)
670 {
671         _max_xval = x;
672 }
673
674 void 
675 AutomationList::mark_dirty ()
676 {
677         _lookup_cache.left = -1;
678         _search_cache.left = -1;
679         Dirty (); /* EMIT SIGNAL */
680 }
681
682 void
683 AutomationList::truncate_end (double last_coordinate)
684 {
685         {
686                 Glib::Mutex::Lock lm (_lock);
687                 ControlEvent cp (last_coordinate, 0);
688                 list<ControlEvent*>::reverse_iterator i;
689                 double last_val;
690
691                 if (_events.empty()) {
692                         return;
693                 }
694
695                 if (last_coordinate == _events.back()->when) {
696                         return;
697                 }
698
699                 if (last_coordinate > _events.back()->when) {
700                         
701                         /* extending end:
702                         */
703
704                         iterator foo = _events.begin();
705                         bool lessthantwo;
706
707                         if (foo == _events.end()) {
708                                 lessthantwo = true;
709                         } else if (++foo == _events.end()) {
710                                 lessthantwo = true;
711                         } else {
712                                 lessthantwo = false;
713                         }
714
715                         if (lessthantwo) {
716                                 /* less than 2 points: add a new point */
717                                 _events.push_back (new ControlEvent (last_coordinate, _events.back()->value));
718                         } else {
719
720                                 /* more than 2 points: check to see if the last 2 values
721                                    are equal. if so, just move the position of the
722                                    last point. otherwise, add a new point.
723                                 */
724
725                                 iterator penultimate = _events.end();
726                                 --penultimate; /* points at last point */
727                                 --penultimate; /* points at the penultimate point */
728                                 
729                                 if (_events.back()->value == (*penultimate)->value) {
730                                         _events.back()->when = last_coordinate;
731                                 } else {
732                                         _events.push_back (new ControlEvent (last_coordinate, _events.back()->value));
733                                 }
734                         }
735
736                 } else {
737
738                         /* shortening end */
739
740                         last_val = unlocked_eval (last_coordinate);
741                         last_val = max ((double) _min_yval, last_val);
742                         last_val = min ((double) _max_yval, last_val);
743                         
744                         i = _events.rbegin();
745                         
746                         /* make i point to the last control point */
747                         
748                         ++i;
749                         
750                         /* now go backwards, removing control points that are
751                            beyond the new last coordinate.
752                         */
753
754                         uint32_t sz = _events.size();
755                         
756                         while (i != _events.rend() && sz > 2) {
757                                 list<ControlEvent*>::reverse_iterator tmp;
758                                 
759                                 tmp = i;
760                                 ++tmp;
761                                 
762                                 if ((*i)->when < last_coordinate) {
763                                         break;
764                                 }
765                                 
766                                 _events.erase (i.base());
767                                 --sz;
768
769                                 i = tmp;
770                         }
771                         
772                         _events.back()->when = last_coordinate;
773                         _events.back()->value = last_val;
774                 }
775
776                 reposition_for_rt_add (0);
777                 mark_dirty();
778         }
779
780         maybe_signal_changed ();
781 }
782
783 void
784 AutomationList::truncate_start (double overall_length)
785 {
786         {
787                 Glib::Mutex::Lock lm (_lock);
788                 iterator i;
789                 double first_legal_value;
790                 double first_legal_coordinate;
791
792                 if (_events.empty()) {
793                         fatal << _("programming error:")
794                               << "AutomationList::truncate_start() called on an empty list"
795                               << endmsg;
796                         /*NOTREACHED*/
797                         return;
798                 }
799                 
800                 if (overall_length == _events.back()->when) {
801                         /* no change in overall length */
802                         return;
803                 }
804                 
805                 if (overall_length > _events.back()->when) {
806                         
807                         /* growing at front: duplicate first point. shift all others */
808
809                         double shift = overall_length - _events.back()->when;
810                         uint32_t np;
811
812                         for (np = 0, i = _events.begin(); i != _events.end(); ++i, ++np) {
813                                 (*i)->when += shift;
814                         }
815
816                         if (np < 2) {
817
818                                 /* less than 2 points: add a new point */
819                                 _events.push_front (new ControlEvent (0, _events.front()->value));
820
821                         } else {
822
823                                 /* more than 2 points: check to see if the first 2 values
824                                    are equal. if so, just move the position of the
825                                    first point. otherwise, add a new point.
826                                 */
827
828                                 iterator second = _events.begin();
829                                 ++second; /* points at the second point */
830                                 
831                                 if (_events.front()->value == (*second)->value) {
832                                         /* first segment is flat, just move start point back to zero */
833                                         _events.front()->when = 0;
834                                 } else {
835                                         /* leave non-flat segment in place, add a new leading point. */
836                                         _events.push_front (new ControlEvent (0, _events.front()->value));
837                                 }
838                         }
839
840                 } else {
841
842                         /* shrinking at front */
843                         
844                         first_legal_coordinate = _events.back()->when - overall_length;
845                         first_legal_value = unlocked_eval (first_legal_coordinate);
846                         first_legal_value = max (_min_yval, first_legal_value);
847                         first_legal_value = min (_max_yval, first_legal_value);
848
849                         /* remove all events earlier than the new "front" */
850
851                         i = _events.begin();
852                         
853                         while (i != _events.end() && !_events.empty()) {
854                                 list<ControlEvent*>::iterator tmp;
855                                 
856                                 tmp = i;
857                                 ++tmp;
858                                 
859                                 if ((*i)->when > first_legal_coordinate) {
860                                         break;
861                                 }
862                                 
863                                 _events.erase (i);
864                                 
865                                 i = tmp;
866                         }
867                         
868
869                         /* shift all remaining points left to keep their same
870                            relative position
871                         */
872                         
873                         for (i = _events.begin(); i != _events.end(); ++i) {
874                                 (*i)->when -= first_legal_coordinate;
875                         }
876
877                         /* add a new point for the interpolated new value */
878                         
879                         _events.push_front (new ControlEvent (0, first_legal_value));
880                 }           
881
882                 reposition_for_rt_add (0);
883
884                 mark_dirty();
885         }
886
887         maybe_signal_changed ();
888 }
889
890 double
891 AutomationList::unlocked_eval (double x) const
892 {
893         pair<EventList::iterator,EventList::iterator> range;
894         int32_t npoints;
895         double lpos, upos;
896         double lval, uval;
897         double fraction;
898
899         npoints = _events.size();
900
901         switch (npoints) {
902         case 0:
903                 return _default_value;
904
905         case 1:
906                 if (x >= _events.front()->when) {
907                         return _events.front()->value;
908                 } else {
909                         // return _default_value;
910                         return _events.front()->value;
911                 } 
912                 
913         case 2:
914                 if (x >= _events.back()->when) {
915                         return _events.back()->value;
916                 } else if (x == _events.front()->when) {
917                         return _events.front()->value;
918                 } else if (x < _events.front()->when) {
919                         // return _default_value;
920                         return _events.front()->value;
921                 }
922
923                 lpos = _events.front()->when;
924                 lval = _events.front()->value;
925                 upos = _events.back()->when;
926                 uval = _events.back()->value;
927                 
928                 if (_interpolation == Discrete)
929                         return lval;
930
931                 /* linear interpolation betweeen the two points
932                 */
933
934                 fraction = (double) (x - lpos) / (double) (upos - lpos);
935                 return lval + (fraction * (uval - lval));
936
937         default:
938
939                 if (x >= _events.back()->when) {
940                         return _events.back()->value;
941                 } else if (x == _events.front()->when) {
942                         return _events.front()->value;
943                 } else if (x < _events.front()->when) {
944                         // return _default_value;
945                         return _events.front()->value;
946                 }
947
948                 return multipoint_eval (x);
949                 break;
950         }
951 }
952
953 double
954 AutomationList::multipoint_eval (double x) const
955 {
956         double upos, lpos;
957         double uval, lval;
958         double fraction;
959         
960         /* "Stepped" lookup (no interpolation) */
961         /* FIXME: no cache.  significant? */
962         if (_interpolation == Discrete) {
963                 const ControlEvent cp (x, 0);
964                 EventList::const_iterator i = lower_bound (_events.begin(), _events.end(), &cp, time_comparator);
965
966                 // shouldn't have made it to multipoint_eval
967                 assert(i != _events.end());
968
969                 if (i == _events.begin() || (*i)->when == x)
970                         return (*i)->value;
971                 else
972                         return (*(--i))->value;
973         }
974
975         /* Only do the range lookup if x is in a different range than last time
976          * this was called (or if the lookup cache has been marked "dirty" (left<0) */
977         if ((_lookup_cache.left < 0) ||
978             ((_lookup_cache.left > x) || 
979              (_lookup_cache.range.first == _events.end()) || 
980              ((*_lookup_cache.range.second)->when < x))) {
981
982                 const ControlEvent cp (x, 0);
983                 
984                 _lookup_cache.range = equal_range (_events.begin(), _events.end(), &cp, time_comparator);
985         }
986         
987         pair<const_iterator,const_iterator> range = _lookup_cache.range;
988
989         if (range.first == range.second) {
990
991                 /* x does not exist within the list as a control point */
992
993                 _lookup_cache.left = x;
994
995                 if (range.first != _events.begin()) {
996                         --range.first;
997                         lpos = (*range.first)->when;
998                         lval = (*range.first)->value;
999                 }  else {
1000                         /* we're before the first point */
1001                         // return _default_value;
1002                         return _events.front()->value;
1003                 }
1004                 
1005                 if (range.second == _events.end()) {
1006                         /* we're after the last point */
1007                         return _events.back()->value;
1008                 }
1009
1010                 upos = (*range.second)->when;
1011                 uval = (*range.second)->value;
1012                 
1013                 /* linear interpolation betweeen the two points
1014                    on either side of x
1015                 */
1016
1017                 fraction = (double) (x - lpos) / (double) (upos - lpos);
1018                 return lval + (fraction * (uval - lval));
1019
1020         } 
1021
1022         /* x is a control point in the data */
1023         _lookup_cache.left = -1;
1024         return (*range.first)->value;
1025 }
1026
1027 void
1028 AutomationList::build_search_cache_if_necessary(double start, double end) const
1029 {
1030         /* Only do the range lookup if x is in a different range than last time
1031          * this was called (or if the search cache has been marked "dirty" (left<0) */
1032         if ((_search_cache.left < 0) ||
1033                         ((_search_cache.left > start) ||
1034                          (_search_cache.right < end))) {
1035
1036                 const ControlEvent start_point (start, 0);
1037                 const ControlEvent end_point (end, 0);
1038
1039                 //cerr << "REBUILD: (" << _search_cache.left << ".." << _search_cache.right << ") -> ("
1040                 //      << start << ".." << end << ")" << endl;
1041
1042                 _search_cache.range.first = lower_bound (_events.begin(), _events.end(), &start_point, time_comparator);
1043                 _search_cache.range.second = upper_bound (_events.begin(), _events.end(), &end_point, time_comparator);
1044
1045                 _search_cache.left = start;
1046                 _search_cache.right = end;
1047         }
1048 }
1049
1050 /** Get the earliest event between \a start and \a end, using the current interpolation style.
1051  *
1052  * If an event is found, \a x and \a y are set to its coordinates.
1053  * \return true if event is found (and \a x and \a y are valid).
1054  */
1055 bool
1056 AutomationList::rt_safe_earliest_event(double start, double end, double& x, double& y) const
1057 {
1058         if (_interpolation == Discrete)
1059                 return rt_safe_earliest_event_discrete(start, end, x, y);
1060         else
1061                 return rt_safe_earliest_event_linear(start, end, x, y);
1062
1063
1064 /** Get the earliest event between \a start and \a end (Discrete (lack of) interpolation)
1065  *
1066  * If an event is found, \a x and \a y are set to its coordinates.
1067  * \return true if event is found (and \a x and \a y are valid).
1068  */
1069 bool
1070 AutomationList::rt_safe_earliest_event_discrete (double start, double end, double& x, double& y) const
1071 {
1072         // FIXME: It would be nice if this was unnecessary..
1073         Glib::Mutex::Lock lm(_lock, Glib::TRY_LOCK);
1074         if (!lm.locked()) {
1075                 return false;
1076         }
1077         
1078         build_search_cache_if_necessary(start, end);
1079
1080         pair<const_iterator,const_iterator> range = _search_cache.range;
1081
1082         if (range.first != _events.end()) {
1083                 const ControlEvent* const first = *range.first;
1084
1085                 /* Earliest points is in range, return it */
1086                 if (first->when >= start && first->when < end) {
1087
1088                         x = first->when;
1089                         y = first->value;
1090
1091                         /* Move left of cache to this point
1092                          * (Optimize for immediate call this cycle within range) */
1093                         _search_cache.left = x;
1094                         ++_search_cache.range.first;
1095
1096                         assert(x >= start);
1097                         assert(x < end);
1098                         return true;
1099
1100                 } else {
1101                                 
1102                         return false;
1103                 }
1104         
1105         /* No points in range */
1106         } else {
1107                 return false;
1108         }
1109 }
1110
1111 /** Get the earliest time the line crosses an integer (Linear interpolation).
1112  *
1113  * If an event is found, \a x and \a y are set to its coordinates.
1114  * \return true if event is found (and \a x and \a y are valid).
1115  */
1116 bool
1117 AutomationList::rt_safe_earliest_event_linear (double start, double end, double& x, double& y) const
1118 {
1119         // FIXME: It would be nice if this was unnecessary..
1120         Glib::Mutex::Lock lm(_lock, Glib::TRY_LOCK);
1121         if (!lm.locked()) {
1122                 return false;
1123         }
1124
1125         if (_events.size() < 2)
1126                 return false;
1127
1128         build_search_cache_if_necessary(start, end);
1129         
1130         pair<const_iterator,const_iterator> range = _search_cache.range;
1131
1132         if (range.first != _events.end()) {
1133
1134                 const ControlEvent* first = NULL;
1135                 const ControlEvent* next = NULL;
1136
1137                 /* Step is after first */
1138                 if (range.first == _events.begin() || (*range.first)->when == start) {
1139                         first = *range.first;
1140                         next = *(++range.first);
1141
1142                 /* Step is before first */
1143                 } else {
1144                         const_iterator prev = range.first;
1145                         --prev;
1146                         first = *prev;
1147                         next = *range.first;
1148                 }
1149                 
1150                 if (first->when == start) {
1151                         x = start;
1152                         y = first->value;
1153                         /* Move left of cache to this point
1154                          * (Optimize for immediate call this cycle within range) */
1155                         _search_cache.left = x;
1156                         ++_search_cache.range.first;
1157                         return true;
1158                 }
1159
1160                 /*cerr << first->value << " @ " << first->when << " ---> "
1161                                 << next->value << " @ " << next->when << endl;*/
1162
1163                 const double slope = (next->value - first->value) / (double)(next->when - first->when);
1164
1165                 const double start_y = first->value + (slope * (start - first->when));
1166                 //cerr << "start y: " << start_y << endl;
1167
1168                 if (start_y >= first->value) {
1169                         x = first->when + ((ceil(start_y) - first->value) / (double)slope);
1170                         y = ceil(start_y);
1171                 } else {
1172                         x = first->when + ((floor(start_y) - first->value) / (double)slope);
1173                         y = floor(start_y);
1174                 }
1175
1176                 if (x >= start && x < end) {
1177                         //cerr << y << " @ " << x << endl;
1178
1179                         x = floor(x);
1180
1181                         /* Move left of cache to this point
1182                          * (Optimize for immediate call this cycle within range) */
1183                         _search_cache.left = x;
1184                         
1185                         if (x >= next->when)
1186                                 ++_search_cache.range.first;
1187
1188                         return true;
1189
1190                 } else {
1191                         //cerr << "\tNo: " << start_y << ", " << x << endl;
1192                         return false;
1193                 }
1194         
1195         /* No points in the future, so no steps (towards them) in the future */
1196         } else {
1197                 return false;
1198         }
1199 }
1200
1201 AutomationList*
1202 AutomationList::cut (iterator start, iterator end)
1203 {
1204         AutomationList* nal = new AutomationList (_parameter, _min_yval, _max_yval, _default_value);
1205
1206         {
1207                 Glib::Mutex::Lock lm (_lock);
1208
1209                 for (iterator x = start; x != end; ) {
1210                         iterator tmp;
1211                         
1212                         tmp = x;
1213                         ++tmp;
1214                         
1215                         nal->_events.push_back (new ControlEvent (**x));
1216                         _events.erase (x);
1217                         
1218                         reposition_for_rt_add (0);
1219
1220                         x = tmp;
1221                 }
1222
1223                 mark_dirty ();
1224         }
1225
1226         maybe_signal_changed ();
1227
1228         return nal;
1229 }
1230
1231 AutomationList*
1232 AutomationList::cut_copy_clear (double start, double end, int op)
1233 {
1234         AutomationList* nal = new AutomationList (_parameter, _min_yval, _max_yval, _default_value);
1235         iterator s, e;
1236         ControlEvent cp (start, 0.0);
1237         bool changed = false;
1238         
1239         {
1240                 Glib::Mutex::Lock lm (_lock);
1241
1242                 if ((s = lower_bound (_events.begin(), _events.end(), &cp, time_comparator)) == _events.end()) {
1243                         return nal;
1244                 }
1245
1246                 cp.when = end;
1247                 e = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
1248
1249                 if (op != 2 && (*s)->when != start) {
1250                         nal->_events.push_back (new ControlEvent (0, unlocked_eval (start)));
1251                 }
1252
1253                 for (iterator x = s; x != e; ) {
1254                         iterator tmp;
1255                         
1256                         tmp = x;
1257                         ++tmp;
1258
1259                         changed = true;
1260                         
1261                         /* adjust new points to be relative to start, which
1262                            has been set to zero.
1263                         */
1264                         
1265                         if (op != 2) {
1266                                 nal->_events.push_back (new ControlEvent ((*x)->when - start, (*x)->value));
1267                         }
1268
1269                         if (op != 1) {
1270                                 _events.erase (x);
1271                         }
1272                         
1273                         x = tmp;
1274                 }
1275
1276                 if (op != 2 && nal->_events.back()->when != end - start) {
1277                         nal->_events.push_back (new ControlEvent (end - start, unlocked_eval (end)));
1278                 }
1279
1280                 if (changed) {
1281                         reposition_for_rt_add (0);
1282                 }
1283
1284                 mark_dirty ();
1285         }
1286
1287         maybe_signal_changed ();
1288
1289         return nal;
1290
1291 }
1292
1293 AutomationList*
1294 AutomationList::copy (iterator start, iterator end)
1295 {
1296         AutomationList* nal = new AutomationList (_parameter, _min_yval, _max_yval, _default_value);
1297
1298         {
1299                 Glib::Mutex::Lock lm (_lock);
1300                 
1301                 for (iterator x = start; x != end; ) {
1302                         iterator tmp;
1303                         
1304                         tmp = x;
1305                         ++tmp;
1306                         
1307                         nal->_events.push_back (new ControlEvent (**x));
1308                         
1309                         x = tmp;
1310                 }
1311         }
1312
1313         return nal;
1314 }
1315
1316 AutomationList*
1317 AutomationList::cut (double start, double end)
1318 {
1319         return cut_copy_clear (start, end, 0);
1320 }
1321
1322 AutomationList*
1323 AutomationList::copy (double start, double end)
1324 {
1325         return cut_copy_clear (start, end, 1);
1326 }
1327
1328 void
1329 AutomationList::clear (double start, double end)
1330 {
1331         (void) cut_copy_clear (start, end, 2);
1332 }
1333
1334 bool
1335 AutomationList::paste (AutomationList& alist, double pos, float times)
1336 {
1337         if (alist._events.empty()) {
1338                 return false;
1339         }
1340
1341         {
1342                 Glib::Mutex::Lock lm (_lock);
1343                 iterator where;
1344                 iterator prev;
1345                 double end = 0;
1346                 ControlEvent cp (pos, 0.0);
1347
1348                 where = upper_bound (_events.begin(), _events.end(), &cp, time_comparator);
1349
1350                 for (iterator i = alist.begin();i != alist.end(); ++i) {
1351                         _events.insert (where, new ControlEvent( (*i)->when+pos,( *i)->value));
1352                         end = (*i)->when + pos;
1353                 }
1354         
1355         
1356                 /* move all  points after the insertion along the timeline by 
1357                    the correct amount.
1358                 */
1359
1360                 while (where != _events.end()) {
1361                         iterator tmp;
1362                         if ((*where)->when <= end) {
1363                                 tmp = where;
1364                                 ++tmp;
1365                                 _events.erase(where);
1366                                 where = tmp;
1367
1368                         } else {
1369                                 break;
1370                         }
1371                 }
1372
1373                 reposition_for_rt_add (0);
1374                 mark_dirty ();
1375         }
1376
1377         maybe_signal_changed ();
1378         return true;
1379 }
1380
1381 XMLNode&
1382 AutomationList::get_state ()
1383 {
1384         return state (true);
1385 }
1386
1387 XMLNode&
1388 AutomationList::state (bool full)
1389 {
1390         XMLNode* root = new XMLNode (X_("AutomationList"));
1391         char buf[64];
1392         LocaleGuard lg (X_("POSIX"));
1393
1394         root->add_property ("automation-id", _parameter.to_string());
1395
1396         root->add_property ("id", _id.to_s());
1397
1398         snprintf (buf, sizeof (buf), "%.12g", _default_value);
1399         root->add_property ("default", buf);
1400         snprintf (buf, sizeof (buf), "%.12g", _min_yval);
1401         root->add_property ("min_yval", buf);
1402         snprintf (buf, sizeof (buf), "%.12g", _max_yval);
1403         root->add_property ("max_yval", buf);
1404         snprintf (buf, sizeof (buf), "%.12g", _max_xval);
1405         root->add_property ("max_xval", buf);
1406         
1407         root->add_property ("interpolation-style", enum_2_string (_interpolation));
1408
1409         if (full) {
1410                 root->add_property ("state", auto_state_to_string (_state));
1411         } else {
1412                 /* never save anything but Off for automation state to a template */
1413                 root->add_property ("state", auto_state_to_string (Off));
1414         }
1415
1416         root->add_property ("style", auto_style_to_string (_style));
1417
1418         if (!_events.empty()) {
1419                 root->add_child_nocopy (serialize_events());
1420         }
1421
1422         return *root;
1423 }
1424
1425 XMLNode&
1426 AutomationList::serialize_events ()
1427 {
1428         XMLNode* node = new XMLNode (X_("events"));
1429         stringstream str;
1430
1431         for (iterator xx = _events.begin(); xx != _events.end(); ++xx) {
1432                 str << (double) (*xx)->when;
1433                 str << ' ';
1434                 str <<(double) (*xx)->value;
1435                 str << '\n';
1436         }
1437
1438         /* XML is a bit wierd */
1439
1440         XMLNode* content_node = new XMLNode (X_("foo")); /* it gets renamed by libxml when we set content */
1441         content_node->set_content (str.str());
1442
1443         node->add_child_nocopy (*content_node);
1444
1445         return *node;
1446 }
1447
1448 int
1449 AutomationList::deserialize_events (const XMLNode& node)
1450 {
1451         if (node.children().empty()) {
1452                 return -1;
1453         }
1454
1455         XMLNode* content_node = node.children().front();
1456
1457         if (content_node->content().empty()) {
1458                 return -1;
1459         }
1460
1461         freeze ();
1462         clear ();
1463         
1464         stringstream str (content_node->content());
1465         
1466         double x;
1467         double y;
1468         bool ok = true;
1469         
1470         while (str) {
1471                 str >> x;
1472                 if (!str) {
1473                         break;
1474                 }
1475                 str >> y;
1476                 if (!str) {
1477                         ok = false;
1478                         break;
1479                 }
1480                 fast_simple_add (x, y);
1481         }
1482         
1483         if (!ok) {
1484                 clear ();
1485                 error << _("automation list: cannot load coordinates from XML, all points ignored") << endmsg;
1486         } else {
1487                 mark_dirty ();
1488                 reposition_for_rt_add (0);
1489                 maybe_signal_changed ();
1490         }
1491
1492         thaw ();
1493
1494         return 0;
1495 }
1496
1497 int
1498 AutomationList::set_state (const XMLNode& node)
1499 {
1500         XMLNodeList nlist = node.children();
1501         XMLNode* nsos;
1502         XMLNodeIterator niter;
1503         const XMLProperty* prop;
1504
1505         if (node.name() == X_("events")) {
1506                 /* partial state setting*/
1507                 return deserialize_events (node);
1508         }
1509         
1510         if (node.name() == X_("Envelope") || node.name() == X_("FadeOut") || node.name() == X_("FadeIn")) {
1511
1512                 if ((nsos = node.child (X_("AutomationList")))) {
1513                         /* new school in old school clothing */
1514                         return set_state (*nsos);
1515                 }
1516
1517                 /* old school */
1518
1519                 const XMLNodeList& elist = node.children();
1520                 XMLNodeConstIterator i;
1521                 XMLProperty* prop;
1522                 nframes_t x;
1523                 double y;
1524                 
1525                 freeze ();
1526                 clear ();
1527                 
1528                 for (i = elist.begin(); i != elist.end(); ++i) {
1529                         
1530                         if ((prop = (*i)->property ("x")) == 0) {
1531                                 error << _("automation list: no x-coordinate stored for control point (point ignored)") << endmsg;
1532                                 continue;
1533                         }
1534                         x = atoi (prop->value().c_str());
1535                         
1536                         if ((prop = (*i)->property ("y")) == 0) {
1537                                 error << _("automation list: no y-coordinate stored for control point (point ignored)") << endmsg;
1538                                 continue;
1539                         }
1540                         y = atof (prop->value().c_str());
1541                         
1542                         fast_simple_add (x, y);
1543                 }
1544                 
1545                 thaw ();
1546
1547                 return 0;
1548         }
1549
1550         if (node.name() != X_("AutomationList") ) {
1551                 error << string_compose (_("AutomationList: passed XML node called %1, not \"AutomationList\" - ignored"), node.name()) << endmsg;
1552                 return -1;
1553         }
1554
1555         if ((prop = node.property ("id")) != 0) {
1556                 _id = prop->value ();
1557                 /* update session AL list */
1558                 AutomationListCreated(this);
1559         }
1560         
1561         if ((prop = node.property (X_("automation-id"))) != 0){ 
1562                 _parameter = Parameter(prop->value());
1563         } else {
1564                 warning << "Legacy session: automation list has no automation-id property.";
1565         }
1566         
1567         if ((prop = node.property (X_("interpolation-style"))) != 0) {
1568                 _interpolation = (InterpolationStyle)string_2_enum(prop->value(), _interpolation);
1569         } else {
1570                 _interpolation = Linear;
1571         }
1572         
1573         if ((prop = node.property (X_("default"))) != 0){ 
1574                 _default_value = atof (prop->value().c_str());
1575         } else {
1576                 _default_value = 0.0;
1577         }
1578
1579         if ((prop = node.property (X_("style"))) != 0) {
1580                 _style = string_to_auto_style (prop->value());
1581         } else {
1582                 _style = Absolute;
1583         }
1584
1585         if ((prop = node.property (X_("state"))) != 0) {
1586                 _state = string_to_auto_state (prop->value());
1587         } else {
1588                 _state = Off;
1589         }
1590
1591         if ((prop = node.property (X_("min_yval"))) != 0) {
1592                 _min_yval = atof (prop->value ().c_str());
1593         } else {
1594                 _min_yval = FLT_MIN;
1595         }
1596
1597         if ((prop = node.property (X_("max_yval"))) != 0) {
1598                 _max_yval = atof (prop->value ().c_str());
1599         } else {
1600                 _max_yval = FLT_MAX;
1601         }
1602
1603         if ((prop = node.property (X_("max_xval"))) != 0) {
1604                 _max_xval = atof (prop->value ().c_str());
1605         } else {
1606                 _max_xval = 0; // means "no limit ;
1607         }
1608
1609         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1610                 if ((*niter)->name() == X_("events")) {
1611                         deserialize_events (*(*niter));
1612                 }
1613         }
1614
1615         return 0;
1616 }
1617