Merge commit 'origin/master-tx'
[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
28 #include <pulse/sample.h>
29 #include <pulse/xmalloc.h>
30
31 #include <pulsecore/macro.h>
32
33 #include "time-smoother.h"
34
35 #define HISTORY_MAX 64
36
37 /*
38  * Implementation of a time smoothing algorithm to synchronize remote
39  * clocks to a local one. Evens out noise, adjusts to clock skew and
40  * allows cheap estimations of the remote time while clock updates may
41  * be seldom and recieved in non-equidistant intervals.
42  *
43  * Basically, we estimate the gradient of received clock samples in a
44  * certain history window (of size 'history_time') with linear
45  * regression. With that info we estimate the remote time in
46  * 'adjust_time' ahead and smoothen our current estimation function
47  * towards that point with a 3rd order polynomial interpolation with
48  * fitting derivatives. (more or less a b-spline)
49  *
50  * The larger 'history_time' is chosen the better we will surpress
51  * noise -- but we'll adjust to clock skew slower..
52  *
53  * The larger 'adjust_time' is chosen the smoother our estimation
54  * function will be -- but we'll adjust to clock skew slower, too.
55  *
56  * If 'monotonic' is TRUE the resulting estimation function is
57  * guaranteed to be monotonic.
58  */
59
60 struct pa_smoother {
61     pa_usec_t adjust_time, history_time;
62
63     pa_usec_t time_offset;
64
65     pa_usec_t px, py;     /* Point p, where we want to reach stability */
66     double dp;            /* Gradient we want at point p */
67
68     pa_usec_t ex, ey;     /* Point e, which we estimated before and need to smooth to */
69     double de;            /* Gradient we estimated for point e */
70     pa_usec_t ry;         /* The original y value for ex */
71
72                           /* History of last measurements */
73     pa_usec_t history_x[HISTORY_MAX], history_y[HISTORY_MAX];
74     unsigned history_idx, n_history;
75
76     /* To even out for monotonicity */
77     pa_usec_t last_y, last_x;
78
79     /* Cached parameters for our interpolation polynomial y=ax^3+b^2+cx */
80     double a, b, c;
81     pa_bool_t abc_valid:1;
82
83     pa_bool_t monotonic:1;
84     pa_bool_t paused:1;
85     pa_bool_t smoothing:1; /* If FALSE we skip the polonyomial interpolation step */
86
87     pa_usec_t pause_time;
88
89     unsigned min_history;
90 };
91
92 pa_smoother* pa_smoother_new(
93         pa_usec_t adjust_time,
94         pa_usec_t history_time,
95         pa_bool_t monotonic,
96         pa_bool_t smoothing,
97         unsigned min_history,
98         pa_usec_t time_offset,
99         pa_bool_t paused) {
100
101     pa_smoother *s;
102
103     pa_assert(adjust_time > 0);
104     pa_assert(history_time > 0);
105     pa_assert(min_history >= 2);
106     pa_assert(min_history <= HISTORY_MAX);
107
108     s = pa_xnew(pa_smoother, 1);
109     s->adjust_time = adjust_time;
110     s->history_time = history_time;
111     s->min_history = min_history;
112     s->monotonic = monotonic;
113     s->smoothing = smoothing;
114
115     pa_smoother_reset(s, time_offset, paused);
116
117     return s;
118 }
119
120 void pa_smoother_free(pa_smoother* s) {
121     pa_assert(s);
122
123     pa_xfree(s);
124 }
125
126 #define REDUCE(x)                               \
127     do {                                        \
128         x = (x) % HISTORY_MAX;                  \
129     } while(FALSE)
130
131 #define REDUCE_INC(x)                           \
132     do {                                        \
133         x = ((x)+1) % HISTORY_MAX;              \
134     } while(FALSE)
135
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     /* Too few measurements, assume gradient of 1 */
200     if (s->n_history < s->min_history)
201         return 1;
202
203     /* First, calculate average of all measurements */
204     i = s->history_idx;
205     for (j = s->n_history; j > 0; j--) {
206
207         ax += (int64_t) s->history_x[i];
208         ay += (int64_t) s->history_y[i];
209         c++;
210
211         REDUCE_INC(i);
212     }
213
214     pa_assert(c >= s->min_history);
215     ax /= c;
216     ay /= c;
217
218     /* Now, do linear regression */
219     k = t = 0;
220
221     i = s->history_idx;
222     for (j = s->n_history; j > 0; j--) {
223         int64_t dx, dy;
224
225         dx = (int64_t) s->history_x[i] - ax;
226         dy = (int64_t) s->history_y[i] - ay;
227
228         k += dx*dy;
229         t += dx*dx;
230
231         REDUCE_INC(i);
232     }
233
234     r = (double) k / (double) t;
235
236     return (s->monotonic && r < 0) ? 0 : r;
237 }
238
239 static void calc_abc(pa_smoother *s) {
240     pa_usec_t ex, ey, px, py;
241     int64_t kx, ky;
242     double de, dp;
243
244     pa_assert(s);
245
246     if (s->abc_valid)
247         return;
248
249     /* We have two points: (ex|ey) and (px|py) with two gradients at
250      * these points de and dp. We do a polynomial
251      * interpolation of degree 3 with these 6 values */
252
253     ex = s->ex; ey = s->ey;
254     px = s->px; py = s->py;
255     de = s->de; dp = s->dp;
256
257     pa_assert(ex < px);
258
259     /* To increase the dynamic range and symplify calculation, we
260      * move these values to the origin */
261     kx = (int64_t) px - (int64_t) ex;
262     ky = (int64_t) py - (int64_t) ey;
263
264     /* Calculate a, b, c for y=ax^3+bx^2+cx */
265     s->c = de;
266     s->b = (((double) (3*ky)/ (double) kx - dp - (double) (2*de))) / (double) kx;
267     s->a = (dp/(double) kx - 2*s->b - de/(double) kx) / (double) (3*kx);
268
269     s->abc_valid = TRUE;
270 }
271
272 static void estimate(pa_smoother *s, pa_usec_t x, pa_usec_t *y, double *deriv) {
273     pa_assert(s);
274     pa_assert(y);
275
276     if (x >= s->px) {
277         /* Linear interpolation right from px */
278         int64_t t;
279
280         /* The requested point is right of the point where we wanted
281          * to be on track again, thus just linearly estimate */
282
283         t = (int64_t) s->py + (int64_t) llrint(s->dp * (double) (x - s->px));
284
285         if (t < 0)
286             t = 0;
287
288         *y = (pa_usec_t) t;
289
290         if (deriv)
291             *deriv = s->dp;
292
293     } else if (x <= s->ex) {
294         /* Linear interpolation left from ex */
295         int64_t t;
296
297         t = (int64_t) s->ey - (int64_t) llrint(s->de * (double) (s->ex - x));
298
299         if (t < 0)
300             t = 0;
301
302         *y = (pa_usec_t) t;
303
304         if (deriv)
305             *deriv = s->de;
306
307     } else {
308         /* Spline interpolation between ex and px */
309         double tx, ty;
310
311         /* Ok, we're not yet on track, thus let's interpolate, and
312          * make sure that the first derivative is smooth */
313
314         calc_abc(s);
315
316         tx = (double) x;
317
318         /* Move to origin */
319         tx -= (double) s->ex;
320
321         /* Horner scheme */
322         ty = (tx * (s->c + tx * (s->b + tx * s->a)));
323
324         /* Move back from origin */
325         ty += (double) s->ey;
326
327         *y = ty >= 0 ? (pa_usec_t) llrint(ty) : 0;
328
329         /* Horner scheme */
330         if (deriv)
331             *deriv = s->c + (tx * (s->b*2 + tx * s->a*3));
332     }
333
334     /* Guarantee monotonicity */
335     if (s->monotonic) {
336
337         if (deriv && *deriv < 0)
338             *deriv = 0;
339     }
340 }
341
342 void pa_smoother_put(pa_smoother *s, pa_usec_t x, pa_usec_t y) {
343     pa_usec_t ney;
344     double nde;
345     pa_bool_t is_new;
346
347     pa_assert(s);
348
349     /* Fix up x value */
350     if (s->paused)
351         x = s->pause_time;
352
353     x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
354
355     is_new = x >= s->ex;
356
357     if (is_new) {
358         /* First, we calculate the position we'd estimate for x, so that
359          * we can adjust our position smoothly from this one */
360         estimate(s, x, &ney, &nde);
361         s->ex = x; s->ey = ney; s->de = nde;
362         s->ry = y;
363     }
364
365     /* Then, we add the new measurement to our history */
366     add_to_history(s, x, y);
367
368     /* And determine the average gradient of the history */
369     s->dp = avg_gradient(s, x);
370
371     /* And calculate when we want to be on track again */
372     if (s->smoothing) {
373         s->px = s->ex + s->adjust_time;
374         s->py = s->ry + (pa_usec_t) llrint(s->dp * (double) s->adjust_time);
375     } else {
376         s->px = s->ex;
377         s->py = s->ry;
378     }
379
380     s->abc_valid = FALSE;
381
382 #ifdef DEBUG_DATA
383     pa_log_debug("%p, put(%llu | %llu) = %llu", s, (unsigned long long)  (x + s->time_offset), (unsigned long long) x, (unsigned long long) y);
384 #endif
385 }
386
387 pa_usec_t pa_smoother_get(pa_smoother *s, pa_usec_t x) {
388     pa_usec_t y;
389
390     pa_assert(s);
391
392     /* Fix up x value */
393     if (s->paused)
394         x = s->pause_time;
395
396     x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
397
398     if (s->monotonic)
399         if (x <= s->last_x)
400             x = s->last_x;
401
402     estimate(s, x, &y, NULL);
403
404     if (s->monotonic) {
405
406         /* Make sure the querier doesn't jump forth and back. */
407         s->last_x = x;
408
409         if (y < s->last_y)
410             y = s->last_y;
411         else
412             s->last_y = y;
413     }
414
415 #ifdef DEBUG_DATA
416     pa_log_debug("%p, get(%llu | %llu) = %llu", s, (unsigned long long) (x + s->time_offset), (unsigned long long) x, (unsigned long long) y);
417 #endif
418
419     return y;
420 }
421
422 void pa_smoother_set_time_offset(pa_smoother *s, pa_usec_t offset) {
423     pa_assert(s);
424
425     s->time_offset = offset;
426
427 #ifdef DEBUG_DATA
428     pa_log_debug("offset(%llu)", (unsigned long long) offset);
429 #endif
430 }
431
432 void pa_smoother_pause(pa_smoother *s, pa_usec_t x) {
433     pa_assert(s);
434
435     if (s->paused)
436         return;
437
438 #ifdef DEBUG_DATA
439     pa_log_debug("pause(%llu)", (unsigned long long)  x);
440 #endif
441
442     s->paused = TRUE;
443     s->pause_time = x;
444 }
445
446 void pa_smoother_resume(pa_smoother *s, pa_usec_t x, pa_bool_t fix_now) {
447     pa_assert(s);
448
449     if (!s->paused)
450         return;
451
452     if (x < s->pause_time)
453         x = s->pause_time;
454
455 #ifdef DEBUG_DATA
456     pa_log_debug("resume(%llu)", (unsigned long long) x);
457 #endif
458
459     s->paused = FALSE;
460     s->time_offset += x - s->pause_time;
461
462     if (fix_now)
463         pa_smoother_fix_now(s);
464 }
465
466 void pa_smoother_fix_now(pa_smoother *s) {
467     pa_assert(s);
468
469     s->px = s->ex;
470     s->py = s->ry;
471 }
472
473 pa_usec_t pa_smoother_translate(pa_smoother *s, pa_usec_t x, pa_usec_t y_delay) {
474     pa_usec_t ney;
475     double nde;
476
477     pa_assert(s);
478
479     /* Fix up x value */
480     if (s->paused)
481         x = s->pause_time;
482
483     x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
484
485     estimate(s, x, &ney, &nde);
486
487     /* Play safe and take the larger gradient, so that we wakeup
488      * earlier when this is used for sleeping */
489     if (s->dp > nde)
490         nde = s->dp;
491
492 #ifdef DEBUG_DATA
493     pa_log_debug("translate(%llu) = %llu (%0.2f)", (unsigned long long) y_delay, (unsigned long long) ((double) y_delay / nde), nde);
494 #endif
495
496     return (pa_usec_t) llrint((double) y_delay / nde);
497 }
498
499 void pa_smoother_reset(pa_smoother *s, pa_usec_t time_offset, pa_bool_t paused) {
500     pa_assert(s);
501
502     s->px = s->py = 0;
503     s->dp = 1;
504
505     s->ex = s->ey = s->ry = 0;
506     s->de = 1;
507
508     s->history_idx = 0;
509     s->n_history = 0;
510
511     s->last_y = s->last_x = 0;
512
513     s->abc_valid = FALSE;
514
515     s->paused = paused;
516     s->time_offset = s->pause_time = time_offset;
517
518 #ifdef DEBUG_DATA
519     pa_log_debug("reset()");
520 #endif
521 }