]> code.delx.au - pulseaudio/blob - src/pulsecore/time-smoother.c
Merge dead branch 'lockfree'
[pulseaudio] / 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;
82
83 pa_bool_t monotonic:1;
84 pa_bool_t paused:1;
85
86 pa_usec_t pause_time;
87
88 unsigned min_history;
89 };
90
91 pa_smoother* pa_smoother_new(pa_usec_t adjust_time, pa_usec_t history_time, pa_bool_t monotonic, unsigned min_history) {
92 pa_smoother *s;
93
94 pa_assert(adjust_time > 0);
95 pa_assert(history_time > 0);
96 pa_assert(min_history >= 2);
97 pa_assert(min_history <= HISTORY_MAX);
98
99 s = pa_xnew(pa_smoother, 1);
100 s->adjust_time = adjust_time;
101 s->history_time = history_time;
102 s->time_offset = 0;
103 s->monotonic = monotonic;
104
105 s->px = s->py = 0;
106 s->dp = 1;
107
108 s->ex = s->ey = s->ry = 0;
109 s->de = 1;
110
111 s->history_idx = 0;
112 s->n_history = 0;
113
114 s->last_y = s->last_x = 0;
115
116 s->abc_valid = FALSE;
117
118 s->paused = FALSE;
119
120 s->min_history = min_history;
121
122 return s;
123 }
124
125 void pa_smoother_free(pa_smoother* s) {
126 pa_assert(s);
127
128 pa_xfree(s);
129 }
130
131 #define REDUCE(x) \
132 do { \
133 x = (x) % HISTORY_MAX; \
134 } while(FALSE)
135
136 #define REDUCE_INC(x) \
137 do { \
138 x = ((x)+1) % HISTORY_MAX; \
139 } while(FALSE)
140
141
142 static void drop_old(pa_smoother *s, pa_usec_t x) {
143
144 /* Drop items from history which are too old, but make sure to
145 * always keep min_history in the history */
146
147 while (s->n_history > s->min_history) {
148
149 if (s->history_x[s->history_idx] + s->history_time >= x)
150 /* This item is still valid, and thus all following ones
151 * are too, so let's quit this loop */
152 break;
153
154 /* Item is too old, let's drop it */
155 REDUCE_INC(s->history_idx);
156
157 s->n_history --;
158 }
159 }
160
161 static void add_to_history(pa_smoother *s, pa_usec_t x, pa_usec_t y) {
162 unsigned j, i;
163 pa_assert(s);
164
165 /* First try to update an existing history entry */
166 i = s->history_idx;
167 for (j = s->n_history; j > 0; j--) {
168
169 if (s->history_x[i] == x) {
170 s->history_y[i] = y;
171 return;
172 }
173
174 REDUCE_INC(i);
175 }
176
177 /* Drop old entries */
178 drop_old(s, x);
179
180 /* Calculate position for new entry */
181 j = s->history_idx + s->n_history;
182 REDUCE(j);
183
184 /* Fill in entry */
185 s->history_x[j] = x;
186 s->history_y[j] = y;
187
188 /* Adjust counter */
189 s->n_history ++;
190
191 /* And make sure we don't store more entries than fit in */
192 if (s->n_history > HISTORY_MAX) {
193 s->history_idx += s->n_history - HISTORY_MAX;
194 REDUCE(s->history_idx);
195 s->n_history = HISTORY_MAX;
196 }
197 }
198
199 static double avg_gradient(pa_smoother *s, pa_usec_t x) {
200 unsigned i, j, c = 0;
201 int64_t ax = 0, ay = 0, k, t;
202 double r;
203
204 /* Too few measurements, assume gradient of 1 */
205 if (s->n_history < s->min_history)
206 return 1;
207
208 /* First, calculate average of all measurements */
209 i = s->history_idx;
210 for (j = s->n_history; j > 0; j--) {
211
212 ax += s->history_x[i];
213 ay += s->history_y[i];
214 c++;
215
216 REDUCE_INC(i);
217 }
218
219 pa_assert(c >= s->min_history);
220 ax /= c;
221 ay /= c;
222
223 /* Now, do linear regression */
224 k = t = 0;
225
226 i = s->history_idx;
227 for (j = s->n_history; j > 0; j--) {
228 int64_t dx, dy;
229
230 dx = (int64_t) s->history_x[i] - ax;
231 dy = (int64_t) s->history_y[i] - ay;
232
233 k += dx*dy;
234 t += dx*dx;
235
236 REDUCE_INC(i);
237 }
238
239 r = (double) k / t;
240
241 return (s->monotonic && r < 0) ? 0 : r;
242 }
243
244 static void calc_abc(pa_smoother *s) {
245 pa_usec_t ex, ey, px, py;
246 int64_t kx, ky;
247 double de, dp;
248
249 pa_assert(s);
250
251 if (s->abc_valid)
252 return;
253
254 /* We have two points: (ex|ey) and (px|py) with two gradients at
255 * these points de and dp. We do a polynomial
256 * interpolation of degree 3 with these 6 values */
257
258 ex = s->ex; ey = s->ey;
259 px = s->px; py = s->py;
260 de = s->de; dp = s->dp;
261
262 pa_assert(ex < px);
263
264 /* To increase the dynamic range and symplify calculation, we
265 * move these values to the origin */
266 kx = (int64_t) px - (int64_t) ex;
267 ky = (int64_t) py - (int64_t) ey;
268
269 /* Calculate a, b, c for y=ax^3+bx^2+cx */
270 s->c = de;
271 s->b = (((double) (3*ky)/kx - dp - 2*de)) / kx;
272 s->a = (dp/kx - 2*s->b - de/kx) / (3*kx);
273
274 s->abc_valid = TRUE;
275 }
276
277 static void estimate(pa_smoother *s, pa_usec_t x, pa_usec_t *y, double *deriv) {
278 pa_assert(s);
279 pa_assert(y);
280
281 if (x >= s->px) {
282 int64_t t;
283
284 /* The requested point is right of the point where we wanted
285 * to be on track again, thus just linearly estimate */
286
287 t = (int64_t) s->py + (int64_t) (s->dp * (x - s->px));
288
289 if (t < 0)
290 t = 0;
291
292 *y = (pa_usec_t) t;
293
294 if (deriv)
295 *deriv = s->dp;
296
297 } else {
298
299 /* Ok, we're not yet on track, thus let's interpolate, and
300 * make sure that the first derivative is smooth */
301
302 calc_abc(s);
303
304 /* Move to origin */
305 x -= s->ex;
306
307 /* Horner scheme */
308 *y = (pa_usec_t) ((double) x * (s->c + (double) x * (s->b + (double) x * s->a)));
309
310 /* Move back from origin */
311 *y += s->ey;
312
313 /* Horner scheme */
314 if (deriv)
315 *deriv = s->c + ((double) x * (s->b*2 + (double) x * s->a*3));
316 }
317
318 /* Guarantee monotonicity */
319 if (s->monotonic) {
320
321 if (deriv && *deriv < 0)
322 *deriv = 0;
323 }
324 }
325
326 void pa_smoother_put(pa_smoother *s, pa_usec_t x, pa_usec_t y) {
327 pa_usec_t ney;
328 double nde;
329 pa_bool_t is_new;
330
331 pa_assert(s);
332
333 /* Fix up x value */
334 if (s->paused)
335 x = s->pause_time;
336
337 x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
338
339 is_new = x >= s->ex;
340
341 if (is_new) {
342 /* First, we calculate the position we'd estimate for x, so that
343 * we can adjust our position smoothly from this one */
344 estimate(s, x, &ney, &nde);
345 s->ex = x; s->ey = ney; s->de = nde;
346
347 s->ry = y;
348 }
349
350 /* Then, we add the new measurement to our history */
351 add_to_history(s, x, y);
352
353 /* And determine the average gradient of the history */
354 s->dp = avg_gradient(s, x);
355
356 /* And calculate when we want to be on track again */
357 s->px = s->ex + s->adjust_time;
358 s->py = s->ry + s->dp *s->adjust_time;
359
360 s->abc_valid = FALSE;
361
362 /* pa_log_debug("put(%llu | %llu) = %llu", (unsigned long long) (x + s->time_offset), (unsigned long long) x, (unsigned long long) y); */
363 }
364
365 pa_usec_t pa_smoother_get(pa_smoother *s, pa_usec_t x) {
366 pa_usec_t y;
367
368 pa_assert(s);
369
370 /* Fix up x value */
371 if (s->paused)
372 x = s->pause_time;
373
374 x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
375
376 estimate(s, x, &y, NULL);
377
378 if (s->monotonic) {
379
380 /* Make sure the querier doesn't jump forth and back. */
381 pa_assert(x >= s->last_x);
382 s->last_x = x;
383
384 if (y < s->last_y)
385 y = s->last_y;
386 else
387 s->last_y = y;
388 }
389
390 /* pa_log_debug("get(%llu | %llu) = %llu", (unsigned long long) (x + s->time_offset), (unsigned long long) x, (unsigned long long) y); */
391
392 return y;
393 }
394
395 void pa_smoother_set_time_offset(pa_smoother *s, pa_usec_t offset) {
396 pa_assert(s);
397
398 s->time_offset = offset;
399
400 /* pa_log_debug("offset(%llu)", (unsigned long long) offset); */
401 }
402
403 void pa_smoother_pause(pa_smoother *s, pa_usec_t x) {
404 pa_assert(s);
405
406 if (s->paused)
407 return;
408
409 /* pa_log_debug("pause(%llu)", (unsigned long long) x); */
410
411 s->paused = TRUE;
412 s->pause_time = x;
413 }
414
415 void pa_smoother_resume(pa_smoother *s, pa_usec_t x) {
416 pa_assert(s);
417
418 if (!s->paused)
419 return;
420
421 pa_assert(x >= s->pause_time);
422
423 /* pa_log_debug("resume(%llu)", (unsigned long long) x); */
424
425 s->paused = FALSE;
426 s->time_offset += x - s->pause_time;
427 }
428
429 pa_usec_t pa_smoother_translate(pa_smoother *s, pa_usec_t x, pa_usec_t y_delay) {
430 pa_usec_t ney;
431 double nde;
432
433 pa_assert(s);
434
435 /* Fix up x value */
436 if (s->paused)
437 x = s->pause_time;
438
439 x = PA_LIKELY(x >= s->time_offset) ? x - s->time_offset : 0;
440
441 estimate(s, x, &ney, &nde);
442
443 /* Play safe and take the larger gradient, so that we wakeup
444 * earlier when this is used for sleeping */
445 if (s->dp > nde)
446 nde = s->dp;
447
448 /* pa_log_debug("translate(%llu) = %llu (%0.2f)", (unsigned long long) y_delay, (unsigned long long) ((double) y_delay / nde), nde); */
449
450 return (pa_usec_t) ((double) y_delay / nde);
451 }
452
453 void pa_smoother_reset(pa_smoother *s) {
454 pa_assert(s);
455
456 s->n_history = 0;
457 s->abc_valid = FALSE;
458
459 }