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