blob: a15b91406c51673b28a3f441fbc1294b8d59400a [file] [log] [blame]
bjornv@google.comb47d4b22011-09-15 12:27:36 +00001/*
bjornv@webrtc.orgbfda85f2012-04-16 07:28:29 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
bjornv@google.comb47d4b22011-09-15 12:27:36 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/utility/delay_estimator.h"
bjornv@google.comb47d4b22011-09-15 12:27:36 +000012
bjornv@google.comb47d4b22011-09-15 12:27:36 +000013#include <stdlib.h>
14#include <string.h>
peahb1fc54d2016-05-12 05:08:45 -070015#include <algorithm>
bjornv@google.comb47d4b22011-09-15 12:27:36 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "rtc_base/checks.h"
kwiberg9e2be5f2016-09-14 05:23:22 -070018
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000019// Number of right shifts for scaling is linearly depending on number of bits in
20// the far-end binary spectrum.
21static const int kShiftsAtZero = 13; // Right shifts at zero binary spectrum.
22static const int kShiftsLinearSlope = 3;
23
Yves Gerey665174f2018-06-19 15:03:05 +020024static const int32_t kProbabilityOffset = 1024; // 2 in Q9.
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000025static const int32_t kProbabilityLowerLimit = 8704; // 17 in Q9.
Yves Gerey665174f2018-06-19 15:03:05 +020026static const int32_t kProbabilityMinSpread = 2816; // 5.5 in Q9.
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000027
bjornv@webrtc.org5c645082013-12-16 10:57:53 +000028// Robust validation settings
29static const float kHistogramMax = 3000.f;
30static const float kLastHistogramMax = 250.f;
31static const float kMinHistogramThreshold = 1.5f;
32static const int kMinRequiredHits = 10;
33static const int kMaxHitsWhenPossiblyNonCausal = 10;
34static const int kMaxHitsWhenPossiblyCausal = 1000;
bjornv@webrtc.org5c645082013-12-16 10:57:53 +000035static const float kQ14Scaling = 1.f / (1 << 14); // Scaling by 2^14 to get Q0.
36static const float kFractionSlope = 0.05f;
37static const float kMinFractionWhenPossiblyCausal = 0.5f;
38static const float kMinFractionWhenPossiblyNonCausal = 0.25f;
39
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000040// Counts and returns number of bits of a 32-bit word.
41static int BitCount(uint32_t u32) {
Yves Gerey665174f2018-06-19 15:03:05 +020042 uint32_t tmp =
43 u32 - ((u32 >> 1) & 033333333333) - ((u32 >> 2) & 011111111111);
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000044 tmp = ((tmp + (tmp >> 3)) & 030707070707);
45 tmp = (tmp + (tmp >> 6));
46 tmp = (tmp + (tmp >> 12) + (tmp >> 24)) & 077;
47
Yves Gerey665174f2018-06-19 15:03:05 +020048 return ((int)tmp);
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000049}
bjornv@google.comb47d4b22011-09-15 12:27:36 +000050
bjornv@google.comb47d4b22011-09-15 12:27:36 +000051// Compares the |binary_vector| with all rows of the |binary_matrix| and counts
52// per row the number of times they have the same value.
53//
54// Inputs:
55// - binary_vector : binary "vector" stored in a long
56// - binary_matrix : binary "matrix" stored as a vector of long
57// - matrix_size : size of binary "matrix"
58//
59// Output:
60// - bit_counts : "Vector" stored as a long, containing for each
61// row the number of times the matrix row and the
62// input vector have the same value
63//
64static void BitCountComparison(uint32_t binary_vector,
65 const uint32_t* binary_matrix,
66 int matrix_size,
67 int32_t* bit_counts) {
68 int n = 0;
bjornv@google.comb47d4b22011-09-15 12:27:36 +000069
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000070 // Compare |binary_vector| with all rows of the |binary_matrix|
bjornv@google.comb47d4b22011-09-15 12:27:36 +000071 for (; n < matrix_size; n++) {
Yves Gerey665174f2018-06-19 15:03:05 +020072 bit_counts[n] = (int32_t)BitCount(binary_vector ^ binary_matrix[n]);
bjornv@google.comb47d4b22011-09-15 12:27:36 +000073 }
74}
75
bjornv@webrtc.org5c645082013-12-16 10:57:53 +000076// Collects necessary statistics for the HistogramBasedValidation(). This
77// function has to be called prior to calling HistogramBasedValidation(). The
78// statistics updated and used by the HistogramBasedValidation() are:
79// 1. the number of |candidate_hits|, which states for how long we have had the
80// same |candidate_delay|
81// 2. the |histogram| of candidate delays over time. This histogram is
82// weighted with respect to a reliability measure and time-varying to cope
83// with possible delay shifts.
84// For further description see commented code.
85//
86// Inputs:
87// - candidate_delay : The delay to validate.
88// - valley_depth_q14 : The cost function has a valley/minimum at the
89// |candidate_delay| location. |valley_depth_q14| is the
90// cost function difference between the minimum and
91// maximum locations. The value is in the Q14 domain.
92// - valley_level_q14 : Is the cost function value at the minimum, in Q14.
93static void UpdateRobustValidationStatistics(BinaryDelayEstimator* self,
94 int candidate_delay,
95 int32_t valley_depth_q14,
96 int32_t valley_level_q14) {
97 const float valley_depth = valley_depth_q14 * kQ14Scaling;
98 float decrease_in_last_set = valley_depth;
Yves Gerey665174f2018-06-19 15:03:05 +020099 const int max_hits_for_slow_change = (candidate_delay < self->last_delay)
100 ? kMaxHitsWhenPossiblyNonCausal
101 : kMaxHitsWhenPossiblyCausal;
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000102 int i = 0;
103
kwiberg9e2be5f2016-09-14 05:23:22 -0700104 RTC_DCHECK_EQ(self->history_size, self->farend->history_size);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000105 // Reset |candidate_hits| if we have a new candidate.
106 if (candidate_delay != self->last_candidate_delay) {
107 self->candidate_hits = 0;
108 self->last_candidate_delay = candidate_delay;
109 }
110 self->candidate_hits++;
111
112 // The |histogram| is updated differently across the bins.
113 // 1. The |candidate_delay| histogram bin is increased with the
114 // |valley_depth|, which is a simple measure of how reliable the
115 // |candidate_delay| is. The histogram is not increased above
116 // |kHistogramMax|.
117 self->histogram[candidate_delay] += valley_depth;
118 if (self->histogram[candidate_delay] > kHistogramMax) {
119 self->histogram[candidate_delay] = kHistogramMax;
120 }
121 // 2. The histogram bins in the neighborhood of |candidate_delay| are
122 // unaffected. The neighborhood is defined as x + {-2, -1, 0, 1}.
123 // 3. The histogram bins in the neighborhood of |last_delay| are decreased
124 // with |decrease_in_last_set|. This value equals the difference between
125 // the cost function values at the locations |candidate_delay| and
126 // |last_delay| until we reach |max_hits_for_slow_change| consecutive hits
127 // at the |candidate_delay|. If we exceed this amount of hits the
128 // |candidate_delay| is a "potential" candidate and we start decreasing
129 // these histogram bins more rapidly with |valley_depth|.
130 if (self->candidate_hits < max_hits_for_slow_change) {
Yves Gerey665174f2018-06-19 15:03:05 +0200131 decrease_in_last_set =
132 (self->mean_bit_counts[self->compare_delay] - valley_level_q14) *
133 kQ14Scaling;
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000134 }
135 // 4. All other bins are decreased with |valley_depth|.
136 // TODO(bjornv): Investigate how to make this loop more efficient. Split up
137 // the loop? Remove parts that doesn't add too much.
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000138 for (i = 0; i < self->history_size; ++i) {
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000139 int is_in_last_set = (i >= self->last_delay - 2) &&
Yves Gerey665174f2018-06-19 15:03:05 +0200140 (i <= self->last_delay + 1) && (i != candidate_delay);
141 int is_in_candidate_set =
142 (i >= candidate_delay - 2) && (i <= candidate_delay + 1);
143 self->histogram[i] -=
144 decrease_in_last_set * is_in_last_set +
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000145 valley_depth * (!is_in_last_set && !is_in_candidate_set);
146 // 5. No histogram bin can go below 0.
147 if (self->histogram[i] < 0) {
148 self->histogram[i] = 0;
149 }
150 }
151}
152
153// Validates the |candidate_delay|, estimated in WebRtc_ProcessBinarySpectrum(),
154// based on a mix of counting concurring hits with a modified histogram
155// of recent delay estimates. In brief a candidate is valid (returns 1) if it
156// is the most likely according to the histogram. There are a couple of
157// exceptions that are worth mentioning:
158// 1. If the |candidate_delay| < |last_delay| it can be that we are in a
159// non-causal state, breaking a possible echo control algorithm. Hence, we
160// open up for a quicker change by allowing the change even if the
161// |candidate_delay| is not the most likely one according to the histogram.
162// 2. There's a minimum number of hits (kMinRequiredHits) and the histogram
163// value has to reached a minimum (kMinHistogramThreshold) to be valid.
164// 3. The action is also depending on the filter length used for echo control.
165// If the delay difference is larger than what the filter can capture, we
166// also move quicker towards a change.
167// For further description see commented code.
168//
169// Input:
170// - candidate_delay : The delay to validate.
171//
172// Return value:
173// - is_histogram_valid : 1 - The |candidate_delay| is valid.
174// 0 - Otherwise.
175static int HistogramBasedValidation(const BinaryDelayEstimator* self,
176 int candidate_delay) {
177 float fraction = 1.f;
178 float histogram_threshold = self->histogram[self->compare_delay];
179 const int delay_difference = candidate_delay - self->last_delay;
180 int is_histogram_valid = 0;
181
182 // The histogram based validation of |candidate_delay| is done by comparing
183 // the |histogram| at bin |candidate_delay| with a |histogram_threshold|.
184 // This |histogram_threshold| equals a |fraction| of the |histogram| at bin
185 // |last_delay|. The |fraction| is a piecewise linear function of the
186 // |delay_difference| between the |candidate_delay| and the |last_delay|
187 // allowing for a quicker move if
188 // i) a potential echo control filter can not handle these large differences.
189 // ii) keeping |last_delay| instead of updating to |candidate_delay| could
190 // force an echo control into a non-causal state.
191 // We further require the histogram to have reached a minimum value of
192 // |kMinHistogramThreshold|. In addition, we also require the number of
193 // |candidate_hits| to be more than |kMinRequiredHits| to remove spurious
194 // values.
195
196 // Calculate a comparison histogram value (|histogram_threshold|) that is
197 // depending on the distance between the |candidate_delay| and |last_delay|.
198 // TODO(bjornv): How much can we gain by turning the fraction calculation
199 // into tables?
bjornv@webrtc.orgbccd53d2014-01-08 08:18:15 +0000200 if (delay_difference > self->allowed_offset) {
201 fraction = 1.f - kFractionSlope * (delay_difference - self->allowed_offset);
Yves Gerey665174f2018-06-19 15:03:05 +0200202 fraction = (fraction > kMinFractionWhenPossiblyCausal
203 ? fraction
204 : kMinFractionWhenPossiblyCausal);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000205 } else if (delay_difference < 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200206 fraction =
207 kMinFractionWhenPossiblyNonCausal - kFractionSlope * delay_difference;
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000208 fraction = (fraction > 1.f ? 1.f : fraction);
209 }
210 histogram_threshold *= fraction;
Yves Gerey665174f2018-06-19 15:03:05 +0200211 histogram_threshold =
212 (histogram_threshold > kMinHistogramThreshold ? histogram_threshold
213 : kMinHistogramThreshold);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000214
215 is_histogram_valid =
216 (self->histogram[candidate_delay] >= histogram_threshold) &&
217 (self->candidate_hits > kMinRequiredHits);
218
219 return is_histogram_valid;
220}
221
222// Performs a robust validation of the |candidate_delay| estimated in
223// WebRtc_ProcessBinarySpectrum(). The algorithm takes the
224// |is_instantaneous_valid| and the |is_histogram_valid| and combines them
225// into a robust validation. The HistogramBasedValidation() has to be called
226// prior to this call.
227// For further description on how the combination is done, see commented code.
228//
229// Inputs:
230// - candidate_delay : The delay to validate.
231// - is_instantaneous_valid : The instantaneous validation performed in
232// WebRtc_ProcessBinarySpectrum().
233// - is_histogram_valid : The histogram based validation.
234//
235// Return value:
236// - is_robust : 1 - The candidate_delay is valid according to a
237// combination of the two inputs.
238// : 0 - Otherwise.
239static int RobustValidation(const BinaryDelayEstimator* self,
240 int candidate_delay,
241 int is_instantaneous_valid,
242 int is_histogram_valid) {
243 int is_robust = 0;
244
245 // The final robust validation is based on the two algorithms; 1) the
246 // |is_instantaneous_valid| and 2) the histogram based with result stored in
247 // |is_histogram_valid|.
248 // i) Before we actually have a valid estimate (|last_delay| == -2), we say
249 // a candidate is valid if either algorithm states so
250 // (|is_instantaneous_valid| OR |is_histogram_valid|).
Yves Gerey665174f2018-06-19 15:03:05 +0200251 is_robust =
252 (self->last_delay < 0) && (is_instantaneous_valid || is_histogram_valid);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000253 // ii) Otherwise, we need both algorithms to be certain
254 // (|is_instantaneous_valid| AND |is_histogram_valid|)
255 is_robust |= is_instantaneous_valid && is_histogram_valid;
256 // iii) With one exception, i.e., the histogram based algorithm can overrule
257 // the instantaneous one if |is_histogram_valid| = 1 and the histogram
258 // is significantly strong.
259 is_robust |= is_histogram_valid &&
Yves Gerey665174f2018-06-19 15:03:05 +0200260 (self->histogram[candidate_delay] > self->last_delay_histogram);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000261
262 return is_robust;
263}
264
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000265void WebRtc_FreeBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend* self) {
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000266 if (self == NULL) {
267 return;
268 }
269
270 free(self->binary_far_history);
271 self->binary_far_history = NULL;
272
273 free(self->far_bit_counts);
274 self->far_bit_counts = NULL;
275
276 free(self);
277}
278
279BinaryDelayEstimatorFarend* WebRtc_CreateBinaryDelayEstimatorFarend(
280 int history_size) {
bjornv@webrtc.org7ded92b2013-01-30 16:16:59 +0000281 BinaryDelayEstimatorFarend* self = NULL;
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000282
bjornv@webrtc.org7ded92b2013-01-30 16:16:59 +0000283 if (history_size > 1) {
284 // Sanity conditions fulfilled.
peahbdb7af62016-04-12 14:47:40 -0700285 self = static_cast<BinaryDelayEstimatorFarend*>(
286 malloc(sizeof(BinaryDelayEstimatorFarend)));
bjornv@webrtc.org7ded92b2013-01-30 16:16:59 +0000287 }
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000288 if (self == NULL) {
289 return NULL;
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000290 }
291
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000292 self->history_size = 0;
293 self->binary_far_history = NULL;
294 self->far_bit_counts = NULL;
295 if (WebRtc_AllocateFarendBufferMemory(self, history_size) == 0) {
296 WebRtc_FreeBinaryDelayEstimatorFarend(self);
297 self = NULL;
298 }
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000299 return self;
300}
301
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000302int WebRtc_AllocateFarendBufferMemory(BinaryDelayEstimatorFarend* self,
303 int history_size) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700304 RTC_DCHECK(self);
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000305 // (Re-)Allocate memory for history buffers.
peahbdb7af62016-04-12 14:47:40 -0700306 self->binary_far_history = static_cast<uint32_t*>(
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000307 realloc(self->binary_far_history,
peahbdb7af62016-04-12 14:47:40 -0700308 history_size * sizeof(*self->binary_far_history)));
Yves Gerey665174f2018-06-19 15:03:05 +0200309 self->far_bit_counts = static_cast<int*>(realloc(
310 self->far_bit_counts, history_size * sizeof(*self->far_bit_counts)));
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000311 if ((self->binary_far_history == NULL) || (self->far_bit_counts == NULL)) {
312 history_size = 0;
313 }
314 // Fill with zeros if we have expanded the buffers.
315 if (history_size > self->history_size) {
316 int size_diff = history_size - self->history_size;
Yves Gerey665174f2018-06-19 15:03:05 +0200317 memset(&self->binary_far_history[self->history_size], 0,
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000318 sizeof(*self->binary_far_history) * size_diff);
Yves Gerey665174f2018-06-19 15:03:05 +0200319 memset(&self->far_bit_counts[self->history_size], 0,
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000320 sizeof(*self->far_bit_counts) * size_diff);
321 }
322 self->history_size = history_size;
323
324 return self->history_size;
325}
326
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000327void WebRtc_InitBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend* self) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700328 RTC_DCHECK(self);
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000329 memset(self->binary_far_history, 0, sizeof(uint32_t) * self->history_size);
330 memset(self->far_bit_counts, 0, sizeof(int) * self->history_size);
331}
332
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000333void WebRtc_SoftResetBinaryDelayEstimatorFarend(
Yves Gerey665174f2018-06-19 15:03:05 +0200334 BinaryDelayEstimatorFarend* self,
335 int delay_shift) {
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000336 int abs_shift = abs(delay_shift);
337 int shift_size = 0;
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000338 int dest_index = 0;
339 int src_index = 0;
340 int padding_index = 0;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000341
kwiberg9e2be5f2016-09-14 05:23:22 -0700342 RTC_DCHECK(self);
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000343 shift_size = self->history_size - abs_shift;
kwiberg9e2be5f2016-09-14 05:23:22 -0700344 RTC_DCHECK_GT(shift_size, 0);
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000345 if (delay_shift == 0) {
346 return;
347 } else if (delay_shift > 0) {
348 dest_index = abs_shift;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000349 } else if (delay_shift < 0) {
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000350 src_index = abs_shift;
351 padding_index = shift_size;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000352 }
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000353
354 // Shift and zero pad buffers.
355 memmove(&self->binary_far_history[dest_index],
356 &self->binary_far_history[src_index],
357 sizeof(*self->binary_far_history) * shift_size);
358 memset(&self->binary_far_history[padding_index], 0,
359 sizeof(*self->binary_far_history) * abs_shift);
Yves Gerey665174f2018-06-19 15:03:05 +0200360 memmove(&self->far_bit_counts[dest_index], &self->far_bit_counts[src_index],
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000361 sizeof(*self->far_bit_counts) * shift_size);
362 memset(&self->far_bit_counts[padding_index], 0,
363 sizeof(*self->far_bit_counts) * abs_shift);
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000364}
365
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000366void WebRtc_AddBinaryFarSpectrum(BinaryDelayEstimatorFarend* handle,
367 uint32_t binary_far_spectrum) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700368 RTC_DCHECK(handle);
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000369 // Shift binary spectrum history and insert current |binary_far_spectrum|.
370 memmove(&(handle->binary_far_history[1]), &(handle->binary_far_history[0]),
371 (handle->history_size - 1) * sizeof(uint32_t));
372 handle->binary_far_history[0] = binary_far_spectrum;
373
374 // Shift history of far-end binary spectrum bit counts and insert bit count
375 // of current |binary_far_spectrum|.
376 memmove(&(handle->far_bit_counts[1]), &(handle->far_bit_counts[0]),
377 (handle->history_size - 1) * sizeof(int));
378 handle->far_bit_counts[0] = BitCount(binary_far_spectrum);
379}
380
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000381void WebRtc_FreeBinaryDelayEstimator(BinaryDelayEstimator* self) {
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000382 if (self == NULL) {
bjornv@webrtc.orgbfda85f2012-04-16 07:28:29 +0000383 return;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000384 }
bjornv@webrtc.orgbfda85f2012-04-16 07:28:29 +0000385
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000386 free(self->mean_bit_counts);
387 self->mean_bit_counts = NULL;
bjornv@webrtc.orgbfda85f2012-04-16 07:28:29 +0000388
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000389 free(self->bit_counts);
390 self->bit_counts = NULL;
bjornv@webrtc.orgbfda85f2012-04-16 07:28:29 +0000391
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000392 free(self->binary_near_history);
393 self->binary_near_history = NULL;
bjornv@webrtc.orgbfda85f2012-04-16 07:28:29 +0000394
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000395 free(self->histogram);
396 self->histogram = NULL;
397
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000398 // BinaryDelayEstimator does not have ownership of |farend|, hence we do not
399 // free the memory here. That should be handled separately by the user.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000400 self->farend = NULL;
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000401
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000402 free(self);
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000403}
404
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000405BinaryDelayEstimator* WebRtc_CreateBinaryDelayEstimator(
Yves Gerey665174f2018-06-19 15:03:05 +0200406 BinaryDelayEstimatorFarend* farend,
407 int max_lookahead) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000408 BinaryDelayEstimator* self = NULL;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000409
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000410 if ((farend != NULL) && (max_lookahead >= 0)) {
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000411 // Sanity conditions fulfilled.
peahbdb7af62016-04-12 14:47:40 -0700412 self = static_cast<BinaryDelayEstimator*>(
413 malloc(sizeof(BinaryDelayEstimator)));
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000414 }
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000415 if (self == NULL) {
416 return NULL;
417 }
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000418
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000419 self->farend = farend;
420 self->near_history_size = max_lookahead + 1;
421 self->history_size = 0;
422 self->robust_validation_enabled = 0; // Disabled by default.
423 self->allowed_offset = 0;
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000424
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000425 self->lookahead = max_lookahead;
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000426
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000427 // Allocate memory for spectrum and history buffers.
428 self->mean_bit_counts = NULL;
429 self->bit_counts = NULL;
430 self->histogram = NULL;
peahbdb7af62016-04-12 14:47:40 -0700431 self->binary_near_history = static_cast<uint32_t*>(
432 malloc((max_lookahead + 1) * sizeof(*self->binary_near_history)));
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000433 if (self->binary_near_history == NULL ||
434 WebRtc_AllocateHistoryBufferMemory(self, farend->history_size) == 0) {
435 WebRtc_FreeBinaryDelayEstimator(self);
436 self = NULL;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000437 }
438
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000439 return self;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000440}
441
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000442int WebRtc_AllocateHistoryBufferMemory(BinaryDelayEstimator* self,
443 int history_size) {
444 BinaryDelayEstimatorFarend* far = self->farend;
445 // (Re-)Allocate memory for spectrum and history buffers.
446 if (history_size != far->history_size) {
447 // Only update far-end buffers if we need.
448 history_size = WebRtc_AllocateFarendBufferMemory(far, history_size);
449 }
450 // The extra array element in |mean_bit_counts| and |histogram| is a dummy
451 // element only used while |last_delay| == -2, i.e., before we have a valid
452 // estimate.
peahbdb7af62016-04-12 14:47:40 -0700453 self->mean_bit_counts = static_cast<int32_t*>(
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000454 realloc(self->mean_bit_counts,
peahbdb7af62016-04-12 14:47:40 -0700455 (history_size + 1) * sizeof(*self->mean_bit_counts)));
456 self->bit_counts = static_cast<int32_t*>(
457 realloc(self->bit_counts, history_size * sizeof(*self->bit_counts)));
458 self->histogram = static_cast<float*>(
459 realloc(self->histogram, (history_size + 1) * sizeof(*self->histogram)));
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000460
Yves Gerey665174f2018-06-19 15:03:05 +0200461 if ((self->mean_bit_counts == NULL) || (self->bit_counts == NULL) ||
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000462 (self->histogram == NULL)) {
463 history_size = 0;
464 }
465 // Fill with zeros if we have expanded the buffers.
466 if (history_size > self->history_size) {
467 int size_diff = history_size - self->history_size;
Yves Gerey665174f2018-06-19 15:03:05 +0200468 memset(&self->mean_bit_counts[self->history_size], 0,
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000469 sizeof(*self->mean_bit_counts) * size_diff);
Yves Gerey665174f2018-06-19 15:03:05 +0200470 memset(&self->bit_counts[self->history_size], 0,
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000471 sizeof(*self->bit_counts) * size_diff);
Yves Gerey665174f2018-06-19 15:03:05 +0200472 memset(&self->histogram[self->history_size], 0,
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000473 sizeof(*self->histogram) * size_diff);
474 }
475 self->history_size = history_size;
476
477 return self->history_size;
478}
479
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000480void WebRtc_InitBinaryDelayEstimator(BinaryDelayEstimator* self) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000481 int i = 0;
kwiberg9e2be5f2016-09-14 05:23:22 -0700482 RTC_DCHECK(self);
andrew@webrtc.org828af1b2011-11-22 22:40:27 +0000483
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000484 memset(self->bit_counts, 0, sizeof(int32_t) * self->history_size);
Yves Gerey665174f2018-06-19 15:03:05 +0200485 memset(self->binary_near_history, 0,
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000486 sizeof(uint32_t) * self->near_history_size);
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000487 for (i = 0; i <= self->history_size; ++i) {
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000488 self->mean_bit_counts[i] = (20 << 9); // 20 in Q9.
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000489 self->histogram[i] = 0.f;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000490 }
Yves Gerey665174f2018-06-19 15:03:05 +0200491 self->minimum_probability = kMaxBitCountsQ9; // 32 in Q9.
492 self->last_delay_probability = (int)kMaxBitCountsQ9; // 32 in Q9.
andrew@webrtc.org828af1b2011-11-22 22:40:27 +0000493
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000494 // Default return value if we're unable to estimate. -1 is used for errors.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000495 self->last_delay = -2;
bjornv@webrtc.orgbd41a842013-11-28 14:58:35 +0000496
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000497 self->last_candidate_delay = -2;
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000498 self->compare_delay = self->history_size;
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000499 self->candidate_hits = 0;
500 self->last_delay_histogram = 0.f;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000501}
502
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000503int WebRtc_SoftResetBinaryDelayEstimator(BinaryDelayEstimator* self,
504 int delay_shift) {
505 int lookahead = 0;
kwiberg9e2be5f2016-09-14 05:23:22 -0700506 RTC_DCHECK(self);
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000507 lookahead = self->lookahead;
508 self->lookahead -= delay_shift;
509 if (self->lookahead < 0) {
510 self->lookahead = 0;
511 }
512 if (self->lookahead > self->near_history_size - 1) {
513 self->lookahead = self->near_history_size - 1;
514 }
515 return lookahead - self->lookahead;
516}
517
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000518int WebRtc_ProcessBinarySpectrum(BinaryDelayEstimator* self,
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000519 uint32_t binary_near_spectrum) {
520 int i = 0;
521 int candidate_delay = -1;
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000522 int valid_candidate = 0;
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000523
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000524 int32_t value_best_candidate = kMaxBitCountsQ9;
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000525 int32_t value_worst_candidate = 0;
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000526 int32_t valley_depth = 0;
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000527
kwiberg9e2be5f2016-09-14 05:23:22 -0700528 RTC_DCHECK(self);
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000529 if (self->farend->history_size != self->history_size) {
530 // Non matching history sizes.
531 return -1;
532 }
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000533 if (self->near_history_size > 1) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000534 // If we apply lookahead, shift near-end binary spectrum history. Insert
535 // current |binary_near_spectrum| and pull out the delayed one.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000536 memmove(&(self->binary_near_history[1]), &(self->binary_near_history[0]),
537 (self->near_history_size - 1) * sizeof(uint32_t));
538 self->binary_near_history[0] = binary_near_spectrum;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000539 binary_near_spectrum = self->binary_near_history[self->lookahead];
andrew@webrtc.org828af1b2011-11-22 22:40:27 +0000540 }
541
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000542 // Compare with delayed spectra and store the |bit_counts| for each delay.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000543 BitCountComparison(binary_near_spectrum, self->farend->binary_far_history,
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000544 self->history_size, self->bit_counts);
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000545
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000546 // Update |mean_bit_counts|, which is the smoothed version of |bit_counts|.
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000547 for (i = 0; i < self->history_size; i++) {
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000548 // |bit_counts| is constrained to [0, 32], meaning we can smooth with a
549 // factor up to 2^26. We use Q9.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000550 int32_t bit_count = (self->bit_counts[i] << 9); // Q9.
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000551
552 // Update |mean_bit_counts| only when far-end signal has something to
553 // contribute. If |far_bit_counts| is zero the far-end signal is weak and
554 // we likely have a poor echo condition, hence don't update.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000555 if (self->farend->far_bit_counts[i] > 0) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000556 // Make number of right shifts piecewise linear w.r.t. |far_bit_counts|.
557 int shifts = kShiftsAtZero;
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000558 shifts -= (kShiftsLinearSlope * self->farend->far_bit_counts[i]) >> 4;
559 WebRtc_MeanEstimatorFix(bit_count, shifts, &(self->mean_bit_counts[i]));
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000560 }
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000561 }
562
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000563 // Find |candidate_delay|, |value_best_candidate| and |value_worst_candidate|
564 // of |mean_bit_counts|.
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000565 for (i = 0; i < self->history_size; i++) {
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000566 if (self->mean_bit_counts[i] < value_best_candidate) {
567 value_best_candidate = self->mean_bit_counts[i];
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000568 candidate_delay = i;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000569 }
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000570 if (self->mean_bit_counts[i] > value_worst_candidate) {
571 value_worst_candidate = self->mean_bit_counts[i];
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000572 }
573 }
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000574 valley_depth = value_worst_candidate - value_best_candidate;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000575
576 // The |value_best_candidate| is a good indicator on the probability of
577 // |candidate_delay| being an accurate delay (a small |value_best_candidate|
578 // means a good binary match). In the following sections we make a decision
579 // whether to update |last_delay| or not.
580 // 1) If the difference bit counts between the best and the worst delay
581 // candidates is too small we consider the situation to be unreliable and
582 // don't update |last_delay|.
583 // 2) If the situation is reliable we update |last_delay| if the value of the
584 // best candidate delay has a value less than
585 // i) an adaptive threshold |minimum_probability|, or
586 // ii) this corresponding value |last_delay_probability|, but updated at
587 // this time instant.
588
589 // Update |minimum_probability|.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000590 if ((self->minimum_probability > kProbabilityLowerLimit) &&
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000591 (valley_depth > kProbabilityMinSpread)) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000592 // The "hard" threshold can't be lower than 17 (in Q9).
593 // The valley in the curve also has to be distinct, i.e., the
594 // difference between |value_worst_candidate| and |value_best_candidate| has
595 // to be large enough.
596 int32_t threshold = value_best_candidate + kProbabilityOffset;
597 if (threshold < kProbabilityLowerLimit) {
598 threshold = kProbabilityLowerLimit;
599 }
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000600 if (self->minimum_probability > threshold) {
601 self->minimum_probability = threshold;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000602 }
603 }
604 // Update |last_delay_probability|.
605 // We use a Markov type model, i.e., a slowly increasing level over time.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000606 self->last_delay_probability++;
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000607 // Validate |candidate_delay|. We have a reliable instantaneous delay
608 // estimate if
609 // 1) The valley is distinct enough (|valley_depth| > |kProbabilityOffset|)
610 // and
611 // 2) The depth of the valley is deep enough
612 // (|value_best_candidate| < |minimum_probability|)
613 // and deeper than the best estimate so far
614 // (|value_best_candidate| < |last_delay_probability|)
615 valid_candidate = ((valley_depth > kProbabilityOffset) &&
Yves Gerey665174f2018-06-19 15:03:05 +0200616 ((value_best_candidate < self->minimum_probability) ||
617 (value_best_candidate < self->last_delay_probability)));
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000618
peahb1fc54d2016-05-12 05:08:45 -0700619 // Check for nonstationary farend signal.
620 const bool non_stationary_farend =
621 std::any_of(self->farend->far_bit_counts,
622 self->farend->far_bit_counts + self->history_size,
623 [](int a) { return a > 0; });
624
625 if (non_stationary_farend) {
626 // Only update the validation statistics when the farend is nonstationary
627 // as the underlying estimates are otherwise frozen.
628 UpdateRobustValidationStatistics(self, candidate_delay, valley_depth,
629 value_best_candidate);
630 }
631
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000632 if (self->robust_validation_enabled) {
Bjorn Volcker532531b2015-05-06 11:58:04 +0200633 int is_histogram_valid = HistogramBasedValidation(self, candidate_delay);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000634 valid_candidate = RobustValidation(self, candidate_delay, valid_candidate,
635 is_histogram_valid);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000636 }
peahb1fc54d2016-05-12 05:08:45 -0700637
638 // Only update the delay estimate when the farend is nonstationary and when
639 // a valid delay candidate is available.
640 if (non_stationary_farend && valid_candidate) {
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000641 if (candidate_delay != self->last_delay) {
bjornv@webrtc.org1e7d6122013-12-16 13:37:28 +0000642 self->last_delay_histogram =
Yves Gerey665174f2018-06-19 15:03:05 +0200643 (self->histogram[candidate_delay] > kLastHistogramMax
644 ? kLastHistogramMax
645 : self->histogram[candidate_delay]);
bjornv@webrtc.org1e7d6122013-12-16 13:37:28 +0000646 // Adjust the histogram if we made a change to |last_delay|, though it was
647 // not the most likely one according to the histogram.
648 if (self->histogram[candidate_delay] <
649 self->histogram[self->compare_delay]) {
650 self->histogram[self->compare_delay] = self->histogram[candidate_delay];
651 }
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000652 }
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000653 self->last_delay = candidate_delay;
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000654 if (value_best_candidate < self->last_delay_probability) {
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000655 self->last_delay_probability = value_best_candidate;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000656 }
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000657 self->compare_delay = self->last_delay;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000658 }
659
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000660 return self->last_delay;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000661}
662
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000663int WebRtc_binary_last_delay(BinaryDelayEstimator* self) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700664 RTC_DCHECK(self);
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000665 return self->last_delay;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000666}
667
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000668float WebRtc_binary_last_delay_quality(BinaryDelayEstimator* self) {
669 float quality = 0;
kwiberg9e2be5f2016-09-14 05:23:22 -0700670 RTC_DCHECK(self);
bjornv@webrtc.orga2d8b752013-01-18 21:54:15 +0000671
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000672 if (self->robust_validation_enabled) {
673 // Simply a linear function of the histogram height at delay estimate.
674 quality = self->histogram[self->compare_delay] / kHistogramMax;
675 } else {
676 // Note that |last_delay_probability| states how deep the minimum of the
677 // cost function is, so it is rather an error probability.
Yves Gerey665174f2018-06-19 15:03:05 +0200678 quality = (float)(kMaxBitCountsQ9 - self->last_delay_probability) /
679 kMaxBitCountsQ9;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000680 if (quality < 0) {
681 quality = 0;
682 }
bjornv@webrtc.org04ecd492013-03-18 14:15:12 +0000683 }
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000684 return quality;
bjornv@webrtc.orga2d8b752013-01-18 21:54:15 +0000685}
686
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000687void WebRtc_MeanEstimatorFix(int32_t new_value,
688 int factor,
689 int32_t* mean_value) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000690 int32_t diff = new_value - *mean_value;
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000691
692 // mean_new = mean_value + ((new_value - mean_value) >> factor);
693 if (diff < 0) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000694 diff = -((-diff) >> factor);
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000695 } else {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000696 diff = (diff >> factor);
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000697 }
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000698 *mean_value += diff;
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000699}