major fixes to automation editing
[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     $Id$
19 */
20
21 #include <set>
22 #include <climits>
23 #include <float.h>
24 #include <cmath>
25 #include <sstream>
26 #include <algorithm>
27 #include <sigc++/bind.h>
28 #include <ardour/automation_event.h>
29
30 #include "i18n.h"
31
32 using namespace std;
33 using namespace ARDOUR;
34 using namespace sigc;
35 using namespace PBD;
36
37 sigc::signal<void,AutomationList *> AutomationList::AutomationListCreated;
38
39 static bool sort_events_by_time (ControlEvent* a, ControlEvent* b)
40 {
41         return a->when < b->when;
42 }
43
44 #if 0
45 static void dumpit (const AutomationList& al, string prefix = "")
46 {
47         cerr << prefix << &al << endl;
48         for (AutomationList::const_iterator i = al.const_begin(); i != al.const_end(); ++i) {
49                 cerr << prefix << '\t' << (*i)->when << ',' << (*i)->value << endl;
50         }
51         cerr << "\n";
52 }
53 #endif
54
55 AutomationList::AutomationList (double defval)
56 {
57         _frozen = 0;
58         changed_when_thawed = false;
59         _state = Off;
60         _style = Absolute;
61         _touching = false;
62         min_yval = FLT_MIN;
63         max_yval = FLT_MAX;
64         max_xval = 0; // means "no limit" 
65         default_value = defval;
66         _dirty = false;
67         rt_insertion_point = events.end();
68         lookup_cache.left = -1;
69         lookup_cache.range.first = events.end();
70         sort_pending = false;
71
72         AutomationListCreated(this);
73 }
74
75 AutomationList::AutomationList (const AutomationList& other)
76 {
77         _frozen = 0;
78         changed_when_thawed = false;
79         _style = other._style;
80         min_yval = other.min_yval;
81         max_yval = other.max_yval;
82         max_xval = other.max_xval;
83         default_value = other.default_value;
84         _state = other._state;
85         _touching = other._touching;
86         _dirty = false;
87         rt_insertion_point = events.end();
88         lookup_cache.left = -1;
89         lookup_cache.range.first = events.end();
90         sort_pending = false;
91
92         for (const_iterator i = other.events.begin(); i != other.events.end(); ++i) {
93                 /* we have to use other point_factory() because
94                    its virtual and we're in a constructor.
95                 */
96                 events.push_back (other.point_factory (**i));
97         }
98
99         mark_dirty ();
100         AutomationListCreated(this);
101 }
102
103 AutomationList::AutomationList (const AutomationList& other, double start, double end)
104 {
105         _frozen = 0;
106         changed_when_thawed = false;
107         _style = other._style;
108         min_yval = other.min_yval;
109         max_yval = other.max_yval;
110         max_xval = other.max_xval;
111         default_value = other.default_value;
112         _state = other._state;
113         _touching = other._touching;
114         _dirty = false;
115         rt_insertion_point = events.end();
116         lookup_cache.left = -1;
117         lookup_cache.range.first = events.end();
118         sort_pending = false;
119
120         /* now grab the relevant points, and shift them back if necessary */
121
122         AutomationList* section = const_cast<AutomationList*>(&other)->copy (start, end);
123
124         if (!section->empty()) {
125                 for (AutomationList::iterator i = section->begin(); i != section->end(); ++i) {
126                         events.push_back (other.point_factory ((*i)->when, (*i)->value));
127                 }
128         }
129
130         delete section;
131
132         mark_dirty ();
133
134         AutomationListCreated(this);
135 }
136
137 AutomationList::AutomationList (const XMLNode& node)
138 {
139         _frozen = 0;
140         changed_when_thawed = false;
141         _touching = false;
142         min_yval = FLT_MIN;
143         max_yval = FLT_MAX;
144         max_xval = 0; // means "no limit" 
145         _dirty = false;
146         _state = Off;
147         _style = Absolute;
148         rt_insertion_point = events.end();
149         lookup_cache.left = -1;
150         lookup_cache.range.first = events.end();
151         sort_pending = false;
152         
153         set_state (node);
154
155         AutomationListCreated(this);
156 }
157
158 AutomationList::~AutomationList()
159 {
160         GoingAway ();
161         
162         for (AutomationEventList::iterator x = events.begin(); x != events.end(); ++x) {
163                 delete (*x);
164         }
165 }
166
167 bool
168 AutomationList::operator== (const AutomationList& other)
169 {
170         return events == other.events;
171 }
172
173 AutomationList&
174 AutomationList::operator= (const AutomationList& other)
175 {
176         if (this != &other) {
177                 
178                 events.clear ();
179                 
180                 for (const_iterator i = other.events.begin(); i != other.events.end(); ++i) {
181                         events.push_back (point_factory (**i));
182                 }
183                 
184                 min_yval = other.min_yval;
185                 max_yval = other.max_yval;
186                 max_xval = other.max_xval;
187                 default_value = other.default_value;
188                 
189                 mark_dirty ();
190                 maybe_signal_changed ();
191         }
192
193         return *this;
194 }
195
196 void
197 AutomationList::maybe_signal_changed ()
198 {
199         mark_dirty ();
200
201         if (_frozen) {
202                 changed_when_thawed = true;
203         } else {
204                 StateChanged ();
205         }
206 }
207
208 void
209 AutomationList::set_automation_state (AutoState s)
210 {
211         if (s != _state) {
212                 _state = s;
213                 automation_state_changed (); /* EMIT SIGNAL */
214         }
215 }
216
217 void
218 AutomationList::set_automation_style (AutoStyle s)
219 {
220         if (s != _style) {
221                 _style = s;
222                 automation_style_changed (); /* EMIT SIGNAL */
223         }
224 }
225
226 void
227 AutomationList::start_touch ()
228 {
229         _touching = true;
230         _new_touch = true;
231 }
232
233 void
234 AutomationList::stop_touch ()
235 {
236         _touching = false;
237         _new_touch = false;
238 }
239
240 void
241 AutomationList::clear ()
242 {
243         {
244                 Glib::Mutex::Lock lm (lock);
245                 events.clear ();
246                 mark_dirty ();
247         }
248
249         maybe_signal_changed ();
250 }
251
252 void
253 AutomationList::x_scale (double factor)
254 {
255         Glib::Mutex::Lock lm (lock);
256         _x_scale (factor);
257 }
258
259 bool
260 AutomationList::extend_to (double when)
261 {
262         Glib::Mutex::Lock lm (lock);
263         if (events.empty() || events.back()->when == when) {
264                 return false;
265         }
266         double factor = when / events.back()->when;
267         _x_scale (factor);
268         return true;
269 }
270
271 void AutomationList::_x_scale (double factor)
272 {
273         for (AutomationList::iterator i = events.begin(); i != events.end(); ++i) {
274                 (*i)->when = floor ((*i)->when * factor);
275         }
276
277         mark_dirty ();
278 }
279
280 void
281 AutomationList::reposition_for_rt_add (double when)
282 {
283         rt_insertion_point = events.end();
284 }
285
286 #define last_rt_insertion_point rt_insertion_point
287
288 void
289 AutomationList::rt_add (double when, double value)
290 {
291         /* this is for automation recording */
292
293         if ((_state & Touch) && !_touching) {
294                 return;
295         }
296
297         // cerr << "RT: alist @ " << this << " add " << value << " @ " << when << endl;
298
299         {
300                 Glib::Mutex::Lock lm (lock);
301
302                 iterator where;
303                 TimeComparator cmp;
304                 ControlEvent cp (when, 0.0);
305                 bool done = false;
306
307                 if ((last_rt_insertion_point != events.end()) && ((*last_rt_insertion_point)->when < when) ) {
308
309                         /* we have a previous insertion point, so we should delete
310                            everything between it and the position where we are going
311                            to insert this point.
312                         */
313
314                         iterator after = last_rt_insertion_point;
315
316                         if (++after != events.end()) {
317                                 iterator far = after;
318
319                                 while (far != events.end()) {
320                                         if ((*far)->when > when) {
321                                                 break;
322                                         }
323                                         ++far;
324                                 }
325
326                                 if(_new_touch) {
327                                         where = far;
328                                         last_rt_insertion_point = where;
329                                                                                              
330                                         if((*where)->when == when) {
331                                                 (*where)->value = value;
332                                                 done = true;
333                                         }
334                                 } else {
335                                         where = events.erase (after, far);
336                                 }
337
338                         } else {
339
340                                 where = after;
341
342                         }
343                         
344                         iterator previous = last_rt_insertion_point;
345                         --previous;
346                         
347                         if (last_rt_insertion_point != events.begin() && (*last_rt_insertion_point)->value == value && (*previous)->value == value) {
348                                 (*last_rt_insertion_point)->when = when;
349                                 done = true;
350                                 
351                         }
352                         
353                 } else {
354
355                         where = lower_bound (events.begin(), events.end(), &cp, cmp);
356
357                         if (where != events.end()) {
358                                 if ((*where)->when == when) {
359                                         (*where)->value = value;
360                                         done = true;
361                                 }
362                         }
363                 }
364                 
365                 if (!done) {
366                         last_rt_insertion_point = events.insert (where, point_factory (when, value));
367                 }
368                 
369                 _new_touch = false;
370                 mark_dirty ();
371         }
372
373         maybe_signal_changed ();
374 }
375
376 void
377 AutomationList::fast_simple_add (double when, double value)
378 {
379         /* to be used only for loading pre-sorted data from saved state */
380         events.insert (events.end(), point_factory (when, value));
381 }
382
383 #undef last_rt_insertion_point
384
385 void
386 AutomationList::add (double when, double value)
387 {
388         /* this is for graphical editing */
389
390         {
391                 Glib::Mutex::Lock lm (lock);
392                 TimeComparator cmp;
393                 ControlEvent cp (when, 0.0f);
394                 bool insert = true;
395                 iterator insertion_point;
396
397                 for (insertion_point = lower_bound (events.begin(), events.end(), &cp, cmp); insertion_point != events.end(); ++insertion_point) {
398
399                         /* only one point allowed per time point */
400
401                         if ((*insertion_point)->when == when) {
402                                 (*insertion_point)->value = value;
403                                 insert = false;
404                                 break;
405                         } 
406
407                         if ((*insertion_point)->when >= when) {
408                                 break;
409                         }
410                 }
411
412                 if (insert) {
413                         
414                         events.insert (insertion_point, point_factory (when, value));
415                         reposition_for_rt_add (0);
416
417                 } 
418
419                 mark_dirty ();
420         }
421
422         maybe_signal_changed ();
423 }
424
425 void
426 AutomationList::erase (AutomationList::iterator i)
427 {
428         {
429                 Glib::Mutex::Lock lm (lock);
430                 events.erase (i);
431                 reposition_for_rt_add (0);
432                 mark_dirty ();
433         }
434         maybe_signal_changed ();
435 }
436
437 void
438 AutomationList::erase (AutomationList::iterator start, AutomationList::iterator end)
439 {
440         {
441                 Glib::Mutex::Lock lm (lock);
442                 events.erase (start, end);
443                 reposition_for_rt_add (0);
444                 mark_dirty ();
445         }
446         maybe_signal_changed ();
447 }       
448
449 void
450 AutomationList::reset_range (double start, double endt)
451 {
452         bool reset = false;
453
454         {
455         Glib::Mutex::Lock lm (lock);
456                 TimeComparator cmp;
457                 ControlEvent cp (start, 0.0f);
458                 iterator s;
459                 iterator e;
460                 
461                 if ((s = lower_bound (events.begin(), events.end(), &cp, cmp)) != events.end()) {
462
463                         cp.when = endt;
464                         e = upper_bound (events.begin(), events.end(), &cp, cmp);
465
466                         for (iterator i = s; i != e; ++i) {
467                                 (*i)->value = default_value;
468                         }
469                         
470                         reset = true;
471
472                         mark_dirty ();
473                 }
474         }
475
476         if (reset) {
477                 maybe_signal_changed ();
478         }
479 }
480
481 void
482 AutomationList::erase_range (double start, double endt)
483 {
484         bool erased = false;
485
486         {
487                 Glib::Mutex::Lock lm (lock);
488                 TimeComparator cmp;
489                 ControlEvent cp (start, 0.0f);
490                 iterator s;
491                 iterator e;
492
493                 if ((s = lower_bound (events.begin(), events.end(), &cp, cmp)) != events.end()) {
494                         cp.when = endt;
495                         e = upper_bound (events.begin(), events.end(), &cp, cmp);
496                         events.erase (s, e);
497                         reposition_for_rt_add (0);
498                         erased = true;
499                         mark_dirty ();
500                 }
501                 
502         }
503
504         if (erased) {
505                 maybe_signal_changed ();
506         }
507 }
508
509 void
510 AutomationList::move_range (iterator start, iterator end, double xdelta, double ydelta)
511 {
512         /* note: we assume higher level logic is in place to avoid this
513            reordering the time-order of control events in the list. ie. all
514            points after end are later than (end)->when.
515         */
516
517         {
518                 Glib::Mutex::Lock lm (lock);
519
520                 while (start != end) {
521                         (*start)->when += xdelta;
522                         (*start)->value += ydelta;
523                         if (isnan ((*start)->value)) {
524                                 abort ();
525                         }
526                         ++start;
527                 }
528
529                 if (!_frozen) {
530                         events.sort (sort_events_by_time);
531                 } else {
532                         sort_pending = true;
533                 }
534
535                 mark_dirty ();
536         }
537
538         maybe_signal_changed ();
539 }
540
541 void
542 AutomationList::slide (iterator before, double distance)
543 {
544         {
545                 Glib::Mutex::Lock lm (lock);
546
547                 if (before == events.end()) {
548                         return;
549                 }
550                 
551                 while (before != events.end()) {
552                         (*before)->when += distance;
553                         ++before;
554                 }
555         }
556
557         maybe_signal_changed ();
558 }
559
560 void
561 AutomationList::modify (iterator iter, double when, double val)
562 {
563         /* note: we assume higher level logic is in place to avoid this
564            reordering the time-order of control events in the list. ie. all
565            points after *iter are later than when.
566         */
567
568         {
569                 Glib::Mutex::Lock lm (lock);
570
571                 (*iter)->when = when;
572                 (*iter)->value = val;
573
574                 if (isnan (val)) {
575                         abort ();
576                 }
577
578                 if (!_frozen) {
579                         events.sort (sort_events_by_time);
580                 } else {
581                         sort_pending = true;
582                 }
583
584                 mark_dirty ();
585         }
586
587         maybe_signal_changed ();
588 }
589
590 std::pair<AutomationList::iterator,AutomationList::iterator>
591 AutomationList::control_points_adjacent (double xval)
592 {
593         Glib::Mutex::Lock lm (lock);
594         iterator i;
595         TimeComparator cmp;
596         ControlEvent cp (xval, 0.0f);
597         std::pair<iterator,iterator> ret;
598
599         ret.first = events.end();
600         ret.second = events.end();
601
602         for (i = lower_bound (events.begin(), events.end(), &cp, cmp); i != events.end(); ++i) {
603                 
604                 if (ret.first == events.end()) {
605                         if ((*i)->when >= xval) {
606                                 if (i != events.begin()) {
607                                         ret.first = i;
608                                         --ret.first;
609                                 } else {
610                                         return ret;
611                                 }
612                         }
613                 } 
614                 
615                 if ((*i)->when > xval) {
616                         ret.second = i;
617                         break;
618                 }
619         }
620
621         return ret;
622 }
623
624 void
625 AutomationList::freeze ()
626 {
627         _frozen++;
628 }
629
630 void
631 AutomationList::thaw ()
632 {
633         if (_frozen == 0) {
634                 fatal << string_compose (_("programming error: %1"), X_("AutomationList::thaw() called while not frozen")) << endmsg;
635                 /*NOTREACHED*/
636         }
637
638         if (--_frozen > 0) {
639                 return;
640         }
641
642         {
643                 Glib::Mutex::Lock lm (lock);
644
645                 if (sort_pending) {
646                         events.sort (sort_events_by_time);
647                         sort_pending = false;
648                 }
649         }
650
651         if (changed_when_thawed) {
652                 StateChanged(); /* EMIT SIGNAL */
653         }
654 }
655
656 void
657 AutomationList::set_max_xval (double x)
658 {
659         max_xval = x;
660 }
661
662 void 
663 AutomationList::mark_dirty ()
664 {
665         lookup_cache.left = -1;
666         _dirty = true;
667 }
668
669 void
670 AutomationList::truncate_end (double last_coordinate)
671 {
672         {
673                 Glib::Mutex::Lock lm (lock);
674                 ControlEvent cp (last_coordinate, 0);
675                 list<ControlEvent*>::reverse_iterator i;
676                 double last_val;
677
678                 if (events.empty()) {
679                         return;
680                 }
681
682                 if (last_coordinate == events.back()->when) {
683                         return;
684                 }
685
686                 if (last_coordinate > events.back()->when) {
687                         
688                         /* extending end:
689                         */
690
691                         iterator foo = events.begin();
692                         bool lessthantwo;
693
694                         if (foo == events.end()) {
695                                 lessthantwo = true;
696                         } else if (++foo == events.end()) {
697                                 lessthantwo = true;
698                         } else {
699                                 lessthantwo = false;
700                         }
701
702                         if (lessthantwo) {
703                                 /* less than 2 points: add a new point */
704                                 events.push_back (point_factory (last_coordinate, events.back()->value));
705                         } else {
706
707                                 /* more than 2 points: check to see if the last 2 values
708                                    are equal. if so, just move the position of the
709                                    last point. otherwise, add a new point.
710                                 */
711
712                                 iterator penultimate = events.end();
713                                 --penultimate; /* points at last point */
714                                 --penultimate; /* points at the penultimate point */
715                                 
716                                 if (events.back()->value == (*penultimate)->value) {
717                                         events.back()->when = last_coordinate;
718                                 } else {
719                                         events.push_back (point_factory (last_coordinate, events.back()->value));
720                                 }
721                         }
722
723                 } else {
724
725                         /* shortening end */
726
727                         last_val = unlocked_eval (last_coordinate);
728                         last_val = max ((double) min_yval, last_val);
729                         last_val = min ((double) max_yval, last_val);
730                         
731                         i = events.rbegin();
732                         
733                         /* make i point to the last control point */
734                         
735                         ++i;
736                         
737                         /* now go backwards, removing control points that are
738                            beyond the new last coordinate.
739                         */
740
741                         uint32_t sz = events.size();
742                         
743                         while (i != events.rend() && sz > 2) {
744                                 list<ControlEvent*>::reverse_iterator tmp;
745                                 
746                                 tmp = i;
747                                 ++tmp;
748                                 
749                                 if ((*i)->when < last_coordinate) {
750                                         break;
751                                 }
752                                 
753                                 events.erase (i.base());
754                                 --sz;
755
756                                 i = tmp;
757                         }
758                         
759                         events.back()->when = last_coordinate;
760                         events.back()->value = last_val;
761                 }
762
763                 reposition_for_rt_add (0);
764                 mark_dirty();
765         }
766
767         maybe_signal_changed ();
768 }
769
770 void
771 AutomationList::truncate_start (double overall_length)
772 {
773         {
774                 Glib::Mutex::Lock lm (lock);
775                 AutomationList::iterator i;
776                 double first_legal_value;
777                 double first_legal_coordinate;
778
779                 if (events.empty()) {
780                         fatal << _("programming error:")
781                               << "AutomationList::truncate_start() called on an empty list"
782                               << endmsg;
783                         /*NOTREACHED*/
784                         return;
785                 }
786                 
787                 if (overall_length == events.back()->when) {
788                         /* no change in overall length */
789                         return;
790                 }
791                 
792                 if (overall_length > events.back()->when) {
793                         
794                         /* growing at front: duplicate first point. shift all others */
795
796                         double shift = overall_length - events.back()->when;
797                         uint32_t np;
798
799                         for (np = 0, i = events.begin(); i != events.end(); ++i, ++np) {
800                                 (*i)->when += shift;
801                         }
802
803                         if (np < 2) {
804
805                                 /* less than 2 points: add a new point */
806                                 events.push_front (point_factory (0, events.front()->value));
807
808                         } else {
809
810                                 /* more than 2 points: check to see if the first 2 values
811                                    are equal. if so, just move the position of the
812                                    first point. otherwise, add a new point.
813                                 */
814
815                                 iterator second = events.begin();
816                                 ++second; /* points at the second point */
817                                 
818                                 if (events.front()->value == (*second)->value) {
819                                         /* first segment is flat, just move start point back to zero */
820                                         events.front()->when = 0;
821                                 } else {
822                                         /* leave non-flat segment in place, add a new leading point. */
823                                         events.push_front (point_factory (0, events.front()->value));
824                                 }
825                         }
826
827                 } else {
828
829                         /* shrinking at front */
830                         
831                         first_legal_coordinate = events.back()->when - overall_length;
832                         first_legal_value = unlocked_eval (first_legal_coordinate);
833                         first_legal_value = max (min_yval, first_legal_value);
834                         first_legal_value = min (max_yval, first_legal_value);
835
836                         /* remove all events earlier than the new "front" */
837
838                         i = events.begin();
839                         
840                         while (i != events.end() && !events.empty()) {
841                                 list<ControlEvent*>::iterator tmp;
842                                 
843                                 tmp = i;
844                                 ++tmp;
845                                 
846                                 if ((*i)->when > first_legal_coordinate) {
847                                         break;
848                                 }
849                                 
850                                 events.erase (i);
851                                 
852                                 i = tmp;
853                         }
854                         
855
856                         /* shift all remaining points left to keep their same
857                            relative position
858                         */
859                         
860                         for (i = events.begin(); i != events.end(); ++i) {
861                                 (*i)->when -= first_legal_coordinate;
862                         }
863
864                         /* add a new point for the interpolated new value */
865                         
866                         events.push_front (point_factory (0, first_legal_value));
867                 }           
868
869                 reposition_for_rt_add (0);
870
871                 mark_dirty();
872         }
873
874         maybe_signal_changed ();
875 }
876
877 double
878 AutomationList::unlocked_eval (double x)
879 {
880         return shared_eval (x);
881 }
882
883 double
884 AutomationList::shared_eval (double x) 
885 {
886         pair<AutomationEventList::iterator,AutomationEventList::iterator> range;
887         int32_t npoints;
888         double lpos, upos;
889         double lval, uval;
890         double fraction;
891
892         npoints = events.size();
893
894         switch (npoints) {
895         case 0:
896                 return default_value;
897
898         case 1:
899                 if (x >= events.front()->when) {
900                         return events.front()->value;
901                 } else {
902                         // return default_value;
903                         return events.front()->value;
904                 } 
905                 
906         case 2:
907                 if (x >= events.back()->when) {
908                         return events.back()->value;
909                 } else if (x == events.front()->when) {
910                         return events.front()->value;
911                 } else if (x < events.front()->when) {
912                         // return default_value;
913                         return events.front()->value;
914                 }
915
916                 lpos = events.front()->when;
917                 lval = events.front()->value;
918                 upos = events.back()->when;
919                 uval = events.back()->value;
920                 
921                 /* linear interpolation betweeen the two points
922                 */
923
924                 fraction = (double) (x - lpos) / (double) (upos - lpos);
925                 return lval + (fraction * (uval - lval));
926
927         default:
928
929                 if (x >= events.back()->when) {
930                         return events.back()->value;
931                 } else if (x == events.front()->when) {
932                         return events.front()->value;
933                 } else if (x < events.front()->when) {
934                         // return default_value;
935                         return events.front()->value;
936                 }
937
938                 return multipoint_eval (x);
939                 break;
940         }
941 }
942
943 double
944 AutomationList::multipoint_eval (double x) 
945 {
946         pair<AutomationList::iterator,AutomationList::iterator> range;
947         double upos, lpos;
948         double uval, lval;
949         double fraction;
950
951         /* only do the range lookup if x is in a different range than last time
952            this was called (or if the lookup cache has been marked "dirty" (left<0)
953         */
954
955         if ((lookup_cache.left < 0) ||
956             ((lookup_cache.left > x) || 
957              (lookup_cache.range.first == events.end()) || 
958              ((*lookup_cache.range.second)->when < x))) {
959
960                 ControlEvent cp (x, 0);
961                 TimeComparator cmp;
962                 
963                 lookup_cache.range = equal_range (events.begin(), events.end(), &cp, cmp);
964         }
965         
966         range = lookup_cache.range;
967
968         if (range.first == range.second) {
969
970                 /* x does not exist within the list as a control point */
971
972                 lookup_cache.left = x;
973
974                 if (range.first != events.begin()) {
975                         --range.first;
976                         lpos = (*range.first)->when;
977                         lval = (*range.first)->value;
978                 }  else {
979                         /* we're before the first point */
980                         // return default_value;
981                         return events.front()->value;
982                 }
983                 
984                 if (range.second == events.end()) {
985                         /* we're after the last point */
986                         return events.back()->value;
987                 }
988
989                 upos = (*range.second)->when;
990                 uval = (*range.second)->value;
991                 
992                 /* linear interpolation betweeen the two points
993                    on either side of x
994                 */
995
996                 fraction = (double) (x - lpos) / (double) (upos - lpos);
997                 return lval + (fraction * (uval - lval));
998
999         } 
1000
1001         /* x is a control point in the data */
1002         lookup_cache.left = -1;
1003         return (*range.first)->value;
1004 }
1005
1006 AutomationList*
1007 AutomationList::cut (iterator start, iterator end)
1008 {
1009         AutomationList* nal = new AutomationList (default_value);
1010
1011         {
1012                 Glib::Mutex::Lock lm (lock);
1013
1014                 for (iterator x = start; x != end; ) {
1015                         iterator tmp;
1016                         
1017                         tmp = x;
1018                         ++tmp;
1019                         
1020                         nal->events.push_back (point_factory (**x));
1021                         events.erase (x);
1022                         
1023                         reposition_for_rt_add (0);
1024
1025                         x = tmp;
1026                 }
1027
1028                 mark_dirty ();
1029         }
1030
1031         maybe_signal_changed ();
1032
1033         return nal;
1034 }
1035
1036 AutomationList*
1037 AutomationList::cut_copy_clear (double start, double end, int op)
1038 {
1039         AutomationList* nal = new AutomationList (default_value);
1040         iterator s, e;
1041         ControlEvent cp (start, 0.0);
1042         TimeComparator cmp;
1043         bool changed = false;
1044         
1045         {
1046                 Glib::Mutex::Lock lm (lock);
1047
1048                 if ((s = lower_bound (events.begin(), events.end(), &cp, cmp)) == events.end()) {
1049                         return nal;
1050                 }
1051
1052                 cp.when = end;
1053                 e = upper_bound (events.begin(), events.end(), &cp, cmp);
1054
1055                 if (op != 2 && (*s)->when != start) {
1056                         nal->events.push_back (point_factory (0, unlocked_eval (start)));
1057                 }
1058
1059                 for (iterator x = s; x != e; ) {
1060                         iterator tmp;
1061                         
1062                         tmp = x;
1063                         ++tmp;
1064
1065                         changed = true;
1066                         
1067                         /* adjust new points to be relative to start, which
1068                            has been set to zero.
1069                         */
1070                         
1071                         if (op != 2) {
1072                                 nal->events.push_back (point_factory ((*x)->when - start, (*x)->value));
1073                         }
1074
1075                         if (op != 1) {
1076                                 events.erase (x);
1077                         }
1078                         
1079                         x = tmp;
1080                 }
1081
1082                 if (op != 2 && nal->events.back()->when != end - start) {
1083                         nal->events.push_back (point_factory (end - start, unlocked_eval (end)));
1084                 }
1085
1086                 if (changed) {
1087                         reposition_for_rt_add (0);
1088                 }
1089
1090                 mark_dirty ();
1091         }
1092
1093         maybe_signal_changed ();
1094
1095         return nal;
1096
1097 }
1098
1099 AutomationList*
1100 AutomationList::copy (iterator start, iterator end)
1101 {
1102         AutomationList* nal = new AutomationList (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 (point_factory (**x));
1114                         
1115                         x = tmp;
1116                 }
1117         }
1118
1119         return nal;
1120 }
1121
1122 AutomationList*
1123 AutomationList::cut (double start, double end)
1124 {
1125         return cut_copy_clear (start, end, 0);
1126 }
1127
1128 AutomationList*
1129 AutomationList::copy (double start, double end)
1130 {
1131         return cut_copy_clear (start, end, 1);
1132 }
1133
1134 void
1135 AutomationList::clear (double start, double end)
1136 {
1137         (void) cut_copy_clear (start, end, 2);
1138 }
1139
1140 bool
1141 AutomationList::paste (AutomationList& alist, double pos, float times)
1142 {
1143         if (alist.events.empty()) {
1144                 return false;
1145         }
1146
1147         {
1148                 Glib::Mutex::Lock lm (lock);
1149                 iterator where;
1150                 iterator prev;
1151                 double end = 0;
1152                 ControlEvent cp (pos, 0.0);
1153                 TimeComparator cmp;
1154
1155                 where = upper_bound (events.begin(), events.end(), &cp, cmp);
1156
1157                 for (iterator i = alist.begin();i != alist.end(); ++i) {
1158                         events.insert (where, point_factory( (*i)->when+pos,( *i)->value));
1159                         end = (*i)->when + pos;
1160                 }
1161         
1162         
1163                 /* move all  points after the insertion along the timeline by 
1164                    the correct amount.
1165                 */
1166
1167                 while (where != events.end()) {
1168                         iterator tmp;
1169                         if ((*where)->when <= end) {
1170                                 tmp = where;
1171                                 ++tmp;
1172                                 events.erase(where);
1173                                 where = tmp;
1174
1175                         } else {
1176                                 break;
1177                         }
1178                 }
1179
1180                 reposition_for_rt_add (0);
1181                 mark_dirty ();
1182         }
1183
1184         maybe_signal_changed ();
1185         return true;
1186 }
1187
1188 ControlEvent*
1189 AutomationList::point_factory (double when, double val) const
1190 {
1191         return new ControlEvent (when, val);
1192 }
1193
1194 ControlEvent*
1195 AutomationList::point_factory (const ControlEvent& other) const
1196 {
1197         return new ControlEvent (other);
1198 }
1199
1200 XMLNode&
1201 AutomationList::get_state ()
1202 {
1203         return state (true);
1204 }
1205
1206 XMLNode&
1207 AutomationList::state (bool full)
1208 {
1209         XMLNode* root = new XMLNode (X_("AutomationList"));
1210         char buf[64];
1211         LocaleGuard lg (X_("POSIX"));
1212
1213         root->add_property ("id", _id.to_s());
1214
1215         snprintf (buf, sizeof (buf), "%.12g", default_value);
1216         root->add_property ("default", buf);
1217         snprintf (buf, sizeof (buf), "%.12g", min_yval);
1218         root->add_property ("min_yval", buf);
1219         snprintf (buf, sizeof (buf), "%.12g", max_yval);
1220         root->add_property ("max_yval", buf);
1221         snprintf (buf, sizeof (buf), "%.12g", max_xval);
1222         root->add_property ("max_xval", buf);
1223
1224         if (full) {
1225                 root->add_property ("state", auto_state_to_string (_state));
1226         } else {
1227                 /* never save anything but Off for automation state to a template */
1228                 root->add_property ("state", auto_state_to_string (Off));
1229         }
1230
1231         root->add_property ("style", auto_style_to_string (_style));
1232
1233         if (!events.empty()) {
1234                 root->add_child_nocopy (serialize_events());
1235         }
1236
1237         return *root;
1238 }
1239
1240 XMLNode&
1241 AutomationList::serialize_events ()
1242 {
1243         XMLNode* node = new XMLNode (X_("events"));
1244         stringstream str;
1245
1246         for (iterator xx = events.begin(); xx != events.end(); ++xx) {
1247                 str << (double) (*xx)->when;
1248                 str << ' ';
1249                 str <<(double) (*xx)->value;
1250                 str << '\n';
1251         }
1252
1253         /* XML is a bit wierd */
1254
1255         XMLNode* content_node = new XMLNode (X_("foo")); /* it gets renamed by libxml when we set content */
1256         content_node->set_content (str.str());
1257
1258         node->add_child_nocopy (*content_node);
1259
1260         return *node;
1261 }
1262
1263 int
1264 AutomationList::deserialize_events (const XMLNode& node)
1265 {
1266         if (node.children().empty()) {
1267                 return -1;
1268         }
1269
1270         XMLNode* content_node = node.children().front();
1271
1272         if (content_node->content().empty()) {
1273                 return -1;
1274         }
1275
1276         freeze ();
1277         clear ();
1278         
1279         stringstream str (content_node->content());
1280         
1281         double x;
1282         double y;
1283         bool ok = true;
1284         
1285         while (str) {
1286                 str >> x;
1287                 if (!str) {
1288                         break;
1289                 }
1290                 str >> y;
1291                 if (!str) {
1292                         ok = false;
1293                         break;
1294                 }
1295                 fast_simple_add (x, y);
1296         }
1297         
1298         if (!ok) {
1299                 clear ();
1300                 error << _("automation list: cannot load coordinates from XML, all points ignored") << endmsg;
1301         } else {
1302                 mark_dirty ();
1303                 reposition_for_rt_add (0);
1304                 maybe_signal_changed ();
1305         }
1306
1307         thaw ();
1308
1309         return 0;
1310 }
1311
1312 int
1313 AutomationList::set_state (const XMLNode& node)
1314 {
1315         XMLNodeList nlist = node.children();
1316         XMLNode* nsos;
1317         XMLNodeIterator niter;
1318         const XMLProperty* prop;
1319
1320         if (node.name() == X_("events")) {
1321                 /* partial state setting*/
1322                 return deserialize_events (node);
1323         }
1324         
1325         if (node.name() == X_("Envelope") || node.name() == X_("FadeOut") || node.name() == X_("FadeIn")) {
1326
1327                 if ((nsos = node.child (X_("AutomationList")))) {
1328                         /* new school in old school clothing */
1329                         return set_state (*nsos);
1330                 }
1331
1332                 /* old school */
1333
1334                 const XMLNodeList& elist = node.children();
1335                 XMLNodeConstIterator i;
1336                 XMLProperty* prop;
1337                 jack_nframes_t x;
1338                 double y;
1339                 
1340                 freeze ();
1341                 clear ();
1342                 
1343                 for (i = elist.begin(); i != elist.end(); ++i) {
1344                         
1345                         if ((prop = (*i)->property ("x")) == 0) {
1346                                 error << _("automation list: no x-coordinate stored for control point (point ignored)") << endmsg;
1347                                 continue;
1348                         }
1349                         x = atoi (prop->value().c_str());
1350                         
1351                         if ((prop = (*i)->property ("y")) == 0) {
1352                                 error << _("automation list: no y-coordinate stored for control point (point ignored)") << endmsg;
1353                                 continue;
1354                         }
1355                         y = atof (prop->value().c_str());
1356                         
1357                         fast_simple_add (x, y);
1358                 }
1359                 
1360                 thaw ();
1361
1362                 return 0;
1363         }
1364
1365         if (node.name() != X_("AutomationList") ) {
1366                 error << string_compose (_("AutomationList: passed XML node called %1, not \"AutomationList\" - ignored"), node.name()) << endmsg;
1367                 return -1;
1368         }
1369         
1370         if ((prop = node.property ("id")) != 0) {
1371                 _id = prop->value ();
1372                 /* update session AL list */
1373                 AutomationListCreated(this);
1374         }
1375         
1376         if ((prop = node.property (X_("default"))) != 0){ 
1377                 default_value = atof (prop->value());
1378         } else {
1379                 default_value = 0.0;
1380         }
1381
1382         if ((prop = node.property (X_("style"))) != 0) {
1383                 _style = string_to_auto_style (prop->value());
1384         } else {
1385                 _style = Absolute;
1386         }
1387
1388         if ((prop = node.property (X_("state"))) != 0) {
1389                 _state = string_to_auto_state (prop->value());
1390         } else {
1391                 _state = Off;
1392         }
1393
1394         if ((prop = node.property (X_("min_yval"))) != 0) {
1395                 min_yval = atof (prop->value ());
1396         } else {
1397                 min_yval = FLT_MIN;
1398         }
1399
1400         if ((prop = node.property (X_("max_yval"))) != 0) {
1401                 max_yval = atof (prop->value ());
1402         } else {
1403                 max_yval = FLT_MAX;
1404         }
1405
1406         if ((prop = node.property (X_("max_xval"))) != 0) {
1407                 max_xval = atof (prop->value ());
1408         } else {
1409                 max_xval = 0; // means "no limit ;
1410         }
1411
1412         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1413                 if ((*niter)->name() == X_("events")) {
1414                         deserialize_events (*(*niter));
1415                 }
1416         }
1417
1418         return 0;
1419 }
1420