613222020c74dfb35c57e7cbac7be4ed9f997847
[ardour.git] / libs / ardour / curve.cc
1 /*
2     Copyright (C) 2001-2003 Paul Davis 
3
4     Contains ideas derived from "Constrained Cubic Spline Interpolation" 
5     by CJC Kruger (www.korf.co.uk/spline.pdf).
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License
18     along with this program; if not, write to the Free Software
19     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21     $Id$
22 */
23
24 #include <iostream>
25 #include <float.h>
26 #include <cmath>
27 #include <climits>
28 #include <cfloat>
29 #include <cmath>
30
31 #include <pbd/lockmonitor.h>
32 #include <sigc++/bind.h>
33
34 #include "ardour/curve.h"
35
36 #include "i18n.h"
37
38 using namespace std;
39 using namespace ARDOUR;
40 using namespace PBD;
41 using namespace sigc;
42
43 Curve::Curve (double minv, double maxv, double canv, bool nostate)
44         : AutomationList (canv, nostate)
45 {
46         min_yval = minv;
47         max_yval = maxv;
48 }
49
50 Curve::Curve (const Curve& other)
51         : AutomationList (other)
52 {
53         min_yval = other.min_yval;
54         max_yval = other.max_yval;
55 }
56
57 Curve::Curve (const Curve& other, double start, double end)
58         : AutomationList (other, start, end)
59 {
60         min_yval = other.min_yval;
61         max_yval = other.max_yval;
62 }
63
64 Curve::~Curve ()
65 {
66 }
67
68 void
69 Curve::solve ()
70 {
71         uint32_t npoints;
72
73         if (!_dirty) {
74                 return;
75         }
76         
77         if ((npoints = events.size()) > 2) {
78                 
79                 /* Compute coefficients needed to efficiently compute a constrained spline
80                    curve. See "Constrained Cubic Spline Interpolation" by CJC Kruger
81                    (www.korf.co.uk/spline.pdf) for more details.
82                 */
83
84                 double x[npoints];
85                 double y[npoints];
86                 uint32_t i;
87                 AutomationEventList::iterator xx;
88
89                 for (i = 0, xx = events.begin(); xx != events.end(); ++xx, ++i) {
90                         x[i] = (double) (*xx)->when;
91                         y[i] = (double) (*xx)->value;
92                 }
93
94                 double lp0, lp1, fpone;
95
96                 lp0 =(x[1] - x[0])/(y[1] - y[0]);
97                 lp1 = (x[2] - x[1])/(y[2] - y[1]);
98
99                 if (lp0*lp1 < 0) {
100                         fpone = 0;
101                 } else {
102                         fpone = 2 / (lp1 + lp0);
103                 }
104
105                 double fplast = 0;
106
107                 for (i = 0, xx = events.begin(); xx != events.end(); ++xx, ++i) {
108                         
109                         CurvePoint* cp = dynamic_cast<CurvePoint*>(*xx);
110
111                         if (cp == 0) {
112                                 fatal  << _("programming error: ")
113                                        << X_("non-CurvePoint event found in event list for a Curve")
114                                        << endmsg;
115                                 /*NOTREACHED*/
116                         }
117                         
118                         double xdelta;   /* gcc is wrong about possible uninitialized use */
119                         double xdelta2;  /* ditto */
120                         double ydelta;   /* ditto */
121                         double fppL, fppR;
122                         double fpi;
123
124                         if (i > 0) {
125                                 xdelta = x[i] - x[i-1];
126                                 xdelta2 = xdelta * xdelta;
127                                 ydelta = y[i] - y[i-1];
128                         }
129
130                         /* compute (constrained) first derivatives */
131                         
132                         if (i == 0) {
133
134                                 /* first segment */
135                                 
136                                 fplast = ((3 * (y[1] - y[0]) / (2 * (x[1] - x[0]))) - (fpone * 0.5));
137
138                                 /* we don't store coefficients for i = 0 */
139
140                                 continue;
141
142                         } else if (i == npoints - 1) {
143
144                                 /* last segment */
145
146                                 fpi = ((3 * ydelta) / (2 * xdelta)) - (fplast * 0.5);
147                                 
148                         } else {
149
150                                 /* all other segments */
151
152                                 double slope_before = ((x[i+1] - x[i]) / (y[i+1] - y[i]));
153                                 double slope_after = (xdelta / ydelta);
154
155                                 if (slope_after * slope_before < 0.0) {
156                                         /* slope changed sign */
157                                         fpi = 0.0;
158                                 } else {
159                                         fpi = 2 / (slope_before + slope_after);
160                                 }
161                                 
162                         }
163
164                         /* compute second derivative for either side of control point `i' */
165                         
166                         fppL = (((-2 * (fpi + (2 * fplast))) / (xdelta))) +
167                                 ((6 * ydelta) / xdelta2);
168                         
169                         fppR = (2 * ((2 * fpi) + fplast) / xdelta) -
170                                 ((6 * ydelta) / xdelta2);
171                         
172                         /* compute polynomial coefficients */
173
174                         double b, c, d;
175
176                         d = (fppR - fppL) / (6 * xdelta);   
177                         c = ((x[i] * fppL) - (x[i-1] * fppR))/(2 * xdelta);
178                         
179                         double xim12, xim13;
180                         double xi2, xi3;
181                         
182                         xim12 = x[i-1] * x[i-1];  /* "x[i-1] squared" */
183                         xim13 = xim12 * x[i-1];   /* "x[i-1] cubed" */
184                         xi2 = x[i] * x[i];        /* "x[i] squared" */
185                         xi3 = xi2 * x[i];         /* "x[i] cubed" */
186                         
187                         b = (ydelta - (c * (xi2 - xim12)) - (d * (xi3 - xim13))) / xdelta;
188
189                         /* store */
190
191                         cp->coeff[0] = y[i-1] - (b * x[i-1]) - (c * xim12) - (d * xim13);
192                         cp->coeff[1] = b;
193                         cp->coeff[2] = c;
194                         cp->coeff[3] = d;
195
196                         fplast = fpi;
197                 }
198                 
199         }
200
201         _dirty = false;
202 }
203
204 bool
205 Curve::rt_safe_get_vector (double x0, double x1, float *vec, int32_t veclen)
206 {
207         TentativeLockMonitor lm (lock, __LINE__, __FILE__);
208
209         if (!lm.locked()) {
210                 return false;
211         } else {
212                 _get_vector (x0, x1, vec, veclen);
213                 return true;
214         }
215 }
216
217 void
218 Curve::get_vector (double x0, double x1, float *vec, int32_t veclen)
219 {
220         LockMonitor lm (lock, __LINE__, __FILE__);
221         _get_vector (x0, x1, vec, veclen);
222 }
223
224 void
225 Curve::_get_vector (double x0, double x1, float *vec, int32_t veclen)
226 {
227         double rx, dx, lx, hx, max_x, min_x;
228         int32_t i;
229         int32_t original_veclen;
230         int32_t npoints;
231
232         if ((npoints = events.size()) == 0) {
233                  for (i = 0; i < veclen; ++i) {
234                          vec[i] = default_value;
235                  }
236                  return;
237         }
238
239         /* events is now known not to be empty */
240
241         max_x = events.back()->when;
242         min_x = events.front()->when;
243
244         lx = max (min_x, x0);
245
246         if (x1 < 0) {
247                 x1 = events.back()->when;
248         }
249
250         hx = min (max_x, x1);
251
252         original_veclen = veclen;
253
254         if (x0 < min_x) {
255
256                 /* fill some beginning section of the array with the 
257                    initial (used to be default) value 
258                 */
259
260                 double frac = (min_x - x0) / (x1 - x0);
261                 int32_t subveclen = (int32_t) floor (veclen * frac);
262                 
263                 subveclen = min (subveclen, veclen);
264
265                 for (i = 0; i < subveclen; ++i) {
266                         vec[i] = events.front()->value;
267                 }
268
269                 veclen -= subveclen;
270                 vec += subveclen;
271         }
272
273         if (veclen && x1 > max_x) {
274
275                 /* fill some end section of the array with the default or final value */
276
277                 double frac = (x1 - max_x) / (x1 - x0);
278
279                 int32_t subveclen = (int32_t) floor (original_veclen * frac);
280
281                 float val;
282                 
283                 subveclen = min (subveclen, veclen);
284
285                 val = events.back()->value;
286
287                 i = veclen - subveclen;
288
289                 for (i = veclen - subveclen; i < veclen; ++i) {
290                         vec[i] = val;
291                 }
292
293                 veclen -= subveclen;
294         }
295
296         if (veclen == 0) {
297                 return;
298         }
299
300         if (npoints == 1 ) {
301         
302                 for (i = 0; i < veclen; ++i) {
303                         vec[i] = events.front()->value;
304                 }
305                 return;
306         }
307  
308  
309         if (npoints == 2) {
310  
311                 /* linear interpolation between 2 points */
312  
313                 /* XXX I'm not sure that this is the right thing to
314                    do here. but its not a common case for the envisaged
315                    uses.
316                 */
317         
318                 if (veclen > 1) {
319                         dx = (hx - lx) / (veclen - 1) ;
320                 } else {
321                         dx = 0; // not used
322                 }
323         
324                 double slope = (events.back()->value - events.front()->value)/  
325                         (events.back()->when - events.front()->when);
326                 double yfrac = dx*slope;
327  
328                 vec[0] = events.front()->value + slope * (lx - events.front()->when);
329  
330                 for (i = 1; i < veclen; ++i) {
331                         vec[i] = vec[i-1] + yfrac;
332                 }
333  
334                 return;
335         }
336  
337         if (_dirty) {
338                 solve ();
339         }
340
341         rx = lx;
342
343         if (veclen > 1) {
344
345                 dx = (hx - lx) / veclen;
346
347                 for (i = 0; i < veclen; ++i, rx += dx) {
348                         vec[i] = multipoint_eval (rx);
349                 }
350         }
351 }
352
353 double
354 Curve::unlocked_eval (double x)
355 {
356         if (_dirty) {
357                 solve ();
358         }
359
360         return shared_eval (x);
361 }
362
363 double
364 Curve::multipoint_eval (double x)
365 {       
366         pair<AutomationEventList::iterator,AutomationEventList::iterator> range;
367
368         if ((lookup_cache.left < 0) ||
369             ((lookup_cache.left > x) || 
370              (lookup_cache.range.first == events.end()) || 
371              ((*lookup_cache.range.second)->when < x))) {
372                 
373                 TimeComparator cmp;
374                 ControlEvent cp (x, 0.0);
375
376                 lookup_cache.range = equal_range (events.begin(), events.end(), &cp, cmp);
377         }
378
379         range = lookup_cache.range;
380
381         /* EITHER 
382            
383            a) x is an existing control point, so first == existing point, second == next point
384
385            OR
386
387            b) x is between control points, so range is empty (first == second, points to where
388                to insert x)
389            
390         */
391
392         if (range.first == range.second) {
393
394                 /* x does not exist within the list as a control point */
395                 
396                 lookup_cache.left = x;
397
398                 if (range.first == events.begin()) {
399                         /* we're before the first point */
400                         // return default_value;
401                         events.front()->value;
402                 }
403                 
404                 if (range.second == events.end()) {
405                         /* we're after the last point */
406                         return events.back()->value;
407                 }
408
409                 double x2 = x * x;
410                 CurvePoint* cp = dynamic_cast<CurvePoint*> (*range.second);
411
412                 return cp->coeff[0] + (cp->coeff[1] * x) + (cp->coeff[2] * x2) + (cp->coeff[3] * x2 * x);
413         } 
414
415         /* x is a control point in the data */
416         /* invalidate the cached range because its not usable */
417         lookup_cache.left = -1;
418         return (*range.first)->value;
419 }
420
421 ControlEvent*
422 Curve::point_factory (double when, double val) const
423 {
424         return new CurvePoint (when, val);
425 }
426
427 ControlEvent*
428 Curve::point_factory (const ControlEvent& other) const
429 {
430         return new CurvePoint (other.when, other.value);
431 }
432
433 Change
434 Curve::restore_state (StateManager::State& state)
435 {
436         mark_dirty ();
437         return AutomationList::restore_state (state);
438 }
439
440
441 extern "C" {
442
443 void 
444 curve_get_vector_from_c (void *arg, double x0, double x1, float* vec, int32_t vecsize)
445 {
446         static_cast<Curve*>(arg)->get_vector (x0, x1, vec, vecsize);
447 }
448
449 }