blob: e01495ea695c4e0069db25421b1102af4c057165 [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
bjornv@webrtc.org7ded92b2013-01-30 16:16:59 +000011#include "webrtc/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
Edward Lemurc20978e2017-07-06 19:44:34 +020017#include "webrtc/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
24static const int32_t kProbabilityOffset = 1024; // 2 in Q9.
25static const int32_t kProbabilityLowerLimit = 8704; // 17 in Q9.
26static const int32_t kProbabilityMinSpread = 2816; // 5.5 in Q9.
27
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) {
42 uint32_t tmp = u32 - ((u32 >> 1) & 033333333333) -
43 ((u32 >> 2) & 011111111111);
44 tmp = ((tmp + (tmp >> 3)) & 030707070707);
45 tmp = (tmp + (tmp >> 6));
46 tmp = (tmp + (tmp >> 12) + (tmp >> 24)) & 077;
47
48 return ((int) tmp);
49}
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++) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +000072 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;
99 const int max_hits_for_slow_change = (candidate_delay < self->last_delay) ?
100 kMaxHitsWhenPossiblyNonCausal : kMaxHitsWhenPossiblyCausal;
101 int i = 0;
102
kwiberg9e2be5f2016-09-14 05:23:22 -0700103 RTC_DCHECK_EQ(self->history_size, self->farend->history_size);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000104 // Reset |candidate_hits| if we have a new candidate.
105 if (candidate_delay != self->last_candidate_delay) {
106 self->candidate_hits = 0;
107 self->last_candidate_delay = candidate_delay;
108 }
109 self->candidate_hits++;
110
111 // The |histogram| is updated differently across the bins.
112 // 1. The |candidate_delay| histogram bin is increased with the
113 // |valley_depth|, which is a simple measure of how reliable the
114 // |candidate_delay| is. The histogram is not increased above
115 // |kHistogramMax|.
116 self->histogram[candidate_delay] += valley_depth;
117 if (self->histogram[candidate_delay] > kHistogramMax) {
118 self->histogram[candidate_delay] = kHistogramMax;
119 }
120 // 2. The histogram bins in the neighborhood of |candidate_delay| are
121 // unaffected. The neighborhood is defined as x + {-2, -1, 0, 1}.
122 // 3. The histogram bins in the neighborhood of |last_delay| are decreased
123 // with |decrease_in_last_set|. This value equals the difference between
124 // the cost function values at the locations |candidate_delay| and
125 // |last_delay| until we reach |max_hits_for_slow_change| consecutive hits
126 // at the |candidate_delay|. If we exceed this amount of hits the
127 // |candidate_delay| is a "potential" candidate and we start decreasing
128 // these histogram bins more rapidly with |valley_depth|.
129 if (self->candidate_hits < max_hits_for_slow_change) {
130 decrease_in_last_set = (self->mean_bit_counts[self->compare_delay] -
131 valley_level_q14) * kQ14Scaling;
132 }
133 // 4. All other bins are decreased with |valley_depth|.
134 // TODO(bjornv): Investigate how to make this loop more efficient. Split up
135 // the loop? Remove parts that doesn't add too much.
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000136 for (i = 0; i < self->history_size; ++i) {
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000137 int is_in_last_set = (i >= self->last_delay - 2) &&
138 (i <= self->last_delay + 1) && (i != candidate_delay);
139 int is_in_candidate_set = (i >= candidate_delay - 2) &&
140 (i <= candidate_delay + 1);
141 self->histogram[i] -= decrease_in_last_set * is_in_last_set +
142 valley_depth * (!is_in_last_set && !is_in_candidate_set);
143 // 5. No histogram bin can go below 0.
144 if (self->histogram[i] < 0) {
145 self->histogram[i] = 0;
146 }
147 }
148}
149
150// Validates the |candidate_delay|, estimated in WebRtc_ProcessBinarySpectrum(),
151// based on a mix of counting concurring hits with a modified histogram
152// of recent delay estimates. In brief a candidate is valid (returns 1) if it
153// is the most likely according to the histogram. There are a couple of
154// exceptions that are worth mentioning:
155// 1. If the |candidate_delay| < |last_delay| it can be that we are in a
156// non-causal state, breaking a possible echo control algorithm. Hence, we
157// open up for a quicker change by allowing the change even if the
158// |candidate_delay| is not the most likely one according to the histogram.
159// 2. There's a minimum number of hits (kMinRequiredHits) and the histogram
160// value has to reached a minimum (kMinHistogramThreshold) to be valid.
161// 3. The action is also depending on the filter length used for echo control.
162// If the delay difference is larger than what the filter can capture, we
163// also move quicker towards a change.
164// For further description see commented code.
165//
166// Input:
167// - candidate_delay : The delay to validate.
168//
169// Return value:
170// - is_histogram_valid : 1 - The |candidate_delay| is valid.
171// 0 - Otherwise.
172static int HistogramBasedValidation(const BinaryDelayEstimator* self,
173 int candidate_delay) {
174 float fraction = 1.f;
175 float histogram_threshold = self->histogram[self->compare_delay];
176 const int delay_difference = candidate_delay - self->last_delay;
177 int is_histogram_valid = 0;
178
179 // The histogram based validation of |candidate_delay| is done by comparing
180 // the |histogram| at bin |candidate_delay| with a |histogram_threshold|.
181 // This |histogram_threshold| equals a |fraction| of the |histogram| at bin
182 // |last_delay|. The |fraction| is a piecewise linear function of the
183 // |delay_difference| between the |candidate_delay| and the |last_delay|
184 // allowing for a quicker move if
185 // i) a potential echo control filter can not handle these large differences.
186 // ii) keeping |last_delay| instead of updating to |candidate_delay| could
187 // force an echo control into a non-causal state.
188 // We further require the histogram to have reached a minimum value of
189 // |kMinHistogramThreshold|. In addition, we also require the number of
190 // |candidate_hits| to be more than |kMinRequiredHits| to remove spurious
191 // values.
192
193 // Calculate a comparison histogram value (|histogram_threshold|) that is
194 // depending on the distance between the |candidate_delay| and |last_delay|.
195 // TODO(bjornv): How much can we gain by turning the fraction calculation
196 // into tables?
bjornv@webrtc.orgbccd53d2014-01-08 08:18:15 +0000197 if (delay_difference > self->allowed_offset) {
198 fraction = 1.f - kFractionSlope * (delay_difference - self->allowed_offset);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000199 fraction = (fraction > kMinFractionWhenPossiblyCausal ? fraction :
200 kMinFractionWhenPossiblyCausal);
201 } else if (delay_difference < 0) {
202 fraction = kMinFractionWhenPossiblyNonCausal -
203 kFractionSlope * delay_difference;
204 fraction = (fraction > 1.f ? 1.f : fraction);
205 }
206 histogram_threshold *= fraction;
207 histogram_threshold = (histogram_threshold > kMinHistogramThreshold ?
208 histogram_threshold : kMinHistogramThreshold);
209
210 is_histogram_valid =
211 (self->histogram[candidate_delay] >= histogram_threshold) &&
212 (self->candidate_hits > kMinRequiredHits);
213
214 return is_histogram_valid;
215}
216
217// Performs a robust validation of the |candidate_delay| estimated in
218// WebRtc_ProcessBinarySpectrum(). The algorithm takes the
219// |is_instantaneous_valid| and the |is_histogram_valid| and combines them
220// into a robust validation. The HistogramBasedValidation() has to be called
221// prior to this call.
222// For further description on how the combination is done, see commented code.
223//
224// Inputs:
225// - candidate_delay : The delay to validate.
226// - is_instantaneous_valid : The instantaneous validation performed in
227// WebRtc_ProcessBinarySpectrum().
228// - is_histogram_valid : The histogram based validation.
229//
230// Return value:
231// - is_robust : 1 - The candidate_delay is valid according to a
232// combination of the two inputs.
233// : 0 - Otherwise.
234static int RobustValidation(const BinaryDelayEstimator* self,
235 int candidate_delay,
236 int is_instantaneous_valid,
237 int is_histogram_valid) {
238 int is_robust = 0;
239
240 // The final robust validation is based on the two algorithms; 1) the
241 // |is_instantaneous_valid| and 2) the histogram based with result stored in
242 // |is_histogram_valid|.
243 // i) Before we actually have a valid estimate (|last_delay| == -2), we say
244 // a candidate is valid if either algorithm states so
245 // (|is_instantaneous_valid| OR |is_histogram_valid|).
246 is_robust = (self->last_delay < 0) &&
247 (is_instantaneous_valid || is_histogram_valid);
248 // ii) Otherwise, we need both algorithms to be certain
249 // (|is_instantaneous_valid| AND |is_histogram_valid|)
250 is_robust |= is_instantaneous_valid && is_histogram_valid;
251 // iii) With one exception, i.e., the histogram based algorithm can overrule
252 // the instantaneous one if |is_histogram_valid| = 1 and the histogram
253 // is significantly strong.
254 is_robust |= is_histogram_valid &&
255 (self->histogram[candidate_delay] > self->last_delay_histogram);
256
257 return is_robust;
258}
259
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000260void WebRtc_FreeBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend* self) {
261
262 if (self == NULL) {
263 return;
264 }
265
266 free(self->binary_far_history);
267 self->binary_far_history = NULL;
268
269 free(self->far_bit_counts);
270 self->far_bit_counts = NULL;
271
272 free(self);
273}
274
275BinaryDelayEstimatorFarend* WebRtc_CreateBinaryDelayEstimatorFarend(
276 int history_size) {
bjornv@webrtc.org7ded92b2013-01-30 16:16:59 +0000277 BinaryDelayEstimatorFarend* self = NULL;
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000278
bjornv@webrtc.org7ded92b2013-01-30 16:16:59 +0000279 if (history_size > 1) {
280 // Sanity conditions fulfilled.
peahbdb7af62016-04-12 14:47:40 -0700281 self = static_cast<BinaryDelayEstimatorFarend*>(
282 malloc(sizeof(BinaryDelayEstimatorFarend)));
bjornv@webrtc.org7ded92b2013-01-30 16:16:59 +0000283 }
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000284 if (self == NULL) {
285 return NULL;
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000286 }
287
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000288 self->history_size = 0;
289 self->binary_far_history = NULL;
290 self->far_bit_counts = NULL;
291 if (WebRtc_AllocateFarendBufferMemory(self, history_size) == 0) {
292 WebRtc_FreeBinaryDelayEstimatorFarend(self);
293 self = NULL;
294 }
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000295 return self;
296}
297
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000298int WebRtc_AllocateFarendBufferMemory(BinaryDelayEstimatorFarend* self,
299 int history_size) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700300 RTC_DCHECK(self);
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000301 // (Re-)Allocate memory for history buffers.
peahbdb7af62016-04-12 14:47:40 -0700302 self->binary_far_history = static_cast<uint32_t*>(
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000303 realloc(self->binary_far_history,
peahbdb7af62016-04-12 14:47:40 -0700304 history_size * sizeof(*self->binary_far_history)));
305 self->far_bit_counts = static_cast<int*>(
306 realloc(self->far_bit_counts,
307 history_size * sizeof(*self->far_bit_counts)));
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000308 if ((self->binary_far_history == NULL) || (self->far_bit_counts == NULL)) {
309 history_size = 0;
310 }
311 // Fill with zeros if we have expanded the buffers.
312 if (history_size > self->history_size) {
313 int size_diff = history_size - self->history_size;
314 memset(&self->binary_far_history[self->history_size],
315 0,
316 sizeof(*self->binary_far_history) * size_diff);
317 memset(&self->far_bit_counts[self->history_size],
318 0,
319 sizeof(*self->far_bit_counts) * size_diff);
320 }
321 self->history_size = history_size;
322
323 return self->history_size;
324}
325
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000326void WebRtc_InitBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend* self) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700327 RTC_DCHECK(self);
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000328 memset(self->binary_far_history, 0, sizeof(uint32_t) * self->history_size);
329 memset(self->far_bit_counts, 0, sizeof(int) * self->history_size);
330}
331
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000332void WebRtc_SoftResetBinaryDelayEstimatorFarend(
333 BinaryDelayEstimatorFarend* self, int delay_shift) {
334 int abs_shift = abs(delay_shift);
335 int shift_size = 0;
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000336 int dest_index = 0;
337 int src_index = 0;
338 int padding_index = 0;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000339
kwiberg9e2be5f2016-09-14 05:23:22 -0700340 RTC_DCHECK(self);
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000341 shift_size = self->history_size - abs_shift;
kwiberg9e2be5f2016-09-14 05:23:22 -0700342 RTC_DCHECK_GT(shift_size, 0);
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000343 if (delay_shift == 0) {
344 return;
345 } else if (delay_shift > 0) {
346 dest_index = abs_shift;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000347 } else if (delay_shift < 0) {
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000348 src_index = abs_shift;
349 padding_index = shift_size;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000350 }
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000351
352 // Shift and zero pad buffers.
353 memmove(&self->binary_far_history[dest_index],
354 &self->binary_far_history[src_index],
355 sizeof(*self->binary_far_history) * shift_size);
356 memset(&self->binary_far_history[padding_index], 0,
357 sizeof(*self->binary_far_history) * abs_shift);
358 memmove(&self->far_bit_counts[dest_index],
359 &self->far_bit_counts[src_index],
360 sizeof(*self->far_bit_counts) * shift_size);
361 memset(&self->far_bit_counts[padding_index], 0,
362 sizeof(*self->far_bit_counts) * abs_shift);
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000363}
364
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000365void WebRtc_AddBinaryFarSpectrum(BinaryDelayEstimatorFarend* handle,
366 uint32_t binary_far_spectrum) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700367 RTC_DCHECK(handle);
bjornv@webrtc.org94c213a2013-01-25 15:53:41 +0000368 // Shift binary spectrum history and insert current |binary_far_spectrum|.
369 memmove(&(handle->binary_far_history[1]), &(handle->binary_far_history[0]),
370 (handle->history_size - 1) * sizeof(uint32_t));
371 handle->binary_far_history[0] = binary_far_spectrum;
372
373 // Shift history of far-end binary spectrum bit counts and insert bit count
374 // of current |binary_far_spectrum|.
375 memmove(&(handle->far_bit_counts[1]), &(handle->far_bit_counts[0]),
376 (handle->history_size - 1) * sizeof(int));
377 handle->far_bit_counts[0] = BitCount(binary_far_spectrum);
378}
379
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000380void WebRtc_FreeBinaryDelayEstimator(BinaryDelayEstimator* self) {
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000381
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(
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000406 BinaryDelayEstimatorFarend* farend, int max_lookahead) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000407 BinaryDelayEstimator* self = NULL;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000408
bjornv@webrtc.org240eec32014-04-03 08:11:47 +0000409 if ((farend != NULL) && (max_lookahead >= 0)) {
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000410 // Sanity conditions fulfilled.
peahbdb7af62016-04-12 14:47:40 -0700411 self = static_cast<BinaryDelayEstimator*>(
412 malloc(sizeof(BinaryDelayEstimator)));
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000413 }
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000414 if (self == NULL) {
415 return NULL;
416 }
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000417
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000418 self->farend = farend;
419 self->near_history_size = max_lookahead + 1;
420 self->history_size = 0;
421 self->robust_validation_enabled = 0; // Disabled by default.
422 self->allowed_offset = 0;
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000423
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000424 self->lookahead = max_lookahead;
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000425
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000426 // Allocate memory for spectrum and history buffers.
427 self->mean_bit_counts = NULL;
428 self->bit_counts = NULL;
429 self->histogram = NULL;
peahbdb7af62016-04-12 14:47:40 -0700430 self->binary_near_history = static_cast<uint32_t*>(
431 malloc((max_lookahead + 1) * sizeof(*self->binary_near_history)));
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000432 if (self->binary_near_history == NULL ||
433 WebRtc_AllocateHistoryBufferMemory(self, farend->history_size) == 0) {
434 WebRtc_FreeBinaryDelayEstimator(self);
435 self = NULL;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000436 }
437
bjornv@webrtc.org2e729762012-04-18 08:30:29 +0000438 return self;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000439}
440
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000441int WebRtc_AllocateHistoryBufferMemory(BinaryDelayEstimator* self,
442 int history_size) {
443 BinaryDelayEstimatorFarend* far = self->farend;
444 // (Re-)Allocate memory for spectrum and history buffers.
445 if (history_size != far->history_size) {
446 // Only update far-end buffers if we need.
447 history_size = WebRtc_AllocateFarendBufferMemory(far, history_size);
448 }
449 // The extra array element in |mean_bit_counts| and |histogram| is a dummy
450 // element only used while |last_delay| == -2, i.e., before we have a valid
451 // estimate.
peahbdb7af62016-04-12 14:47:40 -0700452 self->mean_bit_counts = static_cast<int32_t*>(
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000453 realloc(self->mean_bit_counts,
peahbdb7af62016-04-12 14:47:40 -0700454 (history_size + 1) * sizeof(*self->mean_bit_counts)));
455 self->bit_counts = static_cast<int32_t*>(
456 realloc(self->bit_counts, history_size * sizeof(*self->bit_counts)));
457 self->histogram = static_cast<float*>(
458 realloc(self->histogram, (history_size + 1) * sizeof(*self->histogram)));
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000459
460 if ((self->mean_bit_counts == NULL) ||
461 (self->bit_counts == NULL) ||
462 (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;
468 memset(&self->mean_bit_counts[self->history_size],
469 0,
470 sizeof(*self->mean_bit_counts) * size_diff);
471 memset(&self->bit_counts[self->history_size],
472 0,
473 sizeof(*self->bit_counts) * size_diff);
474 memset(&self->histogram[self->history_size],
475 0,
476 sizeof(*self->histogram) * size_diff);
477 }
478 self->history_size = history_size;
479
480 return self->history_size;
481}
482
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000483void WebRtc_InitBinaryDelayEstimator(BinaryDelayEstimator* self) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000484 int i = 0;
kwiberg9e2be5f2016-09-14 05:23:22 -0700485 RTC_DCHECK(self);
andrew@webrtc.org828af1b2011-11-22 22:40:27 +0000486
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000487 memset(self->bit_counts, 0, sizeof(int32_t) * self->history_size);
488 memset(self->binary_near_history,
489 0,
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000490 sizeof(uint32_t) * self->near_history_size);
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000491 for (i = 0; i <= self->history_size; ++i) {
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000492 self->mean_bit_counts[i] = (20 << 9); // 20 in Q9.
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000493 self->histogram[i] = 0.f;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000494 }
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000495 self->minimum_probability = kMaxBitCountsQ9; // 32 in Q9.
496 self->last_delay_probability = (int) kMaxBitCountsQ9; // 32 in Q9.
andrew@webrtc.org828af1b2011-11-22 22:40:27 +0000497
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000498 // Default return value if we're unable to estimate. -1 is used for errors.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000499 self->last_delay = -2;
bjornv@webrtc.orgbd41a842013-11-28 14:58:35 +0000500
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000501 self->last_candidate_delay = -2;
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000502 self->compare_delay = self->history_size;
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000503 self->candidate_hits = 0;
504 self->last_delay_histogram = 0.f;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000505}
506
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000507int WebRtc_SoftResetBinaryDelayEstimator(BinaryDelayEstimator* self,
508 int delay_shift) {
509 int lookahead = 0;
kwiberg9e2be5f2016-09-14 05:23:22 -0700510 RTC_DCHECK(self);
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000511 lookahead = self->lookahead;
512 self->lookahead -= delay_shift;
513 if (self->lookahead < 0) {
514 self->lookahead = 0;
515 }
516 if (self->lookahead > self->near_history_size - 1) {
517 self->lookahead = self->near_history_size - 1;
518 }
519 return lookahead - self->lookahead;
520}
521
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000522int WebRtc_ProcessBinarySpectrum(BinaryDelayEstimator* self,
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000523 uint32_t binary_near_spectrum) {
524 int i = 0;
525 int candidate_delay = -1;
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000526 int valid_candidate = 0;
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000527
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000528 int32_t value_best_candidate = kMaxBitCountsQ9;
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000529 int32_t value_worst_candidate = 0;
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000530 int32_t valley_depth = 0;
bjornv@webrtc.orgbb599b72013-01-18 23:16:46 +0000531
kwiberg9e2be5f2016-09-14 05:23:22 -0700532 RTC_DCHECK(self);
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000533 if (self->farend->history_size != self->history_size) {
534 // Non matching history sizes.
535 return -1;
536 }
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000537 if (self->near_history_size > 1) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000538 // If we apply lookahead, shift near-end binary spectrum history. Insert
539 // current |binary_near_spectrum| and pull out the delayed one.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000540 memmove(&(self->binary_near_history[1]), &(self->binary_near_history[0]),
541 (self->near_history_size - 1) * sizeof(uint32_t));
542 self->binary_near_history[0] = binary_near_spectrum;
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000543 binary_near_spectrum = self->binary_near_history[self->lookahead];
andrew@webrtc.org828af1b2011-11-22 22:40:27 +0000544 }
545
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000546 // Compare with delayed spectra and store the |bit_counts| for each delay.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000547 BitCountComparison(binary_near_spectrum, self->farend->binary_far_history,
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000548 self->history_size, self->bit_counts);
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000549
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000550 // Update |mean_bit_counts|, which is the smoothed version of |bit_counts|.
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000551 for (i = 0; i < self->history_size; i++) {
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000552 // |bit_counts| is constrained to [0, 32], meaning we can smooth with a
553 // factor up to 2^26. We use Q9.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000554 int32_t bit_count = (self->bit_counts[i] << 9); // Q9.
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000555
556 // Update |mean_bit_counts| only when far-end signal has something to
557 // contribute. If |far_bit_counts| is zero the far-end signal is weak and
558 // we likely have a poor echo condition, hence don't update.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000559 if (self->farend->far_bit_counts[i] > 0) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000560 // Make number of right shifts piecewise linear w.r.t. |far_bit_counts|.
561 int shifts = kShiftsAtZero;
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000562 shifts -= (kShiftsLinearSlope * self->farend->far_bit_counts[i]) >> 4;
563 WebRtc_MeanEstimatorFix(bit_count, shifts, &(self->mean_bit_counts[i]));
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000564 }
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000565 }
566
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000567 // Find |candidate_delay|, |value_best_candidate| and |value_worst_candidate|
568 // of |mean_bit_counts|.
bjornv@webrtc.org69ef9912014-07-03 14:59:03 +0000569 for (i = 0; i < self->history_size; i++) {
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000570 if (self->mean_bit_counts[i] < value_best_candidate) {
571 value_best_candidate = self->mean_bit_counts[i];
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000572 candidate_delay = i;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000573 }
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000574 if (self->mean_bit_counts[i] > value_worst_candidate) {
575 value_worst_candidate = self->mean_bit_counts[i];
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000576 }
577 }
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000578 valley_depth = value_worst_candidate - value_best_candidate;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000579
580 // The |value_best_candidate| is a good indicator on the probability of
581 // |candidate_delay| being an accurate delay (a small |value_best_candidate|
582 // means a good binary match). In the following sections we make a decision
583 // whether to update |last_delay| or not.
584 // 1) If the difference bit counts between the best and the worst delay
585 // candidates is too small we consider the situation to be unreliable and
586 // don't update |last_delay|.
587 // 2) If the situation is reliable we update |last_delay| if the value of the
588 // best candidate delay has a value less than
589 // i) an adaptive threshold |minimum_probability|, or
590 // ii) this corresponding value |last_delay_probability|, but updated at
591 // this time instant.
592
593 // Update |minimum_probability|.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000594 if ((self->minimum_probability > kProbabilityLowerLimit) &&
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000595 (valley_depth > kProbabilityMinSpread)) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000596 // The "hard" threshold can't be lower than 17 (in Q9).
597 // The valley in the curve also has to be distinct, i.e., the
598 // difference between |value_worst_candidate| and |value_best_candidate| has
599 // to be large enough.
600 int32_t threshold = value_best_candidate + kProbabilityOffset;
601 if (threshold < kProbabilityLowerLimit) {
602 threshold = kProbabilityLowerLimit;
603 }
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000604 if (self->minimum_probability > threshold) {
605 self->minimum_probability = threshold;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000606 }
607 }
608 // Update |last_delay_probability|.
609 // We use a Markov type model, i.e., a slowly increasing level over time.
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000610 self->last_delay_probability++;
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000611 // Validate |candidate_delay|. We have a reliable instantaneous delay
612 // estimate if
613 // 1) The valley is distinct enough (|valley_depth| > |kProbabilityOffset|)
614 // and
615 // 2) The depth of the valley is deep enough
616 // (|value_best_candidate| < |minimum_probability|)
617 // and deeper than the best estimate so far
618 // (|value_best_candidate| < |last_delay_probability|)
619 valid_candidate = ((valley_depth > kProbabilityOffset) &&
620 ((value_best_candidate < self->minimum_probability) ||
621 (value_best_candidate < self->last_delay_probability)));
622
peahb1fc54d2016-05-12 05:08:45 -0700623 // Check for nonstationary farend signal.
624 const bool non_stationary_farend =
625 std::any_of(self->farend->far_bit_counts,
626 self->farend->far_bit_counts + self->history_size,
627 [](int a) { return a > 0; });
628
629 if (non_stationary_farend) {
630 // Only update the validation statistics when the farend is nonstationary
631 // as the underlying estimates are otherwise frozen.
632 UpdateRobustValidationStatistics(self, candidate_delay, valley_depth,
633 value_best_candidate);
634 }
635
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000636 if (self->robust_validation_enabled) {
Bjorn Volcker532531b2015-05-06 11:58:04 +0200637 int is_histogram_valid = HistogramBasedValidation(self, candidate_delay);
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000638 valid_candidate = RobustValidation(self, candidate_delay, valid_candidate,
639 is_histogram_valid);
640
641 }
peahb1fc54d2016-05-12 05:08:45 -0700642
643 // Only update the delay estimate when the farend is nonstationary and when
644 // a valid delay candidate is available.
645 if (non_stationary_farend && valid_candidate) {
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000646 if (candidate_delay != self->last_delay) {
bjornv@webrtc.org1e7d6122013-12-16 13:37:28 +0000647 self->last_delay_histogram =
648 (self->histogram[candidate_delay] > kLastHistogramMax ?
649 kLastHistogramMax : self->histogram[candidate_delay]);
650 // Adjust the histogram if we made a change to |last_delay|, though it was
651 // not the most likely one according to the histogram.
652 if (self->histogram[candidate_delay] <
653 self->histogram[self->compare_delay]) {
654 self->histogram[self->compare_delay] = self->histogram[candidate_delay];
655 }
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000656 }
bjornv@webrtc.orgd1a1c352013-11-28 11:45:05 +0000657 self->last_delay = candidate_delay;
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000658 if (value_best_candidate < self->last_delay_probability) {
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000659 self->last_delay_probability = value_best_candidate;
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000660 }
bjornv@webrtc.org5c645082013-12-16 10:57:53 +0000661 self->compare_delay = self->last_delay;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000662 }
663
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000664 return self->last_delay;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000665}
666
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000667int WebRtc_binary_last_delay(BinaryDelayEstimator* self) {
kwiberg9e2be5f2016-09-14 05:23:22 -0700668 RTC_DCHECK(self);
bjornv@webrtc.org57f3a112013-01-25 22:02:15 +0000669 return self->last_delay;
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000670}
671
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000672float WebRtc_binary_last_delay_quality(BinaryDelayEstimator* self) {
673 float quality = 0;
kwiberg9e2be5f2016-09-14 05:23:22 -0700674 RTC_DCHECK(self);
bjornv@webrtc.orga2d8b752013-01-18 21:54:15 +0000675
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000676 if (self->robust_validation_enabled) {
677 // Simply a linear function of the histogram height at delay estimate.
678 quality = self->histogram[self->compare_delay] / kHistogramMax;
679 } else {
680 // Note that |last_delay_probability| states how deep the minimum of the
681 // cost function is, so it is rather an error probability.
682 quality = (float) (kMaxBitCountsQ9 - self->last_delay_probability) /
683 kMaxBitCountsQ9;
684 if (quality < 0) {
685 quality = 0;
686 }
bjornv@webrtc.org04ecd492013-03-18 14:15:12 +0000687 }
bjornv@webrtc.org28e83d12014-03-24 15:26:52 +0000688 return quality;
bjornv@webrtc.orga2d8b752013-01-18 21:54:15 +0000689}
690
bjornv@webrtc.org6a9835d2011-11-18 08:30:34 +0000691void WebRtc_MeanEstimatorFix(int32_t new_value,
692 int factor,
693 int32_t* mean_value) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000694 int32_t diff = new_value - *mean_value;
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000695
696 // mean_new = mean_value + ((new_value - mean_value) >> factor);
697 if (diff < 0) {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000698 diff = -((-diff) >> factor);
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000699 } else {
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000700 diff = (diff >> factor);
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000701 }
bjornv@webrtc.org70adcd42011-12-29 14:51:21 +0000702 *mean_value += diff;
bjornv@google.comb47d4b22011-09-15 12:27:36 +0000703}