volume ramp: additions to the low level infra
[platform/upstream/pulseaudio.git] / src / pulsecore / time-smoother.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2007 Lennart Poettering
5
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public
17   License along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <math.h>
28
29 #include <pulse/sample.h>
30 #include <pulse/xmalloc.h>
31
32 #include <pulsecore/macro.h>
33
34 #include "time-smoother.h"
35
36 #define HISTORY_MAX 64
37
38 /*
39  * Implementation of a time smoothing algorithm to synchronize remote
40  * clocks to a local one. Evens out noise, adjusts to clock skew and
41  * allows cheap estimations of the remote time while clock updates may
42  * be seldom and received in non-equidistant intervals.
43  *
44  * Basically, we estimate the gradient of received clock samples in a
45  * certain history window (of size 'history_time') with linear
46  * regression. With that info we estimate the remote time in
47  * 'adjust_time' ahead and smoothen our current estimation function
48  * towards that point with a 3rd order polynomial interpolation with
49  * fitting derivatives. (more or less a b-spline)
50  *
51  * The larger 'history_time' is chosen the better we will suppress
52  * noise -- but we'll adjust to clock skew slower..
53  *
54  * The larger 'adjust_time' is chosen the smoother our estimation
55  * function will be -- but we'll adjust to clock skew slower, too.
56  *
57  * If 'monotonic' is true the resulting estimation function is
58  * guaranteed to be monotonic.
59  */
60
61 struct pa_smoother {
62     pa_usec_t adjust_time, history_time;
63
64     pa_usec_t time_offset;
65
66     pa_usec_t px, py;     /* Point p, where we want to reach stability */
67     double dp;            /* Gradient we want at point p */
68
69     pa_usec_t ex, ey;     /* Point e, which we estimated before and need to smooth to */
70     double de;            /* Gradient we estimated for point e */
71     pa_usec_t ry;         /* The original y value for ex */
72
73                           /* History of last measurements */
74     pa_usec_t history_x[HISTORY_MAX], history_y[HISTORY_MAX];
75     unsigned history_idx, n_history;
76
77     /* To even out for monotonicity */
78     pa_usec_t last_y, last_x;
79
80     /* Cached parameters for our interpolation polynomial y=ax^3+b^2+cx */
81     double a, b, c;
82     bool abc_valid:1;
83
84     bool monotonic:1;
85     bool paused:1;
86     bool smoothing:1; /* If false we skip the polynomial interpolation step */
87
88     pa_usec_t pause_time;
89
90     unsigned min_history;
91 };
92
93 pa_smoother* pa_smoother_new(
94         pa_usec_t adjust_time,
95         pa_usec_t history_time,
96         bool monotonic,
97         bool smoothing,
98         unsigned min_history,
99         pa_usec_t time_offset,
100         bool paused) {
101
102     pa_smoother *s;
103
104     pa_assert(adjust_time > 0);
105     pa_assert(history_time > 0);
106     pa_assert(min_history >= 2);
107     pa_assert(min_history <= HISTORY_MAX);
108
109     s = pa_xnew(pa_smoother, 1);
110     s->adjust_time = adjust_time;
111     s->history_time = history_time;
112     s->min_history = min_history;
113     s->monotonic = monotonic;
114     s->smoothing = smoothing;
115
116     pa_smoother_reset(s, time_offset, paused);
117
118     return s;
119 }
120
121 void pa_smoother_free(pa_smoother* s) {
122     pa_assert(s);
123
124     pa_xfree(s);
125 }
126
127 #define REDUCE(x)                               \
128     do {                                        \
129         x = (x) % HISTORY_MAX;                  \
130     } while(false)
131
132 #define REDUCE_INC(x)                           \
133     do {                                        \
134         x = ((x)+1) % HISTORY_MAX;              \
135     } while(false)
136
137 static void drop_old(pa_smoother *s, pa_usec_t x) {
138
139     /* Drop items from history which are too old, but make sure to
140      * always keep min_history in the history */
141
142     while (s->n_history > s->min_history) {
143
144         if (s->history_x[s->history_idx] + s->history_time >= x)
145             /* This item is still valid, and thus all following ones
146              * are too, so let's quit this loop */
147             break;
148
149         /* Item is too old, let's drop it */
150         REDUCE_INC(s->history_idx);
151
152         s->n_history --;
153     }
154 }
155
156 static void add_to_history(pa_smoother *s, pa_usec_t x, pa_usec_t y) {
157     unsigned j, i;
158     pa_assert(s);
159
160     /* First try to update an existing history entry */
161     i = s->history_idx;
162     for (j = s->n_history; j > 0; j--) {
163
164         if (s->history_x[i] == x) {
165             s->history_y[i] = y;
166             return;
167         }
168
169         REDUCE_INC(i);
170     }
171
172     /* Drop old entries */
173     drop_old(s, x);
174
175     /* Calculate position for new entry */
176     j = s->history_idx + s->n_history;
177     REDUCE(j);
178
179     /* Fill in entry */
180     s->history_x[j] = x;
181     s->history_y[j] = y;
182
183     /* Adjust counter */
184     s->n_history ++;
185
186     /* And make sure we don't store more entries than fit in */
187     if (s->n_history > HISTORY_MAX) {
188         s->history_idx += s->n_history - HISTORY_MAX;
189         REDUCE(s->history_idx);
190         s->n_history = HISTORY_MAX;
191     }
192 }
193
194 static double avg_gradient(pa_smoother *s, pa_usec_t x) {
195     unsigned i, j, c = 0;
196     int64_t ax = 0, ay = 0, k, t;
197     double r;
198
199     /* FIXME: Optimization: Jason Newton suggested that instead of
200      * going through the history on each iteration we could calculated
201      * avg_gradient() as we go.
202      *
203      * Second idea: it might make sense to weight history entries:
204      * more recent entries should matter more than old ones. */
205
206     /* Too few measurements, assume gradient of 1 */
207     if (s->n_history < s->min_history)
208         return 1;
209
210     /* First, calculate average of all measurements */
211     i = s->history_idx;
212     for (j = s->n_history; j > 0; j--) {
213
214         ax += (int64_t) s->history_x[i];
215         ay += (int64_t) s->history_y[i];
216         c++;
217
218         REDUCE_INC(i);
219     }
220
221     pa_assert(c >= s->min_history);
222     ax /= c;
223     ay /= c;
224
225     /* Now, do linear regression */
226     k = t = 0;
227
228     i = s->history_idx;
229     for (j = s->n_history; j > 0; j--) {
230         int64_t dx, dy;
231
232         dx = (int64_t) s->history_x[i] - ax;
233         dy = (int64_t) s->history_y[i] - ay;
234
235         k += dx*dy;
236         t += dx*dx;
237
238         REDUCE_INC(i);
239     }
240
241     r = (double) k / (double) t;
242
243     return (s->monotonic && r < 0) ? 0 : r;
244 }
245
246 static void calc_abc(pa_smoother *s) {
247     pa_usec_t ex, ey, px, py;
248     int64_t kx, ky;
249     double de, dp;
250
251     pa_assert(s);
252
253     if (s->abc_valid)
254         return;
255
256     /* We have two points: (ex|ey) and (px|py) with two gradients at
257      * these points de and dp. We do a polynomial
258      * interpolation of degree 3 with these 6 values */
259
260     ex = s->ex; ey = s->ey;
261     px = s->px; py = s->py;
262     de = s->de; dp = s->dp;
263
264     pa_assert(ex < px);
265
266     /* To increase the dynamic range and simplify calculation, we
267      * move these values to the origin */
268     kx = (int64_t) px - (int64_t) ex;
269     ky = (int64_t) py - (int64_t) ey;
270
271     /* Calculate a, b, c for y=ax^3+bx^2+cx */
272     s->c = de;
273     s->b = (((double) (3*ky)/ (double) kx - dp - (double) (2*de))) / (double) kx;
274     s->a = (dp/(double) kx - 2*s->b - de/(double) kx) / (double) (3*kx);
275
276     s->abc_valid = true;
277 }
278
279 static void estimate(pa_smoother *s, pa_usec_t x, pa_usec_t *y, double *deriv) {
280     pa_assert(s);
281     pa_assert(y);
282
283     if (x >= s->px) {
284         /* Linear interpolation right from px */
285         int64_t t;
286
287         /* The requested point is right of the point where we wanted
288          * to be on track again, thus just linearly estimate */
289
290         t = (int64_t) s->py + (int64_t) llrint(s->dp * (double) (x - s->px));
291
292         if (t < 0)
293             t = 0;
294
295         *y = (pa_usec_t) t;
296
297         if (deriv)
298             *deriv = s->dp;
299
300     } else if (x <= s->ex) {
301         /* Linear interpolation left from ex */
302         int64_t t;
303
304         t = (int64_t) s->ey - (int64_t) llrint(s->de * (double) (s->ex - x));
305
306         if (t < 0)
307             t = 0;
308
309         *y = (pa_usec_t) t;
310
311         if (deriv)
312             *deriv = s->de;
313
314     } else {
315         /* Spline interpolation between ex and px */
316         double tx, ty;
317
318         /* Ok, we're not yet on track, thus let's interpolate, and
319          * make sure that the first derivative is smooth */
320
321         calc_abc(s);
322
323         /* Move to origin */
324         tx = (double) (x - s->ex);
325
326         /* Horner scheme */
327         ty = (tx * (s->c + tx * (s->b + tx * s->a)));
328
329         /* Move back from origin */
330         ty += (double) s->ey;
331
332         *y = ty >= 0 ? (pa_usec_t) llrint(ty) : 0;
333
334         /* Horner scheme */
335         if (deriv)
336             *deriv = s->c + (tx * (s->b*2 + tx * s->a*3));
337     }
338
339     /* Guarantee monotonicity */
340     if (s->monotonic) {
341
342         if (deriv && *deriv < 0)
343             *deriv = 0;
344     }
345 }
346
347 void pa_smoother_put(pa_smoother *s, pa_usec_t x, pa_usec_t y) {
348     pa_usec_t ney;
349     double nde;
350     bool is_new;
351
352     pa_assert(s);
353
354     /* Fix up x value */
355     if (s->paused)
356         x = s->pause_time;
357
358     x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
359
360     is_new = x >= s->ex;
361
362     if (is_new) {
363         /* First, we calculate the position we'd estimate for x, so that
364          * we can adjust our position smoothly from this one */
365         estimate(s, x, &ney, &nde);
366         s->ex = x; s->ey = ney; s->de = nde;
367         s->ry = y;
368     }
369
370     /* Then, we add the new measurement to our history */
371     add_to_history(s, x, y);
372
373     /* And determine the average gradient of the history */
374     s->dp = avg_gradient(s, x);
375
376     /* And calculate when we want to be on track again */
377     if (s->smoothing) {
378         s->px = s->ex + s->adjust_time;
379         s->py = s->ry + (pa_usec_t) llrint(s->dp * (double) s->adjust_time);
380     } else {
381         s->px = s->ex;
382         s->py = s->ry;
383     }
384
385     s->abc_valid = false;
386
387 #ifdef DEBUG_DATA
388     pa_log_debug("%p, put(%llu | %llu) = %llu", s, (unsigned long long) (x + s->time_offset), (unsigned long long) x, (unsigned long long) y);
389 #endif
390 }
391
392 pa_usec_t pa_smoother_get(pa_smoother *s, pa_usec_t x) {
393     pa_usec_t y;
394
395     pa_assert(s);
396
397     /* Fix up x value */
398     if (s->paused)
399         x = s->pause_time;
400
401     x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
402
403     if (s->monotonic)
404         if (x <= s->last_x)
405             x = s->last_x;
406
407     estimate(s, x, &y, NULL);
408
409     if (s->monotonic) {
410
411         /* Make sure the querier doesn't jump forth and back. */
412         s->last_x = x;
413
414         if (y < s->last_y)
415             y = s->last_y;
416         else
417             s->last_y = y;
418     }
419
420 #ifdef DEBUG_DATA
421     pa_log_debug("%p, get(%llu | %llu) = %llu", s, (unsigned long long) (x + s->time_offset), (unsigned long long) x, (unsigned long long) y);
422 #endif
423
424     return y;
425 }
426
427 void pa_smoother_set_time_offset(pa_smoother *s, pa_usec_t offset) {
428     pa_assert(s);
429
430     s->time_offset = offset;
431
432 #ifdef DEBUG_DATA
433     pa_log_debug("offset(%llu)", (unsigned long long) offset);
434 #endif
435 }
436
437 void pa_smoother_pause(pa_smoother *s, pa_usec_t x) {
438     pa_assert(s);
439
440     if (s->paused)
441         return;
442
443 #ifdef DEBUG_DATA
444     pa_log_debug("pause(%llu)", (unsigned long long) x);
445 #endif
446
447     s->paused = true;
448     s->pause_time = x;
449 }
450
451 void pa_smoother_resume(pa_smoother *s, pa_usec_t x, bool fix_now) {
452     pa_assert(s);
453
454     if (!s->paused)
455         return;
456
457     if (x < s->pause_time)
458         x = s->pause_time;
459
460 #ifdef DEBUG_DATA
461     pa_log_debug("resume(%llu)", (unsigned long long) x);
462 #endif
463
464     s->paused = false;
465     s->time_offset += x - s->pause_time;
466
467     if (fix_now)
468         pa_smoother_fix_now(s);
469 }
470
471 void pa_smoother_fix_now(pa_smoother *s) {
472     pa_assert(s);
473
474     s->px = s->ex;
475     s->py = s->ry;
476 }
477
478 pa_usec_t pa_smoother_translate(pa_smoother *s, pa_usec_t x, pa_usec_t y_delay) {
479     pa_usec_t ney;
480     double nde;
481
482     pa_assert(s);
483
484     /* Fix up x value */
485     if (s->paused)
486         x = s->pause_time;
487
488     x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
489
490     estimate(s, x, &ney, &nde);
491
492     /* Play safe and take the larger gradient, so that we wakeup
493      * earlier when this is used for sleeping */
494     if (s->dp > nde)
495         nde = s->dp;
496
497 #ifdef DEBUG_DATA
498     pa_log_debug("translate(%llu) = %llu (%0.2f)", (unsigned long long) y_delay, (unsigned long long) ((double) y_delay / nde), nde);
499 #endif
500
501     return (pa_usec_t) llrint((double) y_delay / nde);
502 }
503
504 void pa_smoother_reset(pa_smoother *s, pa_usec_t time_offset, bool paused) {
505     pa_assert(s);
506
507     s->px = s->py = 0;
508     s->dp = 1;
509
510     s->ex = s->ey = s->ry = 0;
511     s->de = 1;
512
513     s->history_idx = 0;
514     s->n_history = 0;
515
516     s->last_y = s->last_x = 0;
517
518     s->abc_valid = false;
519
520     s->paused = paused;
521     s->time_offset = s->pause_time = time_offset;
522
523 #ifdef DEBUG_DATA
524     pa_log_debug("reset()");
525 #endif
526 }