• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3  *
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 
11 #include "webrtc/modules/audio_processing/utility/delay_estimator.h"
12 
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
16 
17 // Number of right shifts for scaling is linearly depending on number of bits in
18 // the far-end binary spectrum.
19 static const int kShiftsAtZero = 13;  // Right shifts at zero binary spectrum.
20 static const int kShiftsLinearSlope = 3;
21 
22 static const int32_t kProbabilityOffset = 1024;  // 2 in Q9.
23 static const int32_t kProbabilityLowerLimit = 8704;  // 17 in Q9.
24 static const int32_t kProbabilityMinSpread = 2816;  // 5.5 in Q9.
25 
26 // Robust validation settings
27 static const float kHistogramMax = 3000.f;
28 static const float kLastHistogramMax = 250.f;
29 static const float kMinHistogramThreshold = 1.5f;
30 static const int kMinRequiredHits = 10;
31 static const int kMaxHitsWhenPossiblyNonCausal = 10;
32 static const int kMaxHitsWhenPossiblyCausal = 1000;
33 static const float kQ14Scaling = 1.f / (1 << 14);  // Scaling by 2^14 to get Q0.
34 static const float kFractionSlope = 0.05f;
35 static const float kMinFractionWhenPossiblyCausal = 0.5f;
36 static const float kMinFractionWhenPossiblyNonCausal = 0.25f;
37 
38 // Counts and returns number of bits of a 32-bit word.
BitCount(uint32_t u32)39 static int BitCount(uint32_t u32) {
40   uint32_t tmp = u32 - ((u32 >> 1) & 033333333333) -
41       ((u32 >> 2) & 011111111111);
42   tmp = ((tmp + (tmp >> 3)) & 030707070707);
43   tmp = (tmp + (tmp >> 6));
44   tmp = (tmp + (tmp >> 12) + (tmp >> 24)) & 077;
45 
46   return ((int) tmp);
47 }
48 
49 // Compares the |binary_vector| with all rows of the |binary_matrix| and counts
50 // per row the number of times they have the same value.
51 //
52 // Inputs:
53 //      - binary_vector     : binary "vector" stored in a long
54 //      - binary_matrix     : binary "matrix" stored as a vector of long
55 //      - matrix_size       : size of binary "matrix"
56 //
57 // Output:
58 //      - bit_counts        : "Vector" stored as a long, containing for each
59 //                            row the number of times the matrix row and the
60 //                            input vector have the same value
61 //
BitCountComparison(uint32_t binary_vector,const uint32_t * binary_matrix,int matrix_size,int32_t * bit_counts)62 static void BitCountComparison(uint32_t binary_vector,
63                                const uint32_t* binary_matrix,
64                                int matrix_size,
65                                int32_t* bit_counts) {
66   int n = 0;
67 
68   // Compare |binary_vector| with all rows of the |binary_matrix|
69   for (; n < matrix_size; n++) {
70     bit_counts[n] = (int32_t) BitCount(binary_vector ^ binary_matrix[n]);
71   }
72 }
73 
74 // Collects necessary statistics for the HistogramBasedValidation().  This
75 // function has to be called prior to calling HistogramBasedValidation().  The
76 // statistics updated and used by the HistogramBasedValidation() are:
77 //  1. the number of |candidate_hits|, which states for how long we have had the
78 //     same |candidate_delay|
79 //  2. the |histogram| of candidate delays over time.  This histogram is
80 //     weighted with respect to a reliability measure and time-varying to cope
81 //     with possible delay shifts.
82 // For further description see commented code.
83 //
84 // Inputs:
85 //  - candidate_delay   : The delay to validate.
86 //  - valley_depth_q14  : The cost function has a valley/minimum at the
87 //                        |candidate_delay| location.  |valley_depth_q14| is the
88 //                        cost function difference between the minimum and
89 //                        maximum locations.  The value is in the Q14 domain.
90 //  - valley_level_q14  : Is the cost function value at the minimum, in Q14.
UpdateRobustValidationStatistics(BinaryDelayEstimator * self,int candidate_delay,int32_t valley_depth_q14,int32_t valley_level_q14)91 static void UpdateRobustValidationStatistics(BinaryDelayEstimator* self,
92                                              int candidate_delay,
93                                              int32_t valley_depth_q14,
94                                              int32_t valley_level_q14) {
95   const float valley_depth = valley_depth_q14 * kQ14Scaling;
96   float decrease_in_last_set = valley_depth;
97   const int max_hits_for_slow_change = (candidate_delay < self->last_delay) ?
98       kMaxHitsWhenPossiblyNonCausal : kMaxHitsWhenPossiblyCausal;
99   int i = 0;
100 
101   // Reset |candidate_hits| if we have a new candidate.
102   if (candidate_delay != self->last_candidate_delay) {
103     self->candidate_hits = 0;
104     self->last_candidate_delay = candidate_delay;
105   }
106   self->candidate_hits++;
107 
108   // The |histogram| is updated differently across the bins.
109   // 1. The |candidate_delay| histogram bin is increased with the
110   //    |valley_depth|, which is a simple measure of how reliable the
111   //    |candidate_delay| is.  The histogram is not increased above
112   //    |kHistogramMax|.
113   self->histogram[candidate_delay] += valley_depth;
114   if (self->histogram[candidate_delay] > kHistogramMax) {
115     self->histogram[candidate_delay] = kHistogramMax;
116   }
117   // 2. The histogram bins in the neighborhood of |candidate_delay| are
118   //    unaffected.  The neighborhood is defined as x + {-2, -1, 0, 1}.
119   // 3. The histogram bins in the neighborhood of |last_delay| are decreased
120   //    with |decrease_in_last_set|.  This value equals the difference between
121   //    the cost function values at the locations |candidate_delay| and
122   //    |last_delay| until we reach |max_hits_for_slow_change| consecutive hits
123   //    at the |candidate_delay|.  If we exceed this amount of hits the
124   //    |candidate_delay| is a "potential" candidate and we start decreasing
125   //    these histogram bins more rapidly with |valley_depth|.
126   if (self->candidate_hits < max_hits_for_slow_change) {
127     decrease_in_last_set = (self->mean_bit_counts[self->compare_delay] -
128         valley_level_q14) * kQ14Scaling;
129   }
130   // 4. All other bins are decreased with |valley_depth|.
131   // TODO(bjornv): Investigate how to make this loop more efficient.  Split up
132   // the loop?  Remove parts that doesn't add too much.
133   for (i = 0; i < self->farend->history_size; ++i) {
134     int is_in_last_set = (i >= self->last_delay - 2) &&
135         (i <= self->last_delay + 1) && (i != candidate_delay);
136     int is_in_candidate_set = (i >= candidate_delay - 2) &&
137         (i <= candidate_delay + 1);
138     self->histogram[i] -= decrease_in_last_set * is_in_last_set +
139         valley_depth * (!is_in_last_set && !is_in_candidate_set);
140     // 5. No histogram bin can go below 0.
141     if (self->histogram[i] < 0) {
142       self->histogram[i] = 0;
143     }
144   }
145 }
146 
147 // Validates the |candidate_delay|, estimated in WebRtc_ProcessBinarySpectrum(),
148 // based on a mix of counting concurring hits with a modified histogram
149 // of recent delay estimates.  In brief a candidate is valid (returns 1) if it
150 // is the most likely according to the histogram.  There are a couple of
151 // exceptions that are worth mentioning:
152 //  1. If the |candidate_delay| < |last_delay| it can be that we are in a
153 //     non-causal state, breaking a possible echo control algorithm.  Hence, we
154 //     open up for a quicker change by allowing the change even if the
155 //     |candidate_delay| is not the most likely one according to the histogram.
156 //  2. There's a minimum number of hits (kMinRequiredHits) and the histogram
157 //     value has to reached a minimum (kMinHistogramThreshold) to be valid.
158 //  3. The action is also depending on the filter length used for echo control.
159 //     If the delay difference is larger than what the filter can capture, we
160 //     also move quicker towards a change.
161 // For further description see commented code.
162 //
163 // Input:
164 //  - candidate_delay     : The delay to validate.
165 //
166 // Return value:
167 //  - is_histogram_valid  : 1 - The |candidate_delay| is valid.
168 //                          0 - Otherwise.
HistogramBasedValidation(const BinaryDelayEstimator * self,int candidate_delay)169 static int HistogramBasedValidation(const BinaryDelayEstimator* self,
170                                     int candidate_delay) {
171   float fraction = 1.f;
172   float histogram_threshold = self->histogram[self->compare_delay];
173   const int delay_difference = candidate_delay - self->last_delay;
174   int is_histogram_valid = 0;
175 
176   // The histogram based validation of |candidate_delay| is done by comparing
177   // the |histogram| at bin |candidate_delay| with a |histogram_threshold|.
178   // This |histogram_threshold| equals a |fraction| of the |histogram| at bin
179   // |last_delay|.  The |fraction| is a piecewise linear function of the
180   // |delay_difference| between the |candidate_delay| and the |last_delay|
181   // allowing for a quicker move if
182   //  i) a potential echo control filter can not handle these large differences.
183   // ii) keeping |last_delay| instead of updating to |candidate_delay| could
184   //     force an echo control into a non-causal state.
185   // We further require the histogram to have reached a minimum value of
186   // |kMinHistogramThreshold|.  In addition, we also require the number of
187   // |candidate_hits| to be more than |kMinRequiredHits| to remove spurious
188   // values.
189 
190   // Calculate a comparison histogram value (|histogram_threshold|) that is
191   // depending on the distance between the |candidate_delay| and |last_delay|.
192   // TODO(bjornv): How much can we gain by turning the fraction calculation
193   // into tables?
194   if (delay_difference > self->allowed_offset) {
195     fraction = 1.f - kFractionSlope * (delay_difference - self->allowed_offset);
196     fraction = (fraction > kMinFractionWhenPossiblyCausal ? fraction :
197         kMinFractionWhenPossiblyCausal);
198   } else if (delay_difference < 0) {
199     fraction = kMinFractionWhenPossiblyNonCausal -
200         kFractionSlope * delay_difference;
201     fraction = (fraction > 1.f ? 1.f : fraction);
202   }
203   histogram_threshold *= fraction;
204   histogram_threshold = (histogram_threshold > kMinHistogramThreshold ?
205       histogram_threshold : kMinHistogramThreshold);
206 
207   is_histogram_valid =
208       (self->histogram[candidate_delay] >= histogram_threshold) &&
209       (self->candidate_hits > kMinRequiredHits);
210 
211   return is_histogram_valid;
212 }
213 
214 // Performs a robust validation of the |candidate_delay| estimated in
215 // WebRtc_ProcessBinarySpectrum().  The algorithm takes the
216 // |is_instantaneous_valid| and the |is_histogram_valid| and combines them
217 // into a robust validation.  The HistogramBasedValidation() has to be called
218 // prior to this call.
219 // For further description on how the combination is done, see commented code.
220 //
221 // Inputs:
222 //  - candidate_delay         : The delay to validate.
223 //  - is_instantaneous_valid  : The instantaneous validation performed in
224 //                              WebRtc_ProcessBinarySpectrum().
225 //  - is_histogram_valid      : The histogram based validation.
226 //
227 // Return value:
228 //  - is_robust               : 1 - The candidate_delay is valid according to a
229 //                                  combination of the two inputs.
230 //                            : 0 - Otherwise.
RobustValidation(const BinaryDelayEstimator * self,int candidate_delay,int is_instantaneous_valid,int is_histogram_valid)231 static int RobustValidation(const BinaryDelayEstimator* self,
232                             int candidate_delay,
233                             int is_instantaneous_valid,
234                             int is_histogram_valid) {
235   int is_robust = 0;
236 
237   // The final robust validation is based on the two algorithms; 1) the
238   // |is_instantaneous_valid| and 2) the histogram based with result stored in
239   // |is_histogram_valid|.
240   //   i) Before we actually have a valid estimate (|last_delay| == -2), we say
241   //      a candidate is valid if either algorithm states so
242   //      (|is_instantaneous_valid| OR |is_histogram_valid|).
243   is_robust = (self->last_delay < 0) &&
244       (is_instantaneous_valid || is_histogram_valid);
245   //  ii) Otherwise, we need both algorithms to be certain
246   //      (|is_instantaneous_valid| AND |is_histogram_valid|)
247   is_robust |= is_instantaneous_valid && is_histogram_valid;
248   // iii) With one exception, i.e., the histogram based algorithm can overrule
249   //      the instantaneous one if |is_histogram_valid| = 1 and the histogram
250   //      is significantly strong.
251   is_robust |= is_histogram_valid &&
252       (self->histogram[candidate_delay] > self->last_delay_histogram);
253 
254   return is_robust;
255 }
256 
WebRtc_FreeBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend * self)257 void WebRtc_FreeBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend* self) {
258 
259   if (self == NULL) {
260     return;
261   }
262 
263   free(self->binary_far_history);
264   self->binary_far_history = NULL;
265 
266   free(self->far_bit_counts);
267   self->far_bit_counts = NULL;
268 
269   free(self);
270 }
271 
WebRtc_CreateBinaryDelayEstimatorFarend(int history_size)272 BinaryDelayEstimatorFarend* WebRtc_CreateBinaryDelayEstimatorFarend(
273     int history_size) {
274   BinaryDelayEstimatorFarend* self = NULL;
275 
276   if (history_size > 1) {
277     // Sanity conditions fulfilled.
278     self = malloc(sizeof(BinaryDelayEstimatorFarend));
279   }
280   if (self != NULL) {
281     int malloc_fail = 0;
282 
283     self->history_size = history_size;
284 
285     // Allocate memory for history buffers.
286     self->binary_far_history = malloc(history_size * sizeof(uint32_t));
287     malloc_fail |= (self->binary_far_history == NULL);
288 
289     self->far_bit_counts = malloc(history_size * sizeof(int));
290     malloc_fail |= (self->far_bit_counts == NULL);
291 
292     if (malloc_fail) {
293       WebRtc_FreeBinaryDelayEstimatorFarend(self);
294       self = NULL;
295     }
296   }
297 
298   return self;
299 }
300 
WebRtc_InitBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend * self)301 void WebRtc_InitBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend* self) {
302   assert(self != NULL);
303   memset(self->binary_far_history, 0, sizeof(uint32_t) * self->history_size);
304   memset(self->far_bit_counts, 0, sizeof(int) * self->history_size);
305 }
306 
WebRtc_SoftResetBinaryDelayEstimatorFarend(BinaryDelayEstimatorFarend * self,int delay_shift)307 void WebRtc_SoftResetBinaryDelayEstimatorFarend(
308     BinaryDelayEstimatorFarend* self, int delay_shift) {
309   int abs_shift = abs(delay_shift);
310   int shift_size = 0;
311   int dest_index = 0;
312   int src_index = 0;
313   int padding_index = 0;
314 
315   assert(self != NULL);
316   shift_size = self->history_size - abs_shift;
317   assert(shift_size > 0);
318   if (delay_shift == 0) {
319     return;
320   } else if (delay_shift > 0) {
321     dest_index = abs_shift;
322   } else if (delay_shift < 0) {
323     src_index = abs_shift;
324     padding_index = shift_size;
325   }
326 
327   // Shift and zero pad buffers.
328   memmove(&self->binary_far_history[dest_index],
329           &self->binary_far_history[src_index],
330           sizeof(*self->binary_far_history) * shift_size);
331   memset(&self->binary_far_history[padding_index], 0,
332          sizeof(*self->binary_far_history) * abs_shift);
333   memmove(&self->far_bit_counts[dest_index],
334           &self->far_bit_counts[src_index],
335           sizeof(*self->far_bit_counts) * shift_size);
336   memset(&self->far_bit_counts[padding_index], 0,
337          sizeof(*self->far_bit_counts) * abs_shift);
338 }
339 
WebRtc_AddBinaryFarSpectrum(BinaryDelayEstimatorFarend * handle,uint32_t binary_far_spectrum)340 void WebRtc_AddBinaryFarSpectrum(BinaryDelayEstimatorFarend* handle,
341                                  uint32_t binary_far_spectrum) {
342   assert(handle != NULL);
343   // Shift binary spectrum history and insert current |binary_far_spectrum|.
344   memmove(&(handle->binary_far_history[1]), &(handle->binary_far_history[0]),
345           (handle->history_size - 1) * sizeof(uint32_t));
346   handle->binary_far_history[0] = binary_far_spectrum;
347 
348   // Shift history of far-end binary spectrum bit counts and insert bit count
349   // of current |binary_far_spectrum|.
350   memmove(&(handle->far_bit_counts[1]), &(handle->far_bit_counts[0]),
351           (handle->history_size - 1) * sizeof(int));
352   handle->far_bit_counts[0] = BitCount(binary_far_spectrum);
353 }
354 
WebRtc_FreeBinaryDelayEstimator(BinaryDelayEstimator * self)355 void WebRtc_FreeBinaryDelayEstimator(BinaryDelayEstimator* self) {
356 
357   if (self == NULL) {
358     return;
359   }
360 
361   free(self->mean_bit_counts);
362   self->mean_bit_counts = NULL;
363 
364   free(self->bit_counts);
365   self->bit_counts = NULL;
366 
367   free(self->binary_near_history);
368   self->binary_near_history = NULL;
369 
370   free(self->histogram);
371   self->histogram = NULL;
372 
373   // BinaryDelayEstimator does not have ownership of |farend|, hence we do not
374   // free the memory here. That should be handled separately by the user.
375   self->farend = NULL;
376 
377   free(self);
378 }
379 
WebRtc_CreateBinaryDelayEstimator(BinaryDelayEstimatorFarend * farend,int max_lookahead)380 BinaryDelayEstimator* WebRtc_CreateBinaryDelayEstimator(
381     BinaryDelayEstimatorFarend* farend, int max_lookahead) {
382   BinaryDelayEstimator* self = NULL;
383 
384   if ((farend != NULL) && (max_lookahead >= 0)) {
385     // Sanity conditions fulfilled.
386     self = malloc(sizeof(BinaryDelayEstimator));
387   }
388 
389   if (self != NULL) {
390     int malloc_fail = 0;
391 
392     self->farend = farend;
393     self->near_history_size = max_lookahead + 1;
394     self->robust_validation_enabled = 0;  // Disabled by default.
395     self->allowed_offset = 0;
396 
397     self->lookahead = max_lookahead;
398 
399     // Allocate memory for spectrum buffers.  The extra array element in
400     // |mean_bit_counts| and |histogram| is a dummy element only used while
401     // |last_delay| == -2, i.e., before we have a valid estimate.
402     self->mean_bit_counts =
403         malloc((farend->history_size + 1) * sizeof(int32_t));
404     malloc_fail |= (self->mean_bit_counts == NULL);
405 
406     self->bit_counts = malloc(farend->history_size * sizeof(int32_t));
407     malloc_fail |= (self->bit_counts == NULL);
408 
409     // Allocate memory for history buffers.
410     self->binary_near_history = malloc((max_lookahead + 1) * sizeof(uint32_t));
411     malloc_fail |= (self->binary_near_history == NULL);
412 
413     self->histogram = malloc((farend->history_size + 1) * sizeof(float));
414     malloc_fail |= (self->histogram == NULL);
415 
416     if (malloc_fail) {
417       WebRtc_FreeBinaryDelayEstimator(self);
418       self = NULL;
419     }
420   }
421 
422   return self;
423 }
424 
WebRtc_InitBinaryDelayEstimator(BinaryDelayEstimator * self)425 void WebRtc_InitBinaryDelayEstimator(BinaryDelayEstimator* self) {
426   int i = 0;
427   assert(self != NULL);
428 
429   memset(self->bit_counts, 0, sizeof(int32_t) * self->farend->history_size);
430   memset(self->binary_near_history, 0,
431          sizeof(uint32_t) * self->near_history_size);
432   for (i = 0; i <= self->farend->history_size; ++i) {
433     self->mean_bit_counts[i] = (20 << 9);  // 20 in Q9.
434     self->histogram[i] = 0.f;
435   }
436   self->minimum_probability = kMaxBitCountsQ9;  // 32 in Q9.
437   self->last_delay_probability = (int) kMaxBitCountsQ9;  // 32 in Q9.
438 
439   // Default return value if we're unable to estimate. -1 is used for errors.
440   self->last_delay = -2;
441 
442   self->last_candidate_delay = -2;
443   self->compare_delay = self->farend->history_size;
444   self->candidate_hits = 0;
445   self->last_delay_histogram = 0.f;
446 }
447 
WebRtc_SoftResetBinaryDelayEstimator(BinaryDelayEstimator * self,int delay_shift)448 int WebRtc_SoftResetBinaryDelayEstimator(BinaryDelayEstimator* self,
449                                          int delay_shift) {
450   int lookahead = 0;
451   assert(self != NULL);
452   lookahead = self->lookahead;
453   self->lookahead -= delay_shift;
454   if (self->lookahead < 0) {
455     self->lookahead = 0;
456   }
457   if (self->lookahead > self->near_history_size - 1) {
458     self->lookahead = self->near_history_size - 1;
459   }
460   return lookahead - self->lookahead;
461 }
462 
WebRtc_ProcessBinarySpectrum(BinaryDelayEstimator * self,uint32_t binary_near_spectrum)463 int WebRtc_ProcessBinarySpectrum(BinaryDelayEstimator* self,
464                                  uint32_t binary_near_spectrum) {
465   int i = 0;
466   int candidate_delay = -1;
467   int valid_candidate = 0;
468 
469   int32_t value_best_candidate = kMaxBitCountsQ9;
470   int32_t value_worst_candidate = 0;
471   int32_t valley_depth = 0;
472 
473   assert(self != NULL);
474   if (self->near_history_size > 1) {
475     // If we apply lookahead, shift near-end binary spectrum history. Insert
476     // current |binary_near_spectrum| and pull out the delayed one.
477     memmove(&(self->binary_near_history[1]), &(self->binary_near_history[0]),
478             (self->near_history_size - 1) * sizeof(uint32_t));
479     self->binary_near_history[0] = binary_near_spectrum;
480     binary_near_spectrum = self->binary_near_history[self->lookahead];
481   }
482 
483   // Compare with delayed spectra and store the |bit_counts| for each delay.
484   BitCountComparison(binary_near_spectrum, self->farend->binary_far_history,
485                      self->farend->history_size, self->bit_counts);
486 
487   // Update |mean_bit_counts|, which is the smoothed version of |bit_counts|.
488   for (i = 0; i < self->farend->history_size; i++) {
489     // |bit_counts| is constrained to [0, 32], meaning we can smooth with a
490     // factor up to 2^26. We use Q9.
491     int32_t bit_count = (self->bit_counts[i] << 9);  // Q9.
492 
493     // Update |mean_bit_counts| only when far-end signal has something to
494     // contribute. If |far_bit_counts| is zero the far-end signal is weak and
495     // we likely have a poor echo condition, hence don't update.
496     if (self->farend->far_bit_counts[i] > 0) {
497       // Make number of right shifts piecewise linear w.r.t. |far_bit_counts|.
498       int shifts = kShiftsAtZero;
499       shifts -= (kShiftsLinearSlope * self->farend->far_bit_counts[i]) >> 4;
500       WebRtc_MeanEstimatorFix(bit_count, shifts, &(self->mean_bit_counts[i]));
501     }
502   }
503 
504   // Find |candidate_delay|, |value_best_candidate| and |value_worst_candidate|
505   // of |mean_bit_counts|.
506   for (i = 0; i < self->farend->history_size; i++) {
507     if (self->mean_bit_counts[i] < value_best_candidate) {
508       value_best_candidate = self->mean_bit_counts[i];
509       candidate_delay = i;
510     }
511     if (self->mean_bit_counts[i] > value_worst_candidate) {
512       value_worst_candidate = self->mean_bit_counts[i];
513     }
514   }
515   valley_depth = value_worst_candidate - value_best_candidate;
516 
517   // The |value_best_candidate| is a good indicator on the probability of
518   // |candidate_delay| being an accurate delay (a small |value_best_candidate|
519   // means a good binary match). In the following sections we make a decision
520   // whether to update |last_delay| or not.
521   // 1) If the difference bit counts between the best and the worst delay
522   //    candidates is too small we consider the situation to be unreliable and
523   //    don't update |last_delay|.
524   // 2) If the situation is reliable we update |last_delay| if the value of the
525   //    best candidate delay has a value less than
526   //     i) an adaptive threshold |minimum_probability|, or
527   //    ii) this corresponding value |last_delay_probability|, but updated at
528   //        this time instant.
529 
530   // Update |minimum_probability|.
531   if ((self->minimum_probability > kProbabilityLowerLimit) &&
532       (valley_depth > kProbabilityMinSpread)) {
533     // The "hard" threshold can't be lower than 17 (in Q9).
534     // The valley in the curve also has to be distinct, i.e., the
535     // difference between |value_worst_candidate| and |value_best_candidate| has
536     // to be large enough.
537     int32_t threshold = value_best_candidate + kProbabilityOffset;
538     if (threshold < kProbabilityLowerLimit) {
539       threshold = kProbabilityLowerLimit;
540     }
541     if (self->minimum_probability > threshold) {
542       self->minimum_probability = threshold;
543     }
544   }
545   // Update |last_delay_probability|.
546   // We use a Markov type model, i.e., a slowly increasing level over time.
547   self->last_delay_probability++;
548   // Validate |candidate_delay|.  We have a reliable instantaneous delay
549   // estimate if
550   //  1) The valley is distinct enough (|valley_depth| > |kProbabilityOffset|)
551   // and
552   //  2) The depth of the valley is deep enough
553   //      (|value_best_candidate| < |minimum_probability|)
554   //     and deeper than the best estimate so far
555   //      (|value_best_candidate| < |last_delay_probability|)
556   valid_candidate = ((valley_depth > kProbabilityOffset) &&
557       ((value_best_candidate < self->minimum_probability) ||
558           (value_best_candidate < self->last_delay_probability)));
559 
560   if (self->robust_validation_enabled) {
561     int is_histogram_valid = 0;
562     UpdateRobustValidationStatistics(self, candidate_delay, valley_depth,
563                                      value_best_candidate);
564     is_histogram_valid = HistogramBasedValidation(self, candidate_delay);
565     valid_candidate = RobustValidation(self, candidate_delay, valid_candidate,
566                                        is_histogram_valid);
567 
568   }
569   if (valid_candidate) {
570     if (candidate_delay != self->last_delay) {
571       self->last_delay_histogram =
572           (self->histogram[candidate_delay] > kLastHistogramMax ?
573               kLastHistogramMax : self->histogram[candidate_delay]);
574       // Adjust the histogram if we made a change to |last_delay|, though it was
575       // not the most likely one according to the histogram.
576       if (self->histogram[candidate_delay] <
577           self->histogram[self->compare_delay]) {
578         self->histogram[self->compare_delay] = self->histogram[candidate_delay];
579       }
580     }
581     self->last_delay = candidate_delay;
582     if (value_best_candidate < self->last_delay_probability) {
583       self->last_delay_probability = value_best_candidate;
584     }
585     self->compare_delay = self->last_delay;
586   }
587 
588   return self->last_delay;
589 }
590 
WebRtc_binary_last_delay(BinaryDelayEstimator * self)591 int WebRtc_binary_last_delay(BinaryDelayEstimator* self) {
592   assert(self != NULL);
593   return self->last_delay;
594 }
595 
WebRtc_binary_last_delay_quality(BinaryDelayEstimator * self)596 float WebRtc_binary_last_delay_quality(BinaryDelayEstimator* self) {
597   float quality = 0;
598   assert(self != NULL);
599 
600   if (self->robust_validation_enabled) {
601     // Simply a linear function of the histogram height at delay estimate.
602     quality = self->histogram[self->compare_delay] / kHistogramMax;
603   } else {
604     // Note that |last_delay_probability| states how deep the minimum of the
605     // cost function is, so it is rather an error probability.
606     quality = (float) (kMaxBitCountsQ9 - self->last_delay_probability) /
607         kMaxBitCountsQ9;
608     if (quality < 0) {
609       quality = 0;
610     }
611   }
612   return quality;
613 }
614 
WebRtc_MeanEstimatorFix(int32_t new_value,int factor,int32_t * mean_value)615 void WebRtc_MeanEstimatorFix(int32_t new_value,
616                              int factor,
617                              int32_t* mean_value) {
618   int32_t diff = new_value - *mean_value;
619 
620   // mean_new = mean_value + ((new_value - mean_value) >> factor);
621   if (diff < 0) {
622     diff = -((-diff) >> factor);
623   } else {
624     diff = (diff >> factor);
625   }
626   *mean_value += diff;
627 }
628