1 /*
2  * Copyright (C) 2008-2013 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2008-2016 David Robillard <d@drobilla.net>
4  * Copyright (C) 2010-2012 Carl Hetherington <carl@carlh.net>
5  * Copyright (C) 2012-2018 Robin Gareus <robin@gareus.org>
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 along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21 
22 #include <iostream>
23 #include <float.h>
24 #include <cmath>
25 #include <climits>
26 #include <cfloat>
27 #include <cmath>
28 #include <vector>
29 
30 #include <glibmm/threads.h>
31 
32 #include "pbd/control_math.h"
33 
34 #include "evoral/Curve.h"
35 #include "evoral/ControlList.h"
36 
37 using namespace std;
38 using namespace sigc;
39 
40 namespace Evoral {
41 
42 
Curve(const ControlList & cl)43 Curve::Curve (const ControlList& cl)
44 	: _dirty (true)
45 	, _list (cl)
46 {
47 }
48 
49 void
solve() const50 Curve::solve () const
51 {
52 	uint32_t npoints;
53 
54 	if (!_dirty) {
55 		return;
56 	}
57 
58 	if ((npoints = _list.events().size()) > 2) {
59 
60 		/* Compute coefficients needed to efficiently compute a constrained spline
61 		   curve. See "Constrained Cubic Spline Interpolation" by CJC Kruger
62 		   (www.korf.co.uk/spline.pdf) for more details.
63 		*/
64 
65 		vector<double> x(npoints);
66 		vector<double> y(npoints);
67 		uint32_t i;
68 		ControlList::EventList::const_iterator xx;
69 
70 		for (i = 0, xx = _list.events().begin(); xx != _list.events().end(); ++xx, ++i) {
71 			x[i] = (double) (*xx)->when;
72 			y[i] = (double) (*xx)->value;
73 		}
74 
75 		double lp0, lp1, fpone;
76 
77 		lp0 = (x[1] - x[0])/(y[1] - y[0]);
78 		lp1 = (x[2] - x[1])/(y[2] - y[1]);
79 
80 		if (lp0*lp1 < 0) {
81 			fpone = 0;
82 		} else {
83 			fpone = 2 / (lp1 + lp0);
84 		}
85 
86 		double fplast = 0;
87 
88 		for (i = 0, xx = _list.events().begin(); xx != _list.events().end(); ++xx, ++i) {
89 
90 			double xdelta;   /* gcc is wrong about possible uninitialized use */
91 			double xdelta2;  /* ditto */
92 			double ydelta;   /* ditto */
93 			double fppL, fppR;
94 			double fpi;
95 
96 			if (i > 0) {
97 				xdelta = x[i] - x[i-1];
98 				xdelta2 = xdelta * xdelta;
99 				ydelta = y[i] - y[i-1];
100 			}
101 
102 			/* compute (constrained) first derivatives */
103 
104 			if (i == 0) {
105 
106 				/* first segment */
107 
108 				fplast = ((3 * (y[1] - y[0]) / (2 * (x[1] - x[0]))) - (fpone * 0.5));
109 
110 				/* we don't store coefficients for i = 0 */
111 
112 				continue;
113 
114 			} else if (i == npoints - 1) {
115 
116 				/* last segment */
117 
118 				fpi = ((3 * ydelta) / (2 * xdelta)) - (fplast * 0.5);
119 
120 			} else {
121 
122 				/* all other segments */
123 
124 				double slope_before = ((x[i+1] - x[i]) / (y[i+1] - y[i]));
125 				double slope_after = (xdelta / ydelta);
126 
127 				if (slope_after * slope_before < 0.0) {
128 					/* slope changed sign */
129 					fpi = 0.0;
130 				} else {
131 					fpi = 2 / (slope_before + slope_after);
132 				}
133 			}
134 
135 			/* compute second derivative for either side of control point `i' */
136 
137 			fppL = (((-2 * (fpi + (2 * fplast))) / (xdelta))) +
138 				((6 * ydelta) / xdelta2);
139 
140 			fppR = (2 * ((2 * fpi) + fplast) / xdelta) -
141 				((6 * ydelta) / xdelta2);
142 
143 			/* compute polynomial coefficients */
144 
145 			double b, c, d;
146 
147 			d = (fppR - fppL) / (6 * xdelta);
148 			c = ((x[i] * fppL) - (x[i-1] * fppR))/(2 * xdelta);
149 
150 			double xim12, xim13;
151 			double xi2, xi3;
152 
153 			xim12 = x[i-1] * x[i-1];  /* "x[i-1] squared" */
154 			xim13 = xim12 * x[i-1];   /* "x[i-1] cubed" */
155 			xi2 = x[i] * x[i];        /* "x[i] squared" */
156 			xi3 = xi2 * x[i];         /* "x[i] cubed" */
157 
158 			b = (ydelta - (c * (xi2 - xim12)) - (d * (xi3 - xim13))) / xdelta;
159 
160 			/* store */
161 
162 			(*xx)->create_coeffs();
163 			(*xx)->coeff[0] = y[i-1] - (b * x[i-1]) - (c * xim12) - (d * xim13);
164 			(*xx)->coeff[1] = b;
165 			(*xx)->coeff[2] = c;
166 			(*xx)->coeff[3] = d;
167 
168 			fplast = fpi;
169 		}
170 
171 	}
172 
173 	_dirty = false;
174 }
175 
176 bool
rt_safe_get_vector(double x0,double x1,float * vec,int32_t veclen) const177 Curve::rt_safe_get_vector (double x0, double x1, float *vec, int32_t veclen) const
178 {
179 	Glib::Threads::RWLock::ReaderLock lm(_list.lock(), Glib::Threads::TRY_LOCK);
180 
181 	if (!lm.locked()) {
182 		return false;
183 	} else {
184 		_get_vector (x0, x1, vec, veclen);
185 		return true;
186 	}
187 }
188 
189 void
get_vector(double x0,double x1,float * vec,int32_t veclen) const190 Curve::get_vector (double x0, double x1, float *vec, int32_t veclen) const
191 {
192 	Glib::Threads::RWLock::ReaderLock lm(_list.lock());
193 	_get_vector (x0, x1, vec, veclen);
194 }
195 
196 void
_get_vector(double x0,double x1,float * vec,int32_t veclen) const197 Curve::_get_vector (double x0, double x1, float *vec, int32_t veclen) const
198 {
199 	double rx, lx, hx, max_x, min_x;
200 	int32_t i;
201 	int32_t original_veclen;
202 	int32_t npoints;
203 
204 	if (veclen == 0) {
205 		return;
206 	}
207 
208 	if ((npoints = _list.events().size()) == 0) {
209 		/* no events in list, so just fill the entire array with the default value */
210 		for (int32_t i = 0; i < veclen; ++i) {
211 			vec[i] = _list.descriptor().normal;
212 		}
213 		return;
214 	}
215 
216 	if (npoints == 1) {
217 		for (int32_t i = 0; i < veclen; ++i) {
218 			vec[i] = _list.events().front()->value;
219 		}
220 		return;
221 	}
222 
223 	/* events is now known not to be empty */
224 
225 	max_x = _list.events().back()->when;
226 	min_x = _list.events().front()->when;
227 
228 	if (x0 > max_x) {
229 		/* totally past the end - just fill the entire array with the final value */
230 		for (int32_t i = 0; i < veclen; ++i) {
231 			vec[i] = _list.events().back()->value;
232 		}
233 		return;
234 	}
235 
236 	if (x1 < min_x) {
237 		/* totally before the first event - fill the entire array with
238 		 * the initial value.
239 		 */
240 		for (int32_t i = 0; i < veclen; ++i) {
241 			vec[i] = _list.events().front()->value;
242 		}
243 		return;
244 	}
245 
246 	original_veclen = veclen;
247 
248 	if (x0 < min_x) {
249 
250 		/* fill some beginning section of the array with the
251 		   initial (used to be default) value
252 		*/
253 
254 		double frac = (min_x - x0) / (x1 - x0);
255 		int64_t fill_len = (int64_t) floor (veclen * frac);
256 
257 		fill_len = min (fill_len, (int64_t)veclen);
258 
259 		for (i = 0; i < fill_len; ++i) {
260 			vec[i] = _list.events().front()->value;
261 		}
262 
263 		veclen -= fill_len;
264 		vec += fill_len;
265 	}
266 
267 	if (veclen && x1 > max_x) {
268 
269 		/* fill some end section of the array with the default or final value */
270 
271 		double frac = (x1 - max_x) / (x1 - x0);
272 		int64_t fill_len = (int64_t) floor (original_veclen * frac);
273 		float val;
274 
275 		fill_len = min (fill_len, (int64_t)veclen);
276 		val = _list.events().back()->value;
277 
278 		for (i = veclen - fill_len; i < veclen; ++i) {
279 			vec[i] = val;
280 		}
281 
282 		veclen -= fill_len;
283 	}
284 
285 	lx = max (min_x, x0);
286 	hx = min (max_x, x1);
287 
288 	if (npoints == 2) {
289 
290 		const double lpos = _list.events().front()->when;
291 		const double lval = _list.events().front()->value;
292 		const double upos = _list.events().back()->when;
293 		const double uval = _list.events().back()->value;
294 
295 		/* dx that we are using */
296 		if (veclen > 1) {
297 			const double dx_num = hx - lx;
298 			const double dx_den = veclen - 1;
299 			const double lower = _list.descriptor().lower;
300 			const double upper = _list.descriptor().upper;
301 
302 			/* gradient of the line */
303 			const double m_num = uval - lval;
304 			const double m_den = upos - lpos;
305 			/* y intercept of the line */
306 			const double c = uval - (m_num * upos / m_den);
307 
308 			switch (_list.interpolation()) {
309 				case ControlList::Logarithmic:
310 					for (int i = 0; i < veclen; ++i) {
311 						const double fraction = (lx - lpos + i * dx_num / dx_den) / m_den;
312 						vec[i] = interpolate_logarithmic (lval, uval, fraction, lower, upper);
313 					}
314 					break;
315 				case ControlList::Exponential:
316 					for (int i = 0; i < veclen; ++i) {
317 						const double fraction = (lx - lpos + i * dx_num / dx_den) / m_den;
318 						vec[i] = interpolate_gain (lval, uval, fraction, upper);
319 					}
320 					break;
321 				case ControlList::Discrete:
322 					// any discrete vector curves somewhere?
323 					assert (0);
324 				case ControlList::Curved:
325 					/* no 2 point spline */
326 					/* fallthrough */
327 				default: // Linear:
328 					for (int i = 0; i < veclen; ++i) {
329 						vec[i] = (lx * (m_num / m_den) + m_num * i * dx_num / (m_den * dx_den)) + c;
330 					}
331 					break;
332 			}
333 		} else {
334 			double fraction = (lx - lpos) / (upos - lpos);
335 			switch (_list.interpolation()) {
336 				case ControlList::Logarithmic:
337 					vec[0] = interpolate_logarithmic (lval, uval, fraction, _list.descriptor().lower, _list.descriptor().upper);
338 					break;
339 				case ControlList::Exponential:
340 					vec[0] = interpolate_gain (lval, uval, fraction, _list.descriptor().upper);
341 					break;
342 				case ControlList::Discrete:
343 					// any discrete vector curves somewhere?
344 					assert (0);
345 				case ControlList::Curved:
346 					/* no 2 point spline */
347 					/* fallthrough */
348 				default: // Linear:
349 					vec[0] = interpolate_linear (lval, uval, fraction);
350 					break;
351 			}
352 		}
353 
354 		return;
355 	}
356 
357 	if (_dirty) {
358 		solve ();
359 	}
360 
361 	rx = lx;
362 
363 	double dx = 0;
364 	if (veclen > 1) {
365 		dx = (hx - lx) / (veclen - 1);
366 	}
367 
368 	for (i = 0; i < veclen; ++i, rx += dx) {
369 		vec[i] = multipoint_eval (rx);
370 	}
371 }
372 
373 double
multipoint_eval(double x) const374 Curve::multipoint_eval (double x) const
375 {
376 	pair<ControlList::EventList::const_iterator,ControlList::EventList::const_iterator> range;
377 
378 	ControlList::LookupCache& lookup_cache = _list.lookup_cache();
379 
380 	if ((lookup_cache.left < 0) ||
381 	    ((lookup_cache.left > x) ||
382 	     (lookup_cache.range.first == _list.events().end()) ||
383 	     ((*lookup_cache.range.second)->when < x))) {
384 
385 		ControlEvent cp (x, 0.0);
386 
387 		lookup_cache.range = equal_range (_list.events().begin(), _list.events().end(), &cp, ControlList::time_comparator);
388 	}
389 
390 	range = lookup_cache.range;
391 
392 	/* EITHER
393 
394 	   a) x is an existing control point, so first == existing point, second == next point
395 
396 	   OR
397 
398 	   b) x is between control points, so range is empty (first == second, points to where
399 	       to insert x)
400 
401 	*/
402 
403 	if (range.first == range.second) {
404 
405 		/* x does not exist within the list as a control point */
406 
407 		lookup_cache.left = x;
408 
409 		if (range.first == _list.events().begin()) {
410 			/* we're before the first point */
411 			// return default_value;
412 			return _list.events().front()->value;
413 		}
414 
415 		if (range.second == _list.events().end()) {
416 			/* we're after the last point */
417 			return _list.events().back()->value;
418 		}
419 
420 		ControlEvent* after = (*range.second);
421 		range.second--;
422 		ControlEvent* before = (*range.second);
423 
424 		double vdelta = after->value - before->value;
425 
426 		if (vdelta == 0.0) {
427 			return before->value;
428 		}
429 
430 		double tdelta = x - before->when;
431 		double trange = after->when - before->when;
432 
433 		switch (_list.interpolation()) {
434 			case ControlList::Discrete:
435 				return before->value;
436 			case ControlList::Logarithmic:
437 				return interpolate_logarithmic (before->value, after->value, tdelta / trange, _list.descriptor().lower, _list.descriptor().upper);
438 			case ControlList::Exponential:
439 				return interpolate_gain (before->value, after->value, tdelta / trange, _list.descriptor().upper);
440 			case ControlList::Curved:
441 				if (after->coeff) {
442 					ControlEvent* ev = after;
443 					double x2 = x * x;
444 					return ev->coeff[0] + (ev->coeff[1] * x) + (ev->coeff[2] * x2) + (ev->coeff[3] * x2 * x);
445 				}
446 				/* fallthrough */
447 			case ControlList::Linear:
448 				return before->value + (vdelta * (tdelta / trange));
449 		}
450 	}
451 
452 	/* x is a control point in the data */
453 	/* invalidate the cached range because its not usable */
454 	lookup_cache.left = -1;
455 	return (*range.first)->value;
456 }
457 
458 } // namespace Evoral
459