• 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 /*
12  * Contains the API functions for the AEC.
13  */
14 #include "webrtc/modules/audio_processing/aec/include/echo_cancellation.h"
15 
16 #include <math.h>
17 #ifdef WEBRTC_AEC_DEBUG_DUMP
18 #include <stdio.h>
19 #endif
20 #include <stdlib.h>
21 #include <string.h>
22 
23 #include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
24 #include "webrtc/modules/audio_processing/aec/aec_core.h"
25 #include "webrtc/modules/audio_processing/aec/aec_resampler.h"
26 #include "webrtc/modules/audio_processing/aec/echo_cancellation_internal.h"
27 #include "webrtc/modules/audio_processing/utility/ring_buffer.h"
28 #include "webrtc/typedefs.h"
29 
30 // Measured delays [ms]
31 // Device                Chrome  GTP
32 // MacBook Air           10
33 // MacBook Retina        10      100
34 // MacPro                30?
35 //
36 // Win7 Desktop          70      80?
37 // Win7 T430s            110
38 // Win8 T420s            70
39 //
40 // Daisy                 50
41 // Pixel (w/ preproc?)           240
42 // Pixel (w/o preproc?)  110     110
43 
44 // The extended filter mode gives us the flexibility to ignore the system's
45 // reported delays. We do this for platforms which we believe provide results
46 // which are incompatible with the AEC's expectations. Based on measurements
47 // (some provided above) we set a conservative (i.e. lower than measured)
48 // fixed delay.
49 //
50 // WEBRTC_UNTRUSTED_DELAY will only have an impact when |extended_filter_mode|
51 // is enabled. See the note along with |DelayCorrection| in
52 // echo_cancellation_impl.h for more details on the mode.
53 //
54 // Justification:
55 // Chromium/Mac: Here, the true latency is so low (~10-20 ms), that it plays
56 // havoc with the AEC's buffering. To avoid this, we set a fixed delay of 20 ms
57 // and then compensate by rewinding by 10 ms (in wideband) through
58 // kDelayDiffOffsetSamples. This trick does not seem to work for larger rewind
59 // values, but fortunately this is sufficient.
60 //
61 // Chromium/Linux(ChromeOS): The values we get on this platform don't correspond
62 // well to reality. The variance doesn't match the AEC's buffer changes, and the
63 // bulk values tend to be too low. However, the range across different hardware
64 // appears to be too large to choose a single value.
65 //
66 // GTP/Linux(ChromeOS): TBD, but for the moment we will trust the values.
67 #if defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_MAC)
68 #define WEBRTC_UNTRUSTED_DELAY
69 
70 #if defined(WEBRTC_MAC)
71 static const int kDelayDiffOffsetSamples = -160;
72 #else
73 // Not enabled for now.
74 static const int kDelayDiffOffsetSamples = 0;
75 #endif
76 #endif
77 
78 #if defined(WEBRTC_MAC)
79 static const int kFixedDelayMs = 20;
80 #else
81 static const int kFixedDelayMs = 50;
82 #endif
83 #if !defined(WEBRTC_UNTRUSTED_DELAY)
84 static const int kMinTrustedDelayMs = 20;
85 #endif
86 static const int kMaxTrustedDelayMs = 500;
87 
88 // Maximum length of resampled signal. Must be an integer multiple of frames
89 // (ceil(1/(1 + MIN_SKEW)*2) + 1)*FRAME_LEN
90 // The factor of 2 handles wb, and the + 1 is as a safety margin
91 // TODO(bjornv): Replace with kResamplerBufferSize
92 #define MAX_RESAMP_LEN (5 * FRAME_LEN)
93 
94 static const int kMaxBufSizeStart = 62;  // In partitions
95 static const int sampMsNb = 8;           // samples per ms in nb
96 static const int initCheck = 42;
97 
98 #ifdef WEBRTC_AEC_DEBUG_DUMP
99 int webrtc_aec_instance_count = 0;
100 #endif
101 
102 // Estimates delay to set the position of the far-end buffer read pointer
103 // (controlled by knownDelay)
104 static void EstBufDelayNormal(aecpc_t* aecInst);
105 static void EstBufDelayExtended(aecpc_t* aecInst);
106 static int ProcessNormal(aecpc_t* self,
107                          const float* near,
108                          const float* near_high,
109                          float* out,
110                          float* out_high,
111                          int16_t num_samples,
112                          int16_t reported_delay_ms,
113                          int32_t skew);
114 static void ProcessExtended(aecpc_t* self,
115                             const float* near,
116                             const float* near_high,
117                             float* out,
118                             float* out_high,
119                             int16_t num_samples,
120                             int16_t reported_delay_ms,
121                             int32_t skew);
122 
WebRtcAec_Create(void ** aecInst)123 int32_t WebRtcAec_Create(void** aecInst) {
124   aecpc_t* aecpc;
125   if (aecInst == NULL) {
126     return -1;
127   }
128 
129   aecpc = malloc(sizeof(aecpc_t));
130   *aecInst = aecpc;
131   if (aecpc == NULL) {
132     return -1;
133   }
134 
135   if (WebRtcAec_CreateAec(&aecpc->aec) == -1) {
136     WebRtcAec_Free(aecpc);
137     aecpc = NULL;
138     return -1;
139   }
140 
141   if (WebRtcAec_CreateResampler(&aecpc->resampler) == -1) {
142     WebRtcAec_Free(aecpc);
143     aecpc = NULL;
144     return -1;
145   }
146   // Create far-end pre-buffer. The buffer size has to be large enough for
147   // largest possible drift compensation (kResamplerBufferSize) + "almost" an
148   // FFT buffer (PART_LEN2 - 1).
149   aecpc->far_pre_buf =
150       WebRtc_CreateBuffer(PART_LEN2 + kResamplerBufferSize, sizeof(float));
151   if (!aecpc->far_pre_buf) {
152     WebRtcAec_Free(aecpc);
153     aecpc = NULL;
154     return -1;
155   }
156 
157   aecpc->initFlag = 0;
158   aecpc->lastError = 0;
159 
160 #ifdef WEBRTC_AEC_DEBUG_DUMP
161   aecpc->far_pre_buf_s16 =
162       WebRtc_CreateBuffer(PART_LEN2 + kResamplerBufferSize, sizeof(int16_t));
163   if (!aecpc->far_pre_buf_s16) {
164     WebRtcAec_Free(aecpc);
165     aecpc = NULL;
166     return -1;
167   }
168   {
169     char filename[64];
170     sprintf(filename, "aec_buf%d.dat", webrtc_aec_instance_count);
171     aecpc->bufFile = fopen(filename, "wb");
172     sprintf(filename, "aec_skew%d.dat", webrtc_aec_instance_count);
173     aecpc->skewFile = fopen(filename, "wb");
174     sprintf(filename, "aec_delay%d.dat", webrtc_aec_instance_count);
175     aecpc->delayFile = fopen(filename, "wb");
176     webrtc_aec_instance_count++;
177   }
178 #endif
179 
180   return 0;
181 }
182 
WebRtcAec_Free(void * aecInst)183 int32_t WebRtcAec_Free(void* aecInst) {
184   aecpc_t* aecpc = aecInst;
185 
186   if (aecpc == NULL) {
187     return -1;
188   }
189 
190   WebRtc_FreeBuffer(aecpc->far_pre_buf);
191 
192 #ifdef WEBRTC_AEC_DEBUG_DUMP
193   WebRtc_FreeBuffer(aecpc->far_pre_buf_s16);
194   fclose(aecpc->bufFile);
195   fclose(aecpc->skewFile);
196   fclose(aecpc->delayFile);
197 #endif
198 
199   WebRtcAec_FreeAec(aecpc->aec);
200   WebRtcAec_FreeResampler(aecpc->resampler);
201   free(aecpc);
202 
203   return 0;
204 }
205 
WebRtcAec_Init(void * aecInst,int32_t sampFreq,int32_t scSampFreq)206 int32_t WebRtcAec_Init(void* aecInst, int32_t sampFreq, int32_t scSampFreq) {
207   aecpc_t* aecpc = aecInst;
208   AecConfig aecConfig;
209 
210   if (sampFreq != 8000 && sampFreq != 16000 && sampFreq != 32000) {
211     aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
212     return -1;
213   }
214   aecpc->sampFreq = sampFreq;
215 
216   if (scSampFreq < 1 || scSampFreq > 96000) {
217     aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
218     return -1;
219   }
220   aecpc->scSampFreq = scSampFreq;
221 
222   // Initialize echo canceller core
223   if (WebRtcAec_InitAec(aecpc->aec, aecpc->sampFreq) == -1) {
224     aecpc->lastError = AEC_UNSPECIFIED_ERROR;
225     return -1;
226   }
227 
228   if (WebRtcAec_InitResampler(aecpc->resampler, aecpc->scSampFreq) == -1) {
229     aecpc->lastError = AEC_UNSPECIFIED_ERROR;
230     return -1;
231   }
232 
233   if (WebRtc_InitBuffer(aecpc->far_pre_buf) == -1) {
234     aecpc->lastError = AEC_UNSPECIFIED_ERROR;
235     return -1;
236   }
237   WebRtc_MoveReadPtr(aecpc->far_pre_buf, -PART_LEN);  // Start overlap.
238 
239   aecpc->initFlag = initCheck;  // indicates that initialization has been done
240 
241   if (aecpc->sampFreq == 32000) {
242     aecpc->splitSampFreq = 16000;
243   } else {
244     aecpc->splitSampFreq = sampFreq;
245   }
246 
247   aecpc->delayCtr = 0;
248   aecpc->sampFactor = (aecpc->scSampFreq * 1.0f) / aecpc->splitSampFreq;
249   // Sampling frequency multiplier (SWB is processed as 160 frame size).
250   aecpc->rate_factor = aecpc->splitSampFreq / 8000;
251 
252   aecpc->sum = 0;
253   aecpc->counter = 0;
254   aecpc->checkBuffSize = 1;
255   aecpc->firstVal = 0;
256 
257   aecpc->startup_phase = WebRtcAec_reported_delay_enabled(aecpc->aec);
258   aecpc->bufSizeStart = 0;
259   aecpc->checkBufSizeCtr = 0;
260   aecpc->msInSndCardBuf = 0;
261   aecpc->filtDelay = -1;  // -1 indicates an initialized state.
262   aecpc->timeForDelayChange = 0;
263   aecpc->knownDelay = 0;
264   aecpc->lastDelayDiff = 0;
265 
266   aecpc->skewFrCtr = 0;
267   aecpc->resample = kAecFalse;
268   aecpc->highSkewCtr = 0;
269   aecpc->skew = 0;
270 
271   aecpc->farend_started = 0;
272 
273   // Default settings.
274   aecConfig.nlpMode = kAecNlpModerate;
275   aecConfig.skewMode = kAecFalse;
276   aecConfig.metricsMode = kAecFalse;
277   aecConfig.delay_logging = kAecFalse;
278 
279   if (WebRtcAec_set_config(aecpc, aecConfig) == -1) {
280     aecpc->lastError = AEC_UNSPECIFIED_ERROR;
281     return -1;
282   }
283 
284 #ifdef WEBRTC_AEC_DEBUG_DUMP
285   if (WebRtc_InitBuffer(aecpc->far_pre_buf_s16) == -1) {
286     aecpc->lastError = AEC_UNSPECIFIED_ERROR;
287     return -1;
288   }
289   WebRtc_MoveReadPtr(aecpc->far_pre_buf_s16, -PART_LEN);  // Start overlap.
290 #endif
291 
292   return 0;
293 }
294 
295 // only buffer L band for farend
WebRtcAec_BufferFarend(void * aecInst,const int16_t * farend,int16_t nrOfSamples)296 int32_t WebRtcAec_BufferFarend(void* aecInst,
297                                const int16_t* farend,
298                                int16_t nrOfSamples) {
299   aecpc_t* aecpc = aecInst;
300   int32_t retVal = 0;
301   int newNrOfSamples = (int)nrOfSamples;
302   short newFarend[MAX_RESAMP_LEN];
303   const int16_t* farend_ptr = farend;
304   float tmp_farend[MAX_RESAMP_LEN];
305   const float* farend_float = tmp_farend;
306   float skew;
307   int i = 0;
308 
309   if (farend == NULL) {
310     aecpc->lastError = AEC_NULL_POINTER_ERROR;
311     return -1;
312   }
313 
314   if (aecpc->initFlag != initCheck) {
315     aecpc->lastError = AEC_UNINITIALIZED_ERROR;
316     return -1;
317   }
318 
319   // number of samples == 160 for SWB input
320   if (nrOfSamples != 80 && nrOfSamples != 160) {
321     aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
322     return -1;
323   }
324 
325   skew = aecpc->skew;
326 
327   if (aecpc->skewMode == kAecTrue && aecpc->resample == kAecTrue) {
328     // Resample and get a new number of samples
329     WebRtcAec_ResampleLinear(aecpc->resampler,
330                              farend,
331                              nrOfSamples,
332                              skew,
333                              newFarend,
334                              &newNrOfSamples);
335     farend_ptr = (const int16_t*)newFarend;
336   }
337 
338   aecpc->farend_started = 1;
339   WebRtcAec_SetSystemDelay(aecpc->aec,
340                            WebRtcAec_system_delay(aecpc->aec) + newNrOfSamples);
341 
342 #ifdef WEBRTC_AEC_DEBUG_DUMP
343   WebRtc_WriteBuffer(
344       aecpc->far_pre_buf_s16, farend_ptr, (size_t)newNrOfSamples);
345 #endif
346   // Cast to float and write the time-domain data to |far_pre_buf|.
347   for (i = 0; i < newNrOfSamples; i++) {
348     tmp_farend[i] = (float)farend_ptr[i];
349   }
350   WebRtc_WriteBuffer(aecpc->far_pre_buf, farend_float, (size_t)newNrOfSamples);
351 
352   // Transform to frequency domain if we have enough data.
353   while (WebRtc_available_read(aecpc->far_pre_buf) >= PART_LEN2) {
354     // We have enough data to pass to the FFT, hence read PART_LEN2 samples.
355     WebRtc_ReadBuffer(
356         aecpc->far_pre_buf, (void**)&farend_float, tmp_farend, PART_LEN2);
357 
358     WebRtcAec_BufferFarendPartition(aecpc->aec, farend_float);
359 
360     // Rewind |far_pre_buf| PART_LEN samples for overlap before continuing.
361     WebRtc_MoveReadPtr(aecpc->far_pre_buf, -PART_LEN);
362 #ifdef WEBRTC_AEC_DEBUG_DUMP
363     WebRtc_ReadBuffer(
364         aecpc->far_pre_buf_s16, (void**)&farend_ptr, newFarend, PART_LEN2);
365     WebRtc_WriteBuffer(
366         WebRtcAec_far_time_buf(aecpc->aec), &farend_ptr[PART_LEN], 1);
367     WebRtc_MoveReadPtr(aecpc->far_pre_buf_s16, -PART_LEN);
368 #endif
369   }
370 
371   return retVal;
372 }
373 
WebRtcAec_Process(void * aecInst,const float * nearend,const float * nearendH,float * out,float * outH,int16_t nrOfSamples,int16_t msInSndCardBuf,int32_t skew)374 int32_t WebRtcAec_Process(void* aecInst,
375                           const float* nearend,
376                           const float* nearendH,
377                           float* out,
378                           float* outH,
379                           int16_t nrOfSamples,
380                           int16_t msInSndCardBuf,
381                           int32_t skew) {
382   aecpc_t* aecpc = aecInst;
383   int32_t retVal = 0;
384   if (nearend == NULL) {
385     aecpc->lastError = AEC_NULL_POINTER_ERROR;
386     return -1;
387   }
388 
389   if (out == NULL) {
390     aecpc->lastError = AEC_NULL_POINTER_ERROR;
391     return -1;
392   }
393 
394   if (aecpc->initFlag != initCheck) {
395     aecpc->lastError = AEC_UNINITIALIZED_ERROR;
396     return -1;
397   }
398 
399   // number of samples == 160 for SWB input
400   if (nrOfSamples != 80 && nrOfSamples != 160) {
401     aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
402     return -1;
403   }
404 
405   // Check for valid pointers based on sampling rate
406   if (aecpc->sampFreq == 32000 && nearendH == NULL) {
407     aecpc->lastError = AEC_NULL_POINTER_ERROR;
408     return -1;
409   }
410 
411   if (msInSndCardBuf < 0) {
412     msInSndCardBuf = 0;
413     aecpc->lastError = AEC_BAD_PARAMETER_WARNING;
414     retVal = -1;
415   } else if (msInSndCardBuf > kMaxTrustedDelayMs) {
416     // The clamping is now done in ProcessExtended/Normal().
417     aecpc->lastError = AEC_BAD_PARAMETER_WARNING;
418     retVal = -1;
419   }
420 
421   // This returns the value of aec->extended_filter_enabled.
422   if (WebRtcAec_delay_correction_enabled(aecpc->aec)) {
423     ProcessExtended(
424         aecpc, nearend, nearendH, out, outH, nrOfSamples, msInSndCardBuf, skew);
425   } else {
426     if (ProcessNormal(aecpc,
427                       nearend,
428                       nearendH,
429                       out,
430                       outH,
431                       nrOfSamples,
432                       msInSndCardBuf,
433                       skew) != 0) {
434       retVal = -1;
435     }
436   }
437 
438 #ifdef WEBRTC_AEC_DEBUG_DUMP
439   {
440     int16_t far_buf_size_ms = (int16_t)(WebRtcAec_system_delay(aecpc->aec) /
441                                         (sampMsNb * aecpc->rate_factor));
442     (void)fwrite(&far_buf_size_ms, 2, 1, aecpc->bufFile);
443     (void)fwrite(
444         &aecpc->knownDelay, sizeof(aecpc->knownDelay), 1, aecpc->delayFile);
445   }
446 #endif
447 
448   return retVal;
449 }
450 
WebRtcAec_set_config(void * handle,AecConfig config)451 int WebRtcAec_set_config(void* handle, AecConfig config) {
452   aecpc_t* self = (aecpc_t*)handle;
453   if (self->initFlag != initCheck) {
454     self->lastError = AEC_UNINITIALIZED_ERROR;
455     return -1;
456   }
457 
458   if (config.skewMode != kAecFalse && config.skewMode != kAecTrue) {
459     self->lastError = AEC_BAD_PARAMETER_ERROR;
460     return -1;
461   }
462   self->skewMode = config.skewMode;
463 
464   if (config.nlpMode != kAecNlpConservative &&
465       config.nlpMode != kAecNlpModerate &&
466       config.nlpMode != kAecNlpAggressive) {
467     self->lastError = AEC_BAD_PARAMETER_ERROR;
468     return -1;
469   }
470 
471   if (config.metricsMode != kAecFalse && config.metricsMode != kAecTrue) {
472     self->lastError = AEC_BAD_PARAMETER_ERROR;
473     return -1;
474   }
475 
476   if (config.delay_logging != kAecFalse && config.delay_logging != kAecTrue) {
477     self->lastError = AEC_BAD_PARAMETER_ERROR;
478     return -1;
479   }
480 
481   WebRtcAec_SetConfigCore(
482       self->aec, config.nlpMode, config.metricsMode, config.delay_logging);
483   return 0;
484 }
485 
WebRtcAec_get_echo_status(void * handle,int * status)486 int WebRtcAec_get_echo_status(void* handle, int* status) {
487   aecpc_t* self = (aecpc_t*)handle;
488   if (status == NULL) {
489     self->lastError = AEC_NULL_POINTER_ERROR;
490     return -1;
491   }
492   if (self->initFlag != initCheck) {
493     self->lastError = AEC_UNINITIALIZED_ERROR;
494     return -1;
495   }
496 
497   *status = WebRtcAec_echo_state(self->aec);
498 
499   return 0;
500 }
501 
WebRtcAec_GetMetrics(void * handle,AecMetrics * metrics)502 int WebRtcAec_GetMetrics(void* handle, AecMetrics* metrics) {
503   const float kUpWeight = 0.7f;
504   float dtmp;
505   int stmp;
506   aecpc_t* self = (aecpc_t*)handle;
507   Stats erl;
508   Stats erle;
509   Stats a_nlp;
510 
511   if (handle == NULL) {
512     return -1;
513   }
514   if (metrics == NULL) {
515     self->lastError = AEC_NULL_POINTER_ERROR;
516     return -1;
517   }
518   if (self->initFlag != initCheck) {
519     self->lastError = AEC_UNINITIALIZED_ERROR;
520     return -1;
521   }
522 
523   WebRtcAec_GetEchoStats(self->aec, &erl, &erle, &a_nlp);
524 
525   // ERL
526   metrics->erl.instant = (int)erl.instant;
527 
528   if ((erl.himean > kOffsetLevel) && (erl.average > kOffsetLevel)) {
529     // Use a mix between regular average and upper part average.
530     dtmp = kUpWeight * erl.himean + (1 - kUpWeight) * erl.average;
531     metrics->erl.average = (int)dtmp;
532   } else {
533     metrics->erl.average = kOffsetLevel;
534   }
535 
536   metrics->erl.max = (int)erl.max;
537 
538   if (erl.min < (kOffsetLevel * (-1))) {
539     metrics->erl.min = (int)erl.min;
540   } else {
541     metrics->erl.min = kOffsetLevel;
542   }
543 
544   // ERLE
545   metrics->erle.instant = (int)erle.instant;
546 
547   if ((erle.himean > kOffsetLevel) && (erle.average > kOffsetLevel)) {
548     // Use a mix between regular average and upper part average.
549     dtmp = kUpWeight * erle.himean + (1 - kUpWeight) * erle.average;
550     metrics->erle.average = (int)dtmp;
551   } else {
552     metrics->erle.average = kOffsetLevel;
553   }
554 
555   metrics->erle.max = (int)erle.max;
556 
557   if (erle.min < (kOffsetLevel * (-1))) {
558     metrics->erle.min = (int)erle.min;
559   } else {
560     metrics->erle.min = kOffsetLevel;
561   }
562 
563   // RERL
564   if ((metrics->erl.average > kOffsetLevel) &&
565       (metrics->erle.average > kOffsetLevel)) {
566     stmp = metrics->erl.average + metrics->erle.average;
567   } else {
568     stmp = kOffsetLevel;
569   }
570   metrics->rerl.average = stmp;
571 
572   // No other statistics needed, but returned for completeness.
573   metrics->rerl.instant = stmp;
574   metrics->rerl.max = stmp;
575   metrics->rerl.min = stmp;
576 
577   // A_NLP
578   metrics->aNlp.instant = (int)a_nlp.instant;
579 
580   if ((a_nlp.himean > kOffsetLevel) && (a_nlp.average > kOffsetLevel)) {
581     // Use a mix between regular average and upper part average.
582     dtmp = kUpWeight * a_nlp.himean + (1 - kUpWeight) * a_nlp.average;
583     metrics->aNlp.average = (int)dtmp;
584   } else {
585     metrics->aNlp.average = kOffsetLevel;
586   }
587 
588   metrics->aNlp.max = (int)a_nlp.max;
589 
590   if (a_nlp.min < (kOffsetLevel * (-1))) {
591     metrics->aNlp.min = (int)a_nlp.min;
592   } else {
593     metrics->aNlp.min = kOffsetLevel;
594   }
595 
596   return 0;
597 }
598 
WebRtcAec_GetDelayMetrics(void * handle,int * median,int * std)599 int WebRtcAec_GetDelayMetrics(void* handle, int* median, int* std) {
600   aecpc_t* self = handle;
601   if (median == NULL) {
602     self->lastError = AEC_NULL_POINTER_ERROR;
603     return -1;
604   }
605   if (std == NULL) {
606     self->lastError = AEC_NULL_POINTER_ERROR;
607     return -1;
608   }
609   if (self->initFlag != initCheck) {
610     self->lastError = AEC_UNINITIALIZED_ERROR;
611     return -1;
612   }
613   if (WebRtcAec_GetDelayMetricsCore(self->aec, median, std) == -1) {
614     // Logging disabled.
615     self->lastError = AEC_UNSUPPORTED_FUNCTION_ERROR;
616     return -1;
617   }
618 
619   return 0;
620 }
621 
WebRtcAec_get_error_code(void * aecInst)622 int32_t WebRtcAec_get_error_code(void* aecInst) {
623   aecpc_t* aecpc = aecInst;
624   return aecpc->lastError;
625 }
626 
WebRtcAec_aec_core(void * handle)627 AecCore* WebRtcAec_aec_core(void* handle) {
628   if (!handle) {
629     return NULL;
630   }
631   return ((aecpc_t*)handle)->aec;
632 }
633 
ProcessNormal(aecpc_t * aecpc,const float * nearend,const float * nearendH,float * out,float * outH,int16_t nrOfSamples,int16_t msInSndCardBuf,int32_t skew)634 static int ProcessNormal(aecpc_t* aecpc,
635                          const float* nearend,
636                          const float* nearendH,
637                          float* out,
638                          float* outH,
639                          int16_t nrOfSamples,
640                          int16_t msInSndCardBuf,
641                          int32_t skew) {
642   int retVal = 0;
643   short i;
644   short nBlocks10ms;
645   short nFrames;
646   // Limit resampling to doubling/halving of signal
647   const float minSkewEst = -0.5f;
648   const float maxSkewEst = 1.0f;
649 
650   msInSndCardBuf =
651       msInSndCardBuf > kMaxTrustedDelayMs ? kMaxTrustedDelayMs : msInSndCardBuf;
652   // TODO(andrew): we need to investigate if this +10 is really wanted.
653   msInSndCardBuf += 10;
654   aecpc->msInSndCardBuf = msInSndCardBuf;
655 
656   if (aecpc->skewMode == kAecTrue) {
657     if (aecpc->skewFrCtr < 25) {
658       aecpc->skewFrCtr++;
659     } else {
660       retVal = WebRtcAec_GetSkew(aecpc->resampler, skew, &aecpc->skew);
661       if (retVal == -1) {
662         aecpc->skew = 0;
663         aecpc->lastError = AEC_BAD_PARAMETER_WARNING;
664       }
665 
666       aecpc->skew /= aecpc->sampFactor * nrOfSamples;
667 
668       if (aecpc->skew < 1.0e-3 && aecpc->skew > -1.0e-3) {
669         aecpc->resample = kAecFalse;
670       } else {
671         aecpc->resample = kAecTrue;
672       }
673 
674       if (aecpc->skew < minSkewEst) {
675         aecpc->skew = minSkewEst;
676       } else if (aecpc->skew > maxSkewEst) {
677         aecpc->skew = maxSkewEst;
678       }
679 
680 #ifdef WEBRTC_AEC_DEBUG_DUMP
681       (void)fwrite(&aecpc->skew, sizeof(aecpc->skew), 1, aecpc->skewFile);
682 #endif
683     }
684   }
685 
686   nFrames = nrOfSamples / FRAME_LEN;
687   nBlocks10ms = nFrames / aecpc->rate_factor;
688 
689   if (aecpc->startup_phase) {
690     // Only needed if they don't already point to the same place.
691     if (nearend != out) {
692       memcpy(out, nearend, sizeof(*out) * nrOfSamples);
693     }
694     if (nearendH != outH) {
695       memcpy(outH, nearendH, sizeof(*outH) * nrOfSamples);
696     }
697 
698     // The AEC is in the start up mode
699     // AEC is disabled until the system delay is OK
700 
701     // Mechanism to ensure that the system delay is reasonably stable.
702     if (aecpc->checkBuffSize) {
703       aecpc->checkBufSizeCtr++;
704       // Before we fill up the far-end buffer we require the system delay
705       // to be stable (+/-8 ms) compared to the first value. This
706       // comparison is made during the following 6 consecutive 10 ms
707       // blocks. If it seems to be stable then we start to fill up the
708       // far-end buffer.
709       if (aecpc->counter == 0) {
710         aecpc->firstVal = aecpc->msInSndCardBuf;
711         aecpc->sum = 0;
712       }
713 
714       if (abs(aecpc->firstVal - aecpc->msInSndCardBuf) <
715           WEBRTC_SPL_MAX(0.2 * aecpc->msInSndCardBuf, sampMsNb)) {
716         aecpc->sum += aecpc->msInSndCardBuf;
717         aecpc->counter++;
718       } else {
719         aecpc->counter = 0;
720       }
721 
722       if (aecpc->counter * nBlocks10ms >= 6) {
723         // The far-end buffer size is determined in partitions of
724         // PART_LEN samples. Use 75% of the average value of the system
725         // delay as buffer size to start with.
726         aecpc->bufSizeStart =
727             WEBRTC_SPL_MIN((3 * aecpc->sum * aecpc->rate_factor * 8) /
728                                (4 * aecpc->counter * PART_LEN),
729                            kMaxBufSizeStart);
730         // Buffer size has now been determined.
731         aecpc->checkBuffSize = 0;
732       }
733 
734       if (aecpc->checkBufSizeCtr * nBlocks10ms > 50) {
735         // For really bad systems, don't disable the echo canceller for
736         // more than 0.5 sec.
737         aecpc->bufSizeStart = WEBRTC_SPL_MIN(
738             (aecpc->msInSndCardBuf * aecpc->rate_factor * 3) / 40,
739             kMaxBufSizeStart);
740         aecpc->checkBuffSize = 0;
741       }
742     }
743 
744     // If |checkBuffSize| changed in the if-statement above.
745     if (!aecpc->checkBuffSize) {
746       // The system delay is now reasonably stable (or has been unstable
747       // for too long). When the far-end buffer is filled with
748       // approximately the same amount of data as reported by the system
749       // we end the startup phase.
750       int overhead_elements =
751           WebRtcAec_system_delay(aecpc->aec) / PART_LEN - aecpc->bufSizeStart;
752       if (overhead_elements == 0) {
753         // Enable the AEC
754         aecpc->startup_phase = 0;
755       } else if (overhead_elements > 0) {
756         // TODO(bjornv): Do we need a check on how much we actually
757         // moved the read pointer? It should always be possible to move
758         // the pointer |overhead_elements| since we have only added data
759         // to the buffer and no delay compensation nor AEC processing
760         // has been done.
761         WebRtcAec_MoveFarReadPtr(aecpc->aec, overhead_elements);
762 
763         // Enable the AEC
764         aecpc->startup_phase = 0;
765       }
766     }
767   } else {
768     // AEC is enabled.
769     if (WebRtcAec_reported_delay_enabled(aecpc->aec)) {
770       EstBufDelayNormal(aecpc);
771     }
772 
773     // Note that 1 frame is supported for NB and 2 frames for WB.
774     for (i = 0; i < nFrames; i++) {
775       // Call the AEC.
776       WebRtcAec_ProcessFrame(aecpc->aec,
777                              &nearend[FRAME_LEN * i],
778                              &nearendH[FRAME_LEN * i],
779                              aecpc->knownDelay,
780                              &out[FRAME_LEN * i],
781                              &outH[FRAME_LEN * i]);
782       // TODO(bjornv): Re-structure such that we don't have to pass
783       // |aecpc->knownDelay| as input. Change name to something like
784       // |system_buffer_diff|.
785     }
786   }
787 
788   return retVal;
789 }
790 
ProcessExtended(aecpc_t * self,const float * near,const float * near_high,float * out,float * out_high,int16_t num_samples,int16_t reported_delay_ms,int32_t skew)791 static void ProcessExtended(aecpc_t* self,
792                             const float* near,
793                             const float* near_high,
794                             float* out,
795                             float* out_high,
796                             int16_t num_samples,
797                             int16_t reported_delay_ms,
798                             int32_t skew) {
799   int i;
800   const int num_frames = num_samples / FRAME_LEN;
801 #if defined(WEBRTC_UNTRUSTED_DELAY)
802   const int delay_diff_offset = kDelayDiffOffsetSamples;
803   reported_delay_ms = kFixedDelayMs;
804 #else
805   // This is the usual mode where we trust the reported system delay values.
806   const int delay_diff_offset = 0;
807   // Due to the longer filter, we no longer add 10 ms to the reported delay
808   // to reduce chance of non-causality. Instead we apply a minimum here to avoid
809   // issues with the read pointer jumping around needlessly.
810   reported_delay_ms = reported_delay_ms < kMinTrustedDelayMs
811                           ? kMinTrustedDelayMs
812                           : reported_delay_ms;
813   // If the reported delay appears to be bogus, we attempt to recover by using
814   // the measured fixed delay values. We use >= here because higher layers
815   // may already clamp to this maximum value, and we would otherwise not
816   // detect it here.
817   reported_delay_ms = reported_delay_ms >= kMaxTrustedDelayMs
818                           ? kFixedDelayMs
819                           : reported_delay_ms;
820 #endif
821   self->msInSndCardBuf = reported_delay_ms;
822 
823   if (!self->farend_started) {
824     // Only needed if they don't already point to the same place.
825     if (near != out) {
826       memcpy(out, near, sizeof(*out) * num_samples);
827     }
828     if (near_high != out_high) {
829       memcpy(out_high, near_high, sizeof(*out_high) * num_samples);
830     }
831     return;
832   }
833   if (self->startup_phase) {
834     // In the extended mode, there isn't a startup "phase", just a special
835     // action on the first frame. In the trusted delay case, we'll take the
836     // current reported delay, unless it's less then our conservative
837     // measurement.
838     int startup_size_ms =
839         reported_delay_ms < kFixedDelayMs ? kFixedDelayMs : reported_delay_ms;
840     int overhead_elements = (WebRtcAec_system_delay(self->aec) -
841                              startup_size_ms / 2 * self->rate_factor * 8) /
842                             PART_LEN;
843     WebRtcAec_MoveFarReadPtr(self->aec, overhead_elements);
844     self->startup_phase = 0;
845   }
846 
847   if (WebRtcAec_reported_delay_enabled(self->aec)) {
848     EstBufDelayExtended(self);
849   }
850 
851   {
852     // |delay_diff_offset| gives us the option to manually rewind the delay on
853     // very low delay platforms which can't be expressed purely through
854     // |reported_delay_ms|.
855     const int adjusted_known_delay =
856         WEBRTC_SPL_MAX(0, self->knownDelay + delay_diff_offset);
857 
858     for (i = 0; i < num_frames; ++i) {
859       WebRtcAec_ProcessFrame(self->aec,
860                              &near[FRAME_LEN * i],
861                              &near_high[FRAME_LEN * i],
862                              adjusted_known_delay,
863                              &out[FRAME_LEN * i],
864                              &out_high[FRAME_LEN * i]);
865     }
866   }
867 }
868 
EstBufDelayNormal(aecpc_t * aecpc)869 static void EstBufDelayNormal(aecpc_t* aecpc) {
870   int nSampSndCard = aecpc->msInSndCardBuf * sampMsNb * aecpc->rate_factor;
871   int current_delay = nSampSndCard - WebRtcAec_system_delay(aecpc->aec);
872   int delay_difference = 0;
873 
874   // Before we proceed with the delay estimate filtering we:
875   // 1) Compensate for the frame that will be read.
876   // 2) Compensate for drift resampling.
877   // 3) Compensate for non-causality if needed, since the estimated delay can't
878   //    be negative.
879 
880   // 1) Compensating for the frame(s) that will be read/processed.
881   current_delay += FRAME_LEN * aecpc->rate_factor;
882 
883   // 2) Account for resampling frame delay.
884   if (aecpc->skewMode == kAecTrue && aecpc->resample == kAecTrue) {
885     current_delay -= kResamplingDelay;
886   }
887 
888   // 3) Compensate for non-causality, if needed, by flushing one block.
889   if (current_delay < PART_LEN) {
890     current_delay += WebRtcAec_MoveFarReadPtr(aecpc->aec, 1) * PART_LEN;
891   }
892 
893   // We use -1 to signal an initialized state in the "extended" implementation;
894   // compensate for that.
895   aecpc->filtDelay = aecpc->filtDelay < 0 ? 0 : aecpc->filtDelay;
896   aecpc->filtDelay =
897       WEBRTC_SPL_MAX(0, (short)(0.8 * aecpc->filtDelay + 0.2 * current_delay));
898 
899   delay_difference = aecpc->filtDelay - aecpc->knownDelay;
900   if (delay_difference > 224) {
901     if (aecpc->lastDelayDiff < 96) {
902       aecpc->timeForDelayChange = 0;
903     } else {
904       aecpc->timeForDelayChange++;
905     }
906   } else if (delay_difference < 96 && aecpc->knownDelay > 0) {
907     if (aecpc->lastDelayDiff > 224) {
908       aecpc->timeForDelayChange = 0;
909     } else {
910       aecpc->timeForDelayChange++;
911     }
912   } else {
913     aecpc->timeForDelayChange = 0;
914   }
915   aecpc->lastDelayDiff = delay_difference;
916 
917   if (aecpc->timeForDelayChange > 25) {
918     aecpc->knownDelay = WEBRTC_SPL_MAX((int)aecpc->filtDelay - 160, 0);
919   }
920 }
921 
EstBufDelayExtended(aecpc_t * self)922 static void EstBufDelayExtended(aecpc_t* self) {
923   int reported_delay = self->msInSndCardBuf * sampMsNb * self->rate_factor;
924   int current_delay = reported_delay - WebRtcAec_system_delay(self->aec);
925   int delay_difference = 0;
926 
927   // Before we proceed with the delay estimate filtering we:
928   // 1) Compensate for the frame that will be read.
929   // 2) Compensate for drift resampling.
930   // 3) Compensate for non-causality if needed, since the estimated delay can't
931   //    be negative.
932 
933   // 1) Compensating for the frame(s) that will be read/processed.
934   current_delay += FRAME_LEN * self->rate_factor;
935 
936   // 2) Account for resampling frame delay.
937   if (self->skewMode == kAecTrue && self->resample == kAecTrue) {
938     current_delay -= kResamplingDelay;
939   }
940 
941   // 3) Compensate for non-causality, if needed, by flushing two blocks.
942   if (current_delay < PART_LEN) {
943     current_delay += WebRtcAec_MoveFarReadPtr(self->aec, 2) * PART_LEN;
944   }
945 
946   if (self->filtDelay == -1) {
947     self->filtDelay = WEBRTC_SPL_MAX(0, 0.5 * current_delay);
948   } else {
949     self->filtDelay = WEBRTC_SPL_MAX(
950         0, (short)(0.95 * self->filtDelay + 0.05 * current_delay));
951   }
952 
953   delay_difference = self->filtDelay - self->knownDelay;
954   if (delay_difference > 384) {
955     if (self->lastDelayDiff < 128) {
956       self->timeForDelayChange = 0;
957     } else {
958       self->timeForDelayChange++;
959     }
960   } else if (delay_difference < 128 && self->knownDelay > 0) {
961     if (self->lastDelayDiff > 384) {
962       self->timeForDelayChange = 0;
963     } else {
964       self->timeForDelayChange++;
965     }
966   } else {
967     self->timeForDelayChange = 0;
968   }
969   self->lastDelayDiff = delay_difference;
970 
971   if (self->timeForDelayChange > 25) {
972     self->knownDelay = WEBRTC_SPL_MAX((int)self->filtDelay - 256, 0);
973   }
974 }
975