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