1 /* Copyright (c) 2014 The Chromium OS Authors. All rights reserved. 2 * Use of this source code is governed by a BSD-style license that can be 3 * found in the LICENSE file. 4 */ 5 6 #ifndef RATE_ESTIMATOR_H_ 7 #define RATE_ESTIMATOR_H_ 8 9 #include <time.h> 10 11 12 /* Hold information to calculate linear least square from 13 * several (x, y) samples. 14 */ 15 struct least_square { 16 double sum_x; 17 double sum_y; 18 double sum_xy; 19 double sum_x2; 20 int num_samples; 21 }; 22 23 /* An estimator holding the required information to determine the actual frame 24 * rate of an audio device. 25 * Members: 26 * last_level - Buffer level of the audio device at last check time. 27 * level_diff - Number of frames written to or read from audio device since 28 * the last check time. Rate estimator will use this change plus the 29 * difference of buffer level to derive the number of frames audio 30 * device has actually processed. 31 * window_start_ts - The start time of the current window. 32 * window_size - The size of the window. 33 * window_frames - The number of frames accumulated in current window. 34 * lsq - The helper used to estimate sample rate. 35 */ 36 struct rate_estimator { 37 int last_level; 38 int level_diff; 39 struct timespec window_start_ts; 40 struct timespec window_size; 41 int window_frames; 42 struct least_square lsq; 43 double smooth_factor; 44 double estimated_rate; 45 }; 46 47 /* Creates a rate estimator. 48 * Args: 49 * rate - The initial value to estimate rate from. 50 * window_size - The window size of the rate estimator. 51 * smooth_factor - The coefficient used to calculate moving average 52 * from old estimated rate values. 53 */ 54 struct rate_estimator *rate_estimator_create(unsigned int rate, 55 const struct timespec *window_size, 56 double smooth_factor); 57 /* Destroy a rate estimator. */ 58 void rate_estimator_destroy(struct rate_estimator *re); 59 60 /* Adds additional frames transmitted to/from audio device. 61 * Args: 62 * re - The rate estimator. 63 * fr - The number of frames written to the device. For input, this should 64 * be negative to indicate how many samples were read. 65 */ 66 void rate_estimator_add_frames(struct rate_estimator *re, int fr); 67 68 /* Checks the timestamp and buffer level difference since last check time, 69 * and use them as a new sample to update the estimated rate. 70 * Args: 71 * re - The rate estimator. 72 * level - The current buffer level of audio device. 73 * now - The time at which this function is called. 74 * Returns: 75 * True if the estimated rate is updated and window is reset, 76 * otherwise false. 77 */ 78 int rate_estimator_check(struct rate_estimator *re, int level, 79 struct timespec *now); 80 81 /* Gets the estimated rate. */ 82 double rate_estimator_get_rate(struct rate_estimator *re); 83 84 /* Resets the estimated rate. */ 85 void rate_estimator_reset_rate(struct rate_estimator *re, unsigned int rate); 86 87 #endif /* RATE_ESTIMATOR_H_ */ 88