2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
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.
12 * Contains the API functions for the AEC.
14 #include "webrtc/modules/audio_processing/aec/include/echo_cancellation.h"
17 #ifdef WEBRTC_AEC_DEBUG_DUMP
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"
30 // Measured delays [ms]
33 // MacBook Retina 10 100
36 // Win7 Desktop 70 80?
41 // Pixel (w/ preproc?) 240
42 // Pixel (w/o preproc?) 110 110
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)
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.
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.
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.
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
70 #if defined(WEBRTC_MAC)
71 static const int kDelayDiffOffsetSamples = -160;
73 // Not enabled for now.
74 static const int kDelayDiffOffsetSamples = 0;
78 #if defined(WEBRTC_MAC)
79 static const int kFixedDelayMs = 20;
81 static const int kFixedDelayMs = 50;
83 #if !defined(WEBRTC_UNTRUSTED_DELAY)
84 static const int kMinTrustedDelayMs = 20;
86 static const int kMaxTrustedDelayMs = 500;
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)
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;
98 #ifdef WEBRTC_AEC_DEBUG_DUMP
99 int webrtc_aec_instance_count = 0;
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,
108 const int16_t* near_high,
112 int16_t reported_delay_ms,
114 static void ProcessExtended(aecpc_t* self,
116 const int16_t* near_high,
120 int16_t reported_delay_ms,
123 int32_t WebRtcAec_Create(void** aecInst) {
125 if (aecInst == NULL) {
129 aecpc = malloc(sizeof(aecpc_t));
135 if (WebRtcAec_CreateAec(&aecpc->aec) == -1) {
136 WebRtcAec_Free(aecpc);
141 if (WebRtcAec_CreateResampler(&aecpc->resampler) == -1) {
142 WebRtcAec_Free(aecpc);
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).
150 WebRtc_CreateBuffer(PART_LEN2 + kResamplerBufferSize, sizeof(float));
151 if (!aecpc->far_pre_buf) {
152 WebRtcAec_Free(aecpc);
158 aecpc->lastError = 0;
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);
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++;
183 int32_t WebRtcAec_Free(void* aecInst) {
184 aecpc_t* aecpc = aecInst;
190 WebRtc_FreeBuffer(aecpc->far_pre_buf);
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);
199 WebRtcAec_FreeAec(aecpc->aec);
200 WebRtcAec_FreeResampler(aecpc->resampler);
206 int32_t WebRtcAec_Init(void* aecInst, int32_t sampFreq, int32_t scSampFreq) {
207 aecpc_t* aecpc = aecInst;
210 if (sampFreq != 8000 && sampFreq != 16000 && sampFreq != 32000) {
211 aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
214 aecpc->sampFreq = sampFreq;
216 if (scSampFreq < 1 || scSampFreq > 96000) {
217 aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
220 aecpc->scSampFreq = scSampFreq;
222 // Initialize echo canceller core
223 if (WebRtcAec_InitAec(aecpc->aec, aecpc->sampFreq) == -1) {
224 aecpc->lastError = AEC_UNSPECIFIED_ERROR;
228 if (WebRtcAec_InitResampler(aecpc->resampler, aecpc->scSampFreq) == -1) {
229 aecpc->lastError = AEC_UNSPECIFIED_ERROR;
233 if (WebRtc_InitBuffer(aecpc->far_pre_buf) == -1) {
234 aecpc->lastError = AEC_UNSPECIFIED_ERROR;
237 WebRtc_MoveReadPtr(aecpc->far_pre_buf, -PART_LEN); // Start overlap.
239 aecpc->initFlag = initCheck; // indicates that initialization has been done
241 if (aecpc->sampFreq == 32000) {
242 aecpc->splitSampFreq = 16000;
244 aecpc->splitSampFreq = sampFreq;
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;
254 aecpc->checkBuffSize = 1;
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;
266 aecpc->skewFrCtr = 0;
267 aecpc->resample = kAecFalse;
268 aecpc->highSkewCtr = 0;
271 aecpc->farend_started = 0;
274 aecConfig.nlpMode = kAecNlpModerate;
275 aecConfig.skewMode = kAecFalse;
276 aecConfig.metricsMode = kAecFalse;
277 aecConfig.delay_logging = kAecFalse;
279 if (WebRtcAec_set_config(aecpc, aecConfig) == -1) {
280 aecpc->lastError = AEC_UNSPECIFIED_ERROR;
284 #ifdef WEBRTC_AEC_DEBUG_DUMP
285 if (WebRtc_InitBuffer(aecpc->far_pre_buf_s16) == -1) {
286 aecpc->lastError = AEC_UNSPECIFIED_ERROR;
289 WebRtc_MoveReadPtr(aecpc->far_pre_buf_s16, -PART_LEN); // Start overlap.
295 // only buffer L band for farend
296 int32_t WebRtcAec_BufferFarend(void* aecInst,
297 const int16_t* farend,
298 int16_t nrOfSamples) {
299 aecpc_t* aecpc = aecInst;
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;
309 if (farend == NULL) {
310 aecpc->lastError = AEC_NULL_POINTER_ERROR;
314 if (aecpc->initFlag != initCheck) {
315 aecpc->lastError = AEC_UNINITIALIZED_ERROR;
319 // number of samples == 160 for SWB input
320 if (nrOfSamples != 80 && nrOfSamples != 160) {
321 aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
327 if (aecpc->skewMode == kAecTrue && aecpc->resample == kAecTrue) {
328 // Resample and get a new number of samples
329 WebRtcAec_ResampleLinear(aecpc->resampler,
335 farend_ptr = (const int16_t*)newFarend;
338 aecpc->farend_started = 1;
339 WebRtcAec_SetSystemDelay(aecpc->aec,
340 WebRtcAec_system_delay(aecpc->aec) + newNrOfSamples);
342 #ifdef WEBRTC_AEC_DEBUG_DUMP
344 aecpc->far_pre_buf_s16, farend_ptr, (size_t)newNrOfSamples);
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];
350 WebRtc_WriteBuffer(aecpc->far_pre_buf, farend_float, (size_t)newNrOfSamples);
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.
356 aecpc->far_pre_buf, (void**)&farend_float, tmp_farend, PART_LEN2);
358 WebRtcAec_BufferFarendPartition(aecpc->aec, farend_float);
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
364 aecpc->far_pre_buf_s16, (void**)&farend_ptr, newFarend, PART_LEN2);
366 WebRtcAec_far_time_buf(aecpc->aec), &farend_ptr[PART_LEN], 1);
367 WebRtc_MoveReadPtr(aecpc->far_pre_buf_s16, -PART_LEN);
374 int32_t WebRtcAec_Process(void* aecInst,
375 const int16_t* nearend,
376 const int16_t* nearendH,
380 int16_t msInSndCardBuf,
382 aecpc_t* aecpc = aecInst;
384 if (nearend == NULL) {
385 aecpc->lastError = AEC_NULL_POINTER_ERROR;
390 aecpc->lastError = AEC_NULL_POINTER_ERROR;
394 if (aecpc->initFlag != initCheck) {
395 aecpc->lastError = AEC_UNINITIALIZED_ERROR;
399 // number of samples == 160 for SWB input
400 if (nrOfSamples != 80 && nrOfSamples != 160) {
401 aecpc->lastError = AEC_BAD_PARAMETER_ERROR;
405 // Check for valid pointers based on sampling rate
406 if (aecpc->sampFreq == 32000 && nearendH == NULL) {
407 aecpc->lastError = AEC_NULL_POINTER_ERROR;
411 if (msInSndCardBuf < 0) {
413 aecpc->lastError = AEC_BAD_PARAMETER_WARNING;
415 } else if (msInSndCardBuf > kMaxTrustedDelayMs) {
416 // The clamping is now done in ProcessExtended/Normal().
417 aecpc->lastError = AEC_BAD_PARAMETER_WARNING;
421 // This returns the value of aec->extended_filter_enabled.
422 if (WebRtcAec_delay_correction_enabled(aecpc->aec)) {
424 aecpc, nearend, nearendH, out, outH, nrOfSamples, msInSndCardBuf, skew);
426 if (ProcessNormal(aecpc,
438 #ifdef WEBRTC_AEC_DEBUG_DUMP
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);
444 &aecpc->knownDelay, sizeof(aecpc->knownDelay), 1, aecpc->delayFile);
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;
458 if (config.skewMode != kAecFalse && config.skewMode != kAecTrue) {
459 self->lastError = AEC_BAD_PARAMETER_ERROR;
462 self->skewMode = config.skewMode;
464 if (config.nlpMode != kAecNlpConservative &&
465 config.nlpMode != kAecNlpModerate &&
466 config.nlpMode != kAecNlpAggressive) {
467 self->lastError = AEC_BAD_PARAMETER_ERROR;
471 if (config.metricsMode != kAecFalse && config.metricsMode != kAecTrue) {
472 self->lastError = AEC_BAD_PARAMETER_ERROR;
476 if (config.delay_logging != kAecFalse && config.delay_logging != kAecTrue) {
477 self->lastError = AEC_BAD_PARAMETER_ERROR;
481 WebRtcAec_SetConfigCore(
482 self->aec, config.nlpMode, config.metricsMode, config.delay_logging);
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;
492 if (self->initFlag != initCheck) {
493 self->lastError = AEC_UNINITIALIZED_ERROR;
497 *status = WebRtcAec_echo_state(self->aec);
502 int WebRtcAec_GetMetrics(void* handle, AecMetrics* metrics) {
503 const float kUpWeight = 0.7f;
506 aecpc_t* self = (aecpc_t*)handle;
511 if (handle == NULL) {
514 if (metrics == NULL) {
515 self->lastError = AEC_NULL_POINTER_ERROR;
518 if (self->initFlag != initCheck) {
519 self->lastError = AEC_UNINITIALIZED_ERROR;
523 WebRtcAec_GetEchoStats(self->aec, &erl, &erle, &a_nlp);
526 metrics->erl.instant = (int)erl.instant;
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;
533 metrics->erl.average = kOffsetLevel;
536 metrics->erl.max = (int)erl.max;
538 if (erl.min < (kOffsetLevel * (-1))) {
539 metrics->erl.min = (int)erl.min;
541 metrics->erl.min = kOffsetLevel;
545 metrics->erle.instant = (int)erle.instant;
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;
552 metrics->erle.average = kOffsetLevel;
555 metrics->erle.max = (int)erle.max;
557 if (erle.min < (kOffsetLevel * (-1))) {
558 metrics->erle.min = (int)erle.min;
560 metrics->erle.min = kOffsetLevel;
564 if ((metrics->erl.average > kOffsetLevel) &&
565 (metrics->erle.average > kOffsetLevel)) {
566 stmp = metrics->erl.average + metrics->erle.average;
570 metrics->rerl.average = stmp;
572 // No other statistics needed, but returned for completeness.
573 metrics->rerl.instant = stmp;
574 metrics->rerl.max = stmp;
575 metrics->rerl.min = stmp;
578 metrics->aNlp.instant = (int)a_nlp.instant;
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;
585 metrics->aNlp.average = kOffsetLevel;
588 metrics->aNlp.max = (int)a_nlp.max;
590 if (a_nlp.min < (kOffsetLevel * (-1))) {
591 metrics->aNlp.min = (int)a_nlp.min;
593 metrics->aNlp.min = kOffsetLevel;
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;
606 self->lastError = AEC_NULL_POINTER_ERROR;
609 if (self->initFlag != initCheck) {
610 self->lastError = AEC_UNINITIALIZED_ERROR;
613 if (WebRtcAec_GetDelayMetricsCore(self->aec, median, std) == -1) {
615 self->lastError = AEC_UNSUPPORTED_FUNCTION_ERROR;
622 int32_t WebRtcAec_get_error_code(void* aecInst) {
623 aecpc_t* aecpc = aecInst;
624 return aecpc->lastError;
627 AecCore* WebRtcAec_aec_core(void* handle) {
631 return ((aecpc_t*)handle)->aec;
634 static int ProcessNormal(aecpc_t* aecpc,
635 const int16_t* nearend,
636 const int16_t* nearendH,
640 int16_t msInSndCardBuf,
646 // Limit resampling to doubling/halving of signal
647 const float minSkewEst = -0.5f;
648 const float maxSkewEst = 1.0f;
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;
656 if (aecpc->skewMode == kAecTrue) {
657 if (aecpc->skewFrCtr < 25) {
660 retVal = WebRtcAec_GetSkew(aecpc->resampler, skew, &aecpc->skew);
663 aecpc->lastError = AEC_BAD_PARAMETER_WARNING;
666 aecpc->skew /= aecpc->sampFactor * nrOfSamples;
668 if (aecpc->skew < 1.0e-3 && aecpc->skew > -1.0e-3) {
669 aecpc->resample = kAecFalse;
671 aecpc->resample = kAecTrue;
674 if (aecpc->skew < minSkewEst) {
675 aecpc->skew = minSkewEst;
676 } else if (aecpc->skew > maxSkewEst) {
677 aecpc->skew = maxSkewEst;
680 #ifdef WEBRTC_AEC_DEBUG_DUMP
681 (void)fwrite(&aecpc->skew, sizeof(aecpc->skew), 1, aecpc->skewFile);
686 nFrames = nrOfSamples / FRAME_LEN;
687 nBlocks10ms = nFrames / aecpc->rate_factor;
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(short) * nrOfSamples);
694 if (nearendH != outH) {
695 memcpy(outH, nearendH, sizeof(short) * nrOfSamples);
698 // The AEC is in the start up mode
699 // AEC is disabled until the system delay is OK
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
709 if (aecpc->counter == 0) {
710 aecpc->firstVal = aecpc->msInSndCardBuf;
714 if (abs(aecpc->firstVal - aecpc->msInSndCardBuf) <
715 WEBRTC_SPL_MAX(0.2 * aecpc->msInSndCardBuf, sampMsNb)) {
716 aecpc->sum += aecpc->msInSndCardBuf;
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),
730 // Buffer size has now been determined.
731 aecpc->checkBuffSize = 0;
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,
740 aecpc->checkBuffSize = 0;
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) {
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
761 WebRtcAec_MoveFarReadPtr(aecpc->aec, overhead_elements);
764 aecpc->startup_phase = 0;
769 if (WebRtcAec_reported_delay_enabled(aecpc->aec)) {
770 EstBufDelayNormal(aecpc);
773 // Note that 1 frame is supported for NB and 2 frames for WB.
774 for (i = 0; i < nFrames; i++) {
776 WebRtcAec_ProcessFrame(aecpc->aec,
777 &nearend[FRAME_LEN * i],
778 &nearendH[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|.
791 static void ProcessExtended(aecpc_t* self,
793 const int16_t* near_high,
797 int16_t reported_delay_ms,
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;
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
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
817 reported_delay_ms = reported_delay_ms >= kMaxTrustedDelayMs
821 self->msInSndCardBuf = reported_delay_ms;
823 if (!self->farend_started) {
824 // Only needed if they don't already point to the same place.
826 memcpy(out, near, sizeof(short) * num_samples);
828 if (near_high != out_high) {
829 memcpy(out_high, near_high, sizeof(short) * num_samples);
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
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) /
843 WebRtcAec_MoveFarReadPtr(self->aec, overhead_elements);
844 self->startup_phase = 0;
847 if (WebRtcAec_reported_delay_enabled(self->aec)) {
848 EstBufDelayExtended(self);
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);
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,
864 &out_high[FRAME_LEN * i]);
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;
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
880 // 1) Compensating for the frame(s) that will be read/processed.
881 current_delay += FRAME_LEN * aecpc->rate_factor;
883 // 2) Account for resampling frame delay.
884 if (aecpc->skewMode == kAecTrue && aecpc->resample == kAecTrue) {
885 current_delay -= kResamplingDelay;
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;
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;
897 WEBRTC_SPL_MAX(0, (short)(0.8 * aecpc->filtDelay + 0.2 * current_delay));
899 delay_difference = aecpc->filtDelay - aecpc->knownDelay;
900 if (delay_difference > 224) {
901 if (aecpc->lastDelayDiff < 96) {
902 aecpc->timeForDelayChange = 0;
904 aecpc->timeForDelayChange++;
906 } else if (delay_difference < 96 && aecpc->knownDelay > 0) {
907 if (aecpc->lastDelayDiff > 224) {
908 aecpc->timeForDelayChange = 0;
910 aecpc->timeForDelayChange++;
913 aecpc->timeForDelayChange = 0;
915 aecpc->lastDelayDiff = delay_difference;
917 if (aecpc->timeForDelayChange > 25) {
918 aecpc->knownDelay = WEBRTC_SPL_MAX((int)aecpc->filtDelay - 160, 0);
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;
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
933 // 1) Compensating for the frame(s) that will be read/processed.
934 current_delay += FRAME_LEN * self->rate_factor;
936 // 2) Account for resampling frame delay.
937 if (self->skewMode == kAecTrue && self->resample == kAecTrue) {
938 current_delay -= kResamplingDelay;
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;
946 if (self->filtDelay == -1) {
947 self->filtDelay = WEBRTC_SPL_MAX(0, 0.5 * current_delay);
949 self->filtDelay = WEBRTC_SPL_MAX(
950 0, (short)(0.95 * self->filtDelay + 0.05 * current_delay));
953 delay_difference = self->filtDelay - self->knownDelay;
954 if (delay_difference > 384) {
955 if (self->lastDelayDiff < 128) {
956 self->timeForDelayChange = 0;
958 self->timeForDelayChange++;
960 } else if (delay_difference < 128 && self->knownDelay > 0) {
961 if (self->lastDelayDiff > 384) {
962 self->timeForDelayChange = 0;
964 self->timeForDelayChange++;
967 self->timeForDelayChange = 0;
969 self->lastDelayDiff = delay_difference;
971 if (self->timeForDelayChange > 25) {
972 self->knownDelay = WEBRTC_SPL_MAX((int)self->filtDelay - 256, 0);