fix building when PATH_MAX is not defined. (should fix debian bug 320736)
[jack.git] / tools / time_smoother.c
blob3c6c7d1c1b65393ac5fc78ec58722a03092d4d62
2 // After looking at how pulseaudio is doing things,
3 // i have came to the conclusion, that forgetting
4 // about statistics is a bad idea ;)
5 //
6 // i am loosely basing this on pulsecore/time-smoother.c
8 #include "time_smoother.h"
9 #include <stdlib.h>
10 #include <assert.h>
12 time_smoother *time_smoother_new( int history_size )
14 time_smoother *retval = malloc( sizeof( time_smoother ) );
15 if( !retval )
16 return NULL;
18 retval->x = malloc( sizeof(jack_nframes_t) * history_size );
20 if( !retval->x ) {
21 free( retval );
22 return NULL;
25 retval->y = malloc( sizeof(jack_nframes_t) * history_size );
26 if( !retval->y ) {
27 free( retval->x );
28 free( retval );
29 return NULL;
32 retval->history_size = history_size;
33 retval->num_valid = 0;
34 return retval;
37 void time_smoother_free( time_smoother *ts )
39 free( ts->x );
40 free( ts->y );
41 free( ts );
44 // put a time measurement into the smoother.
45 // assume monotonically increasing x.
47 void time_smoother_put ( time_smoother *ts, jack_nframes_t x, jack_nframes_t y )
49 int i;
50 int oldest_index;
51 jack_nframes_t oldest_diff;
53 if( ts->num_valid < ts->history_size ) {
54 ts->x[ts->num_valid] = x;
55 ts->y[ts->num_valid] = y;
56 ts->num_valid += 1;
57 return;
60 // Its full. find oldest value and replace.
61 oldest_index = -1;
62 oldest_diff = 0;
63 for( i=0; i<ts->history_size; i++ ) {
64 if( (x - ts->x[i]) > oldest_diff ) {
65 oldest_diff = (x - ts->x[i]);
66 oldest_index = i;
69 assert( oldest_index != -1 );
71 ts->x[oldest_index] = x;
72 ts->y[oldest_index] = y;
75 // return a and b for the linear regression line,
76 // such that y=a+bx;
77 void time_smoother_get_linear_params( time_smoother *ts,
78 jack_nframes_t now_x,
79 jack_nframes_t now_y,
80 jack_nframes_t history,
81 double *a, double *b )
83 int i;
84 jack_nframes_t sum_x = 0;
85 jack_nframes_t sum_y = 0;
86 int num_values = 0;
87 double mean_x, mean_y;
88 double sxx = 0.0;
89 double sxy = 0.0;
90 double val_a, val_b;
92 for( i=0; i<ts->num_valid; i++ ) {
93 if( (now_x - ts->x[i]) < history ) {
94 sum_x += (now_x - ts->x[i]);
95 sum_y += (now_y - ts->y[i]);
96 num_values += 1;
100 // Give some valid values if we dont have
101 // enough data;
102 if( num_values < 10 ) {
103 if( a ) *a = 0.0;
104 if( b ) *b = 1.0;
106 return;
109 mean_x = (double) sum_x / (double) num_values;
110 mean_y = (double) sum_y / (double) num_values;
111 //printf( "mean: %f %f\n", (float) mean_x, (float) mean_y );
113 for( i=0; i<ts->num_valid; i++ ) {
114 if( (now_x - ts->x[i]) < history ) {
115 sxx += ((double)(now_x-ts->x[i])-mean_x) * ((double)(now_x-ts->x[i])-mean_x);
116 sxy += ((double)(now_x-ts->x[i])-mean_x) * ((double)(now_y-ts->y[i])-mean_y);
120 val_b = sxy/sxx;
121 val_a = mean_y - val_b*mean_x;
123 if( a )
124 *a = val_a;
126 if( b )
127 *b = val_b;