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