blob: a9d901d2c0a30b01141b2ea04e60a3871d058ce6 [file] [log] [blame]
peah522d71b2017-02-23 05:16:26 -08001/*
2 * Copyright (c) 2017 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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/aec3/aec_state.h"
peah522d71b2017-02-23 05:16:26 -080012
13#include <math.h>
Raphael Kubo da Costa07438142017-10-16 17:00:02 +020014
peah522d71b2017-02-23 05:16:26 -080015#include <numeric>
16#include <vector>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/array_view.h"
19#include "modules/audio_processing/logging/apm_data_dumper.h"
20#include "rtc_base/atomicops.h"
21#include "rtc_base/checks.h"
peah522d71b2017-02-23 05:16:26 -080022
23namespace webrtc {
24namespace {
25
peah86afe9d2017-04-06 15:45:32 -070026// Computes delay of the adaptive filter.
Per Åhgren40659c32017-10-17 12:56:21 +020027int EstimateFilterDelay(
peah522d71b2017-02-23 05:16:26 -080028 const std::vector<std::array<float, kFftLengthBy2Plus1>>&
peah86afe9d2017-04-06 15:45:32 -070029 adaptive_filter_frequency_response) {
30 const auto& H2 = adaptive_filter_frequency_response;
peah522d71b2017-02-23 05:16:26 -080031 constexpr size_t kUpperBin = kFftLengthBy2 - 5;
Per Åhgren40659c32017-10-17 12:56:21 +020032 RTC_DCHECK_GE(kAdaptiveFilterLength, H2.size());
33 std::array<int, kAdaptiveFilterLength> delays;
34 delays.fill(0);
peah522d71b2017-02-23 05:16:26 -080035 for (size_t k = 1; k < kUpperBin; ++k) {
peah86afe9d2017-04-06 15:45:32 -070036 // Find the maximum of H2[j].
Per Åhgren40659c32017-10-17 12:56:21 +020037 size_t peak = 0;
peah522d71b2017-02-23 05:16:26 -080038 for (size_t j = 0; j < H2.size(); ++j) {
39 if (H2[j][k] > H2[peak][k]) {
40 peak = j;
41 }
42 }
Per Åhgren40659c32017-10-17 12:56:21 +020043 ++delays[peak];
peah522d71b2017-02-23 05:16:26 -080044 }
peah522d71b2017-02-23 05:16:26 -080045
Per Åhgren40659c32017-10-17 12:56:21 +020046 return std::distance(delays.begin(),
47 std::max_element(delays.begin(), delays.end()));
peah522d71b2017-02-23 05:16:26 -080048}
49
peah522d71b2017-02-23 05:16:26 -080050} // namespace
51
52int AecState::instance_count_ = 0;
53
Gustaf Ullbergbd83b912017-10-18 12:32:42 +020054AecState::AecState(const EchoCanceller3Config& config)
peah522d71b2017-02-23 05:16:26 -080055 : data_dumper_(
56 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Gustaf Ullbergbd83b912017-10-18 12:32:42 +020057 erle_estimator_(config.erle.min, config.erle.max_l, config.erle.max_h),
peah8cee56f2017-08-24 22:36:53 -070058 config_(config),
Per Åhgren7ddd4632017-10-25 02:59:45 +020059 reverb_decay_(config_.ep_strength.default_len) {
60 max_render_.fill(0.f);
61}
peah522d71b2017-02-23 05:16:26 -080062
63AecState::~AecState() = default;
64
peah86afe9d2017-04-06 15:45:32 -070065void AecState::HandleEchoPathChange(
66 const EchoPathVariability& echo_path_variability) {
Per Åhgren8ba58612017-12-01 23:01:44 +010067 const auto full_reset = [&]() {
Per Åhgren63b494d2017-12-06 11:32:38 +010068 blocks_since_last_saturation_ = 0;
peah86afe9d2017-04-06 15:45:32 -070069 usable_linear_estimate_ = false;
70 echo_leakage_detected_ = false;
71 capture_signal_saturation_ = false;
72 echo_saturation_ = false;
Per Åhgren63b494d2017-12-06 11:32:38 +010073 previous_max_sample_ = 0.f;
Per Åhgren7ddd4632017-10-25 02:59:45 +020074 max_render_.fill(0.f);
Per Åhgren8ba58612017-12-01 23:01:44 +010075 force_zero_gain_counter_ = 0;
76 blocks_with_filter_adaptation_ = 0;
77 blocks_with_strong_render_ = 0;
78 initial_state_ = true;
79 capture_block_counter_ = 0;
80 linear_echo_estimate_ = false;
81 sufficient_filter_updates_ = false;
82 render_received_ = false;
83 force_zero_gain_ = true;
84 };
peah6d822ad2017-04-10 13:52:14 -070085
Per Åhgren8ba58612017-12-01 23:01:44 +010086 // TODO(peah): Refine the reset scheme according to the type of gain and
87 // delay adjustment.
88 if (echo_path_variability.gain_change) {
89 full_reset();
90 }
91
92 if (echo_path_variability.delay_change !=
93 EchoPathVariability::DelayAdjustment::kBufferReadjustment) {
94 full_reset();
95 } else if (echo_path_variability.delay_change !=
96 EchoPathVariability::DelayAdjustment::kBufferFlush) {
97 full_reset();
98
99 } else if (echo_path_variability.delay_change !=
100 EchoPathVariability::DelayAdjustment::kDelayReset) {
101 full_reset();
102 } else if (echo_path_variability.delay_change !=
103 EchoPathVariability::DelayAdjustment::kNewDetectedDelay) {
104 full_reset();
105 } else if (echo_path_variability.gain_change) {
106 capture_block_counter_ = kNumBlocksPerSecond;
peah86afe9d2017-04-06 15:45:32 -0700107 }
108}
109
peah522d71b2017-02-23 05:16:26 -0800110void AecState::Update(const std::vector<std::array<float, kFftLengthBy2Plus1>>&
peah86afe9d2017-04-06 15:45:32 -0700111 adaptive_filter_frequency_response,
peah29103572017-07-11 02:54:02 -0700112 const std::array<float, kAdaptiveFilterTimeDomainLength>&
113 adaptive_filter_impulse_response,
Per Åhgren1b4059e2017-10-15 20:19:21 +0200114 bool converged_filter,
peah522d71b2017-02-23 05:16:26 -0800115 const rtc::Optional<size_t>& external_delay_samples,
peah86afe9d2017-04-06 15:45:32 -0700116 const RenderBuffer& render_buffer,
peah522d71b2017-02-23 05:16:26 -0800117 const std::array<float, kFftLengthBy2Plus1>& E2_main,
peah522d71b2017-02-23 05:16:26 -0800118 const std::array<float, kFftLengthBy2Plus1>& Y2,
119 rtc::ArrayView<const float> x,
peah29103572017-07-11 02:54:02 -0700120 const std::array<float, kBlockSize>& s,
peah522d71b2017-02-23 05:16:26 -0800121 bool echo_leakage_detected) {
peah86afe9d2017-04-06 15:45:32 -0700122 // Store input parameters.
123 echo_leakage_detected_ = echo_leakage_detected;
124
125 // Update counters.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200126 ++capture_block_counter_;
peah86afe9d2017-04-06 15:45:32 -0700127
peah6d822ad2017-04-10 13:52:14 -0700128 // Force zero echo suppression gain after an echo path change to allow at
129 // least some render data to be collected in order to avoid an initial echo
130 // burst.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200131 force_zero_gain_ = (++force_zero_gain_counter_) < kNumBlocksPerSecond / 5;
peah6d822ad2017-04-10 13:52:14 -0700132
peah86afe9d2017-04-06 15:45:32 -0700133 // Estimate delays.
Oskar Sundbomaa8b67d2017-11-17 14:34:48 +0100134 filter_delay_ = EstimateFilterDelay(adaptive_filter_frequency_response);
peah522d71b2017-02-23 05:16:26 -0800135 external_delay_ =
136 external_delay_samples
137 ? rtc::Optional<size_t>(*external_delay_samples / kBlockSize)
Oskar Sundbomaa8b67d2017-11-17 14:34:48 +0100138 : rtc::nullopt;
peah522d71b2017-02-23 05:16:26 -0800139
peah86afe9d2017-04-06 15:45:32 -0700140 // Update the ERL and ERLE measures.
Per Åhgren40659c32017-10-17 12:56:21 +0200141 if (converged_filter && capture_block_counter_ >= 2 * kNumBlocksPerSecond) {
peah86afe9d2017-04-06 15:45:32 -0700142 const auto& X2 = render_buffer.Spectrum(*filter_delay_);
peah522d71b2017-02-23 05:16:26 -0800143 erle_estimator_.Update(X2, Y2, E2_main);
144 erl_estimator_.Update(X2, Y2);
peah522d71b2017-02-23 05:16:26 -0800145 }
peah86afe9d2017-04-06 15:45:32 -0700146
Per Åhgren1b4059e2017-10-15 20:19:21 +0200147 // Update the echo audibility evaluator.
148 echo_audibility_.Update(x, s, converged_filter);
149
Per Åhgren63b494d2017-12-06 11:32:38 +0100150 // Detect and flag echo saturation.
151 // TODO(peah): Add the delay in this computation to ensure that the render and
152 // capture signals are properly aligned.
153 RTC_DCHECK_LT(0, x.size());
154 const float max_sample = fabs(*std::max_element(
155 x.begin(), x.end(), [](float a, float b) { return a * a < b * b; }));
Per Åhgren1b4059e2017-10-15 20:19:21 +0200156
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200157 if (config_.ep_strength.echo_can_saturate) {
Per Åhgren63b494d2017-12-06 11:32:38 +0100158 const bool saturated_echo =
159 (previous_max_sample_ > 200.f) && SaturatedCapture();
Per Åhgren1b4059e2017-10-15 20:19:21 +0200160
Per Åhgren63b494d2017-12-06 11:32:38 +0100161 // Counts the blocks since saturation.
162 constexpr size_t kSaturationLeakageBlocks = 20;
Per Åhgren7ddd4632017-10-25 02:59:45 +0200163
164 // Set flag for potential presence of saturated echo
Per Åhgren1b4059e2017-10-15 20:19:21 +0200165 blocks_since_last_saturation_ =
166 saturated_echo ? 0 : blocks_since_last_saturation_ + 1;
167
Per Åhgren63b494d2017-12-06 11:32:38 +0100168 echo_saturation_ = blocks_since_last_saturation_ < kSaturationLeakageBlocks;
Per Åhgren1b4059e2017-10-15 20:19:21 +0200169 } else {
170 echo_saturation_ = false;
171 }
Per Åhgren63b494d2017-12-06 11:32:38 +0100172 previous_max_sample_ = max_sample;
peah86afe9d2017-04-06 15:45:32 -0700173
Per Åhgren63b494d2017-12-06 11:32:38 +0100174 // TODO(peah): Move?
175 sufficient_filter_updates_ =
176 blocks_with_filter_adaptation_ >= kEchoPathChangeConvergenceBlocks;
177 initial_state_ = capture_block_counter_ < 3 * kNumBlocksPerSecond;
178
179 // Flag whether the linear filter estimate is usable.
180 usable_linear_estimate_ =
181 (!echo_saturation_) && (converged_filter || SufficientFilterUpdates()) &&
182 capture_block_counter_ >= 2 * kNumBlocksPerSecond && external_delay_;
183
184 linear_echo_estimate_ = UsableLinearEstimate() && !TransparentMode();
185
186 // After an amount of active render samples for which an echo should have been
187 // detected in the capture signal if the ERL was not infinite, flag that a
188 // transparent mode should be entered.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200189 const float x_energy = std::inner_product(x.begin(), x.end(), x.begin(), 0.f);
190 const bool active_render_block =
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200191 x_energy > (config_.render_levels.active_render_limit *
192 config_.render_levels.active_render_limit) *
Per Åhgren1b4059e2017-10-15 20:19:21 +0200193 kFftLengthBy2;
Per Åhgren7ddd4632017-10-25 02:59:45 +0200194
Per Åhgren1b4059e2017-10-15 20:19:21 +0200195 if (active_render_block) {
196 render_received_ = true;
197 }
Per Åhgren7ddd4632017-10-25 02:59:45 +0200198
199 // Update counters.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200200 blocks_with_filter_adaptation_ +=
201 (active_render_block && (!SaturatedCapture()) ? 1 : 0);
202
Per Åhgren63b494d2017-12-06 11:32:38 +0100203 transparent_mode_ = !converged_filter &&
204 (!render_received_ || blocks_with_filter_adaptation_ >=
205 5 * kNumBlocksPerSecond);
peah29103572017-07-11 02:54:02 -0700206
207 // Update the room reverb estimate.
208 UpdateReverb(adaptive_filter_impulse_response);
209}
210
211void AecState::UpdateReverb(
212 const std::array<float, kAdaptiveFilterTimeDomainLength>&
213 impulse_response) {
214 if ((!(filter_delay_ && usable_linear_estimate_)) ||
215 (*filter_delay_ > kAdaptiveFilterLength - 4)) {
216 return;
217 }
218
219 // Form the data to match against by squaring the impulse response
220 // coefficients.
221 std::array<float, kAdaptiveFilterTimeDomainLength> matching_data;
222 std::transform(impulse_response.begin(), impulse_response.end(),
223 matching_data.begin(), [](float a) { return a * a; });
224
225 // Avoid matching against noise in the model by subtracting an estimate of the
226 // model noise power.
227 constexpr size_t kTailLength = 64;
228 constexpr size_t tail_index = kAdaptiveFilterTimeDomainLength - kTailLength;
229 const float tail_power = *std::max_element(matching_data.begin() + tail_index,
230 matching_data.end());
231 std::for_each(matching_data.begin(), matching_data.begin() + tail_index,
232 [tail_power](float& a) { a = std::max(0.f, a - tail_power); });
233
234 // Identify the peak index of the impulse response.
235 const size_t peak_index = *std::max_element(
236 matching_data.begin(), matching_data.begin() + tail_index);
237
238 if (peak_index + 128 < tail_index) {
239 size_t start_index = peak_index + 64;
240 // Compute the matching residual error for the current candidate to match.
241 float residual_sqr_sum = 0.f;
242 float d_k = reverb_decay_to_test_;
243 for (size_t k = start_index; k < tail_index; ++k) {
244 if (matching_data[start_index + 1] == 0.f) {
245 break;
246 }
247
248 float residual = matching_data[k] - matching_data[peak_index] * d_k;
249 residual_sqr_sum += residual * residual;
250 d_k *= reverb_decay_to_test_;
251 }
252
253 // If needed, update the best candidate for the reverb decay.
254 if (reverb_decay_candidate_residual_ < 0.f ||
255 residual_sqr_sum < reverb_decay_candidate_residual_) {
256 reverb_decay_candidate_residual_ = residual_sqr_sum;
257 reverb_decay_candidate_ = reverb_decay_to_test_;
258 }
259 }
260
261 // Compute the next reverb candidate to evaluate such that all candidates will
262 // be evaluated within one second.
263 reverb_decay_to_test_ += (0.9965f - 0.9f) / (5 * kNumBlocksPerSecond);
264
265 // If all reverb candidates have been evaluated, choose the best one as the
266 // reverb decay.
267 if (reverb_decay_to_test_ >= 0.9965f) {
268 if (reverb_decay_candidate_residual_ < 0.f) {
269 // Transform the decay to be in the unit of blocks.
270 reverb_decay_ = powf(reverb_decay_candidate_, kFftLengthBy2);
271
272 // Limit the estimated reverb_decay_ to the maximum one needed in practice
273 // to minimize the impact of incorrect estimates.
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200274 reverb_decay_ = std::min(config_.ep_strength.default_len, reverb_decay_);
peah29103572017-07-11 02:54:02 -0700275 }
276 reverb_decay_to_test_ = 0.9f;
277 reverb_decay_candidate_residual_ = -1.f;
278 }
279
280 // For noisy impulse responses, assume a fixed tail length.
281 if (tail_power > 0.0005f) {
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200282 reverb_decay_ = config_.ep_strength.default_len;
peah29103572017-07-11 02:54:02 -0700283 }
284 data_dumper_->DumpRaw("aec3_reverb_decay", reverb_decay_);
285 data_dumper_->DumpRaw("aec3_tail_power", tail_power);
286}
287
288void AecState::EchoAudibility::Update(rtc::ArrayView<const float> x,
Per Åhgren1b4059e2017-10-15 20:19:21 +0200289 const std::array<float, kBlockSize>& s,
290 bool converged_filter) {
peah29103572017-07-11 02:54:02 -0700291 auto result_x = std::minmax_element(x.begin(), x.end());
292 auto result_s = std::minmax_element(s.begin(), s.end());
293 const float x_abs =
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200294 std::max(fabsf(*result_x.first), fabsf(*result_x.second));
peah29103572017-07-11 02:54:02 -0700295 const float s_abs =
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200296 std::max(fabsf(*result_s.first), fabsf(*result_s.second));
peah29103572017-07-11 02:54:02 -0700297
Per Åhgren1b4059e2017-10-15 20:19:21 +0200298 if (converged_filter) {
299 if (x_abs < 20.f) {
300 ++low_farend_counter_;
301 } else {
302 low_farend_counter_ = 0;
303 }
peah29103572017-07-11 02:54:02 -0700304 } else {
Per Åhgren1b4059e2017-10-15 20:19:21 +0200305 if (x_abs < 100.f) {
306 ++low_farend_counter_;
307 } else {
308 low_farend_counter_ = 0;
309 }
peah29103572017-07-11 02:54:02 -0700310 }
311
312 // The echo is deemed as not audible if the echo estimate is on the level of
313 // the quantization noise in the FFTs and the nearend level is sufficiently
314 // strong to mask that by ensuring that the playout and AGC gains do not boost
315 // any residual echo that is below the quantization noise level. Furthermore,
316 // cases where the render signal is very close to zero are also identified as
317 // not producing audible echo.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200318 inaudible_echo_ = (max_nearend_ > 500 && s_abs < 30.f) ||
319 (!converged_filter && x_abs < 500);
peah29103572017-07-11 02:54:02 -0700320 inaudible_echo_ = inaudible_echo_ || low_farend_counter_ > 20;
321}
322
323void AecState::EchoAudibility::UpdateWithOutput(rtc::ArrayView<const float> e) {
324 const float e_max = *std::max_element(e.begin(), e.end());
325 const float e_min = *std::min_element(e.begin(), e.end());
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200326 const float e_abs = std::max(fabsf(e_max), fabsf(e_min));
peah29103572017-07-11 02:54:02 -0700327
328 if (max_nearend_ < e_abs) {
329 max_nearend_ = e_abs;
330 max_nearend_counter_ = 0;
331 } else {
332 if (++max_nearend_counter_ > 5 * kNumBlocksPerSecond) {
333 max_nearend_ *= 0.995f;
334 }
335 }
peah522d71b2017-02-23 05:16:26 -0800336}
337
338} // namespace webrtc