blob: 78329a713deeda0a59e2cd04c33b21cf0aa9efd9 [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 Åhgren09a718a2017-12-11 22:28:45 +010032 RTC_DCHECK_GE(kMaxAdaptiveFilterLength, H2.size());
33 std::array<int, kMaxAdaptiveFilterLength> delays;
Per Åhgren40659c32017-10-17 12:56:21 +020034 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 Åhgren09a718a2017-12-11 22:28:45 +010059 max_render_(config_.filter.length_blocks, 0.f),
60 reverb_decay_(config_.ep_strength.default_len) {}
peah522d71b2017-02-23 05:16:26 -080061
62AecState::~AecState() = default;
63
peah86afe9d2017-04-06 15:45:32 -070064void AecState::HandleEchoPathChange(
65 const EchoPathVariability& echo_path_variability) {
Per Åhgren8ba58612017-12-01 23:01:44 +010066 const auto full_reset = [&]() {
Per Åhgren63b494d2017-12-06 11:32:38 +010067 blocks_since_last_saturation_ = 0;
peah86afe9d2017-04-06 15:45:32 -070068 usable_linear_estimate_ = false;
69 echo_leakage_detected_ = false;
70 capture_signal_saturation_ = false;
71 echo_saturation_ = false;
Per Åhgren63b494d2017-12-06 11:32:38 +010072 previous_max_sample_ = 0.f;
Per Åhgren09a718a2017-12-11 22:28:45 +010073 std::fill(max_render_.begin(), max_render_.end(), 0.f);
Per Åhgren8ba58612017-12-01 23:01:44 +010074 force_zero_gain_counter_ = 0;
75 blocks_with_filter_adaptation_ = 0;
76 blocks_with_strong_render_ = 0;
77 initial_state_ = true;
78 capture_block_counter_ = 0;
79 linear_echo_estimate_ = false;
80 sufficient_filter_updates_ = false;
81 render_received_ = false;
82 force_zero_gain_ = true;
83 };
peah6d822ad2017-04-10 13:52:14 -070084
Per Åhgren8ba58612017-12-01 23:01:44 +010085 // TODO(peah): Refine the reset scheme according to the type of gain and
86 // delay adjustment.
87 if (echo_path_variability.gain_change) {
88 full_reset();
89 }
90
91 if (echo_path_variability.delay_change !=
92 EchoPathVariability::DelayAdjustment::kBufferReadjustment) {
93 full_reset();
94 } else if (echo_path_variability.delay_change !=
95 EchoPathVariability::DelayAdjustment::kBufferFlush) {
96 full_reset();
97
98 } else if (echo_path_variability.delay_change !=
99 EchoPathVariability::DelayAdjustment::kDelayReset) {
100 full_reset();
101 } else if (echo_path_variability.delay_change !=
102 EchoPathVariability::DelayAdjustment::kNewDetectedDelay) {
103 full_reset();
104 } else if (echo_path_variability.gain_change) {
105 capture_block_counter_ = kNumBlocksPerSecond;
peah86afe9d2017-04-06 15:45:32 -0700106 }
107}
108
Per Åhgren09a718a2017-12-11 22:28:45 +0100109void AecState::Update(
110 const std::vector<std::array<float, kFftLengthBy2Plus1>>&
111 adaptive_filter_frequency_response,
112 const std::vector<float>& adaptive_filter_impulse_response,
113 bool converged_filter,
114 const rtc::Optional<size_t>& external_delay_samples,
115 const RenderBuffer& render_buffer,
116 const std::array<float, kFftLengthBy2Plus1>& E2_main,
117 const std::array<float, kFftLengthBy2Plus1>& Y2,
118 rtc::ArrayView<const float> x,
119 const std::array<float, kBlockSize>& s,
120 bool echo_leakage_detected) {
peah86afe9d2017-04-06 15:45:32 -0700121 // Store input parameters.
122 echo_leakage_detected_ = echo_leakage_detected;
123
124 // Update counters.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200125 ++capture_block_counter_;
peah86afe9d2017-04-06 15:45:32 -0700126
peah6d822ad2017-04-10 13:52:14 -0700127 // Force zero echo suppression gain after an echo path change to allow at
128 // least some render data to be collected in order to avoid an initial echo
129 // burst.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200130 force_zero_gain_ = (++force_zero_gain_counter_) < kNumBlocksPerSecond / 5;
peah6d822ad2017-04-10 13:52:14 -0700131
peah86afe9d2017-04-06 15:45:32 -0700132 // Estimate delays.
Oskar Sundbomaa8b67d2017-11-17 14:34:48 +0100133 filter_delay_ = EstimateFilterDelay(adaptive_filter_frequency_response);
peah522d71b2017-02-23 05:16:26 -0800134 external_delay_ =
135 external_delay_samples
136 ? rtc::Optional<size_t>(*external_delay_samples / kBlockSize)
Oskar Sundbomaa8b67d2017-11-17 14:34:48 +0100137 : rtc::nullopt;
peah522d71b2017-02-23 05:16:26 -0800138
peah86afe9d2017-04-06 15:45:32 -0700139 // Update the ERL and ERLE measures.
Per Åhgren40659c32017-10-17 12:56:21 +0200140 if (converged_filter && capture_block_counter_ >= 2 * kNumBlocksPerSecond) {
peah86afe9d2017-04-06 15:45:32 -0700141 const auto& X2 = render_buffer.Spectrum(*filter_delay_);
peah522d71b2017-02-23 05:16:26 -0800142 erle_estimator_.Update(X2, Y2, E2_main);
143 erl_estimator_.Update(X2, Y2);
peah522d71b2017-02-23 05:16:26 -0800144 }
peah86afe9d2017-04-06 15:45:32 -0700145
Per Åhgren1b4059e2017-10-15 20:19:21 +0200146 // Update the echo audibility evaluator.
147 echo_audibility_.Update(x, s, converged_filter);
148
Per Åhgren63b494d2017-12-06 11:32:38 +0100149 // Detect and flag echo saturation.
150 // TODO(peah): Add the delay in this computation to ensure that the render and
151 // capture signals are properly aligned.
152 RTC_DCHECK_LT(0, x.size());
153 const float max_sample = fabs(*std::max_element(
154 x.begin(), x.end(), [](float a, float b) { return a * a < b * b; }));
Per Åhgren1b4059e2017-10-15 20:19:21 +0200155
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200156 if (config_.ep_strength.echo_can_saturate) {
Per Åhgren63b494d2017-12-06 11:32:38 +0100157 const bool saturated_echo =
158 (previous_max_sample_ > 200.f) && SaturatedCapture();
Per Åhgren1b4059e2017-10-15 20:19:21 +0200159
Per Åhgren63b494d2017-12-06 11:32:38 +0100160 // Counts the blocks since saturation.
161 constexpr size_t kSaturationLeakageBlocks = 20;
Per Åhgren7ddd4632017-10-25 02:59:45 +0200162
163 // Set flag for potential presence of saturated echo
Per Åhgren1b4059e2017-10-15 20:19:21 +0200164 blocks_since_last_saturation_ =
165 saturated_echo ? 0 : blocks_since_last_saturation_ + 1;
166
Per Åhgren63b494d2017-12-06 11:32:38 +0100167 echo_saturation_ = blocks_since_last_saturation_ < kSaturationLeakageBlocks;
Per Åhgren1b4059e2017-10-15 20:19:21 +0200168 } else {
169 echo_saturation_ = false;
170 }
Per Åhgren63b494d2017-12-06 11:32:38 +0100171 previous_max_sample_ = max_sample;
peah86afe9d2017-04-06 15:45:32 -0700172
Per Åhgren63b494d2017-12-06 11:32:38 +0100173 // TODO(peah): Move?
174 sufficient_filter_updates_ =
175 blocks_with_filter_adaptation_ >= kEchoPathChangeConvergenceBlocks;
176 initial_state_ = capture_block_counter_ < 3 * kNumBlocksPerSecond;
177
178 // Flag whether the linear filter estimate is usable.
179 usable_linear_estimate_ =
180 (!echo_saturation_) && (converged_filter || SufficientFilterUpdates()) &&
181 capture_block_counter_ >= 2 * kNumBlocksPerSecond && external_delay_;
182
183 linear_echo_estimate_ = UsableLinearEstimate() && !TransparentMode();
184
185 // After an amount of active render samples for which an echo should have been
186 // detected in the capture signal if the ERL was not infinite, flag that a
187 // transparent mode should be entered.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200188 const float x_energy = std::inner_product(x.begin(), x.end(), x.begin(), 0.f);
189 const bool active_render_block =
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200190 x_energy > (config_.render_levels.active_render_limit *
191 config_.render_levels.active_render_limit) *
Per Åhgren1b4059e2017-10-15 20:19:21 +0200192 kFftLengthBy2;
Per Åhgren7ddd4632017-10-25 02:59:45 +0200193
Per Åhgren1b4059e2017-10-15 20:19:21 +0200194 if (active_render_block) {
195 render_received_ = true;
196 }
Per Åhgren7ddd4632017-10-25 02:59:45 +0200197
198 // Update counters.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200199 blocks_with_filter_adaptation_ +=
200 (active_render_block && (!SaturatedCapture()) ? 1 : 0);
201
Per Åhgren63b494d2017-12-06 11:32:38 +0100202 transparent_mode_ = !converged_filter &&
203 (!render_received_ || blocks_with_filter_adaptation_ >=
204 5 * kNumBlocksPerSecond);
peah29103572017-07-11 02:54:02 -0700205
206 // Update the room reverb estimate.
207 UpdateReverb(adaptive_filter_impulse_response);
208}
209
Per Åhgren09a718a2017-12-11 22:28:45 +0100210void AecState::UpdateReverb(const std::vector<float>& impulse_response) {
peah29103572017-07-11 02:54:02 -0700211 if ((!(filter_delay_ && usable_linear_estimate_)) ||
Per Åhgren09a718a2017-12-11 22:28:45 +0100212 (*filter_delay_ > config_.filter.length_blocks - 4)) {
peah29103572017-07-11 02:54:02 -0700213 return;
214 }
215
216 // Form the data to match against by squaring the impulse response
217 // coefficients.
Per Åhgren09a718a2017-12-11 22:28:45 +0100218 std::array<float, GetTimeDomainLength(kMaxAdaptiveFilterLength)>
219 matching_data_data;
220 RTC_DCHECK_LE(GetTimeDomainLength(config_.filter.length_blocks),
221 matching_data_data.size());
222 rtc::ArrayView<float> matching_data(
223 matching_data_data.data(),
224 GetTimeDomainLength(config_.filter.length_blocks));
peah29103572017-07-11 02:54:02 -0700225 std::transform(impulse_response.begin(), impulse_response.end(),
226 matching_data.begin(), [](float a) { return a * a; });
227
228 // Avoid matching against noise in the model by subtracting an estimate of the
229 // model noise power.
230 constexpr size_t kTailLength = 64;
Per Åhgren09a718a2017-12-11 22:28:45 +0100231 const size_t tail_index =
232 GetTimeDomainLength(config_.filter.length_blocks) - kTailLength;
peah29103572017-07-11 02:54:02 -0700233 const float tail_power = *std::max_element(matching_data.begin() + tail_index,
234 matching_data.end());
235 std::for_each(matching_data.begin(), matching_data.begin() + tail_index,
236 [tail_power](float& a) { a = std::max(0.f, a - tail_power); });
237
238 // Identify the peak index of the impulse response.
239 const size_t peak_index = *std::max_element(
240 matching_data.begin(), matching_data.begin() + tail_index);
241
242 if (peak_index + 128 < tail_index) {
243 size_t start_index = peak_index + 64;
244 // Compute the matching residual error for the current candidate to match.
245 float residual_sqr_sum = 0.f;
246 float d_k = reverb_decay_to_test_;
247 for (size_t k = start_index; k < tail_index; ++k) {
248 if (matching_data[start_index + 1] == 0.f) {
249 break;
250 }
251
252 float residual = matching_data[k] - matching_data[peak_index] * d_k;
253 residual_sqr_sum += residual * residual;
254 d_k *= reverb_decay_to_test_;
255 }
256
257 // If needed, update the best candidate for the reverb decay.
258 if (reverb_decay_candidate_residual_ < 0.f ||
259 residual_sqr_sum < reverb_decay_candidate_residual_) {
260 reverb_decay_candidate_residual_ = residual_sqr_sum;
261 reverb_decay_candidate_ = reverb_decay_to_test_;
262 }
263 }
264
265 // Compute the next reverb candidate to evaluate such that all candidates will
266 // be evaluated within one second.
267 reverb_decay_to_test_ += (0.9965f - 0.9f) / (5 * kNumBlocksPerSecond);
268
269 // If all reverb candidates have been evaluated, choose the best one as the
270 // reverb decay.
271 if (reverb_decay_to_test_ >= 0.9965f) {
272 if (reverb_decay_candidate_residual_ < 0.f) {
273 // Transform the decay to be in the unit of blocks.
274 reverb_decay_ = powf(reverb_decay_candidate_, kFftLengthBy2);
275
276 // Limit the estimated reverb_decay_ to the maximum one needed in practice
277 // to minimize the impact of incorrect estimates.
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200278 reverb_decay_ = std::min(config_.ep_strength.default_len, reverb_decay_);
peah29103572017-07-11 02:54:02 -0700279 }
280 reverb_decay_to_test_ = 0.9f;
281 reverb_decay_candidate_residual_ = -1.f;
282 }
283
284 // For noisy impulse responses, assume a fixed tail length.
285 if (tail_power > 0.0005f) {
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200286 reverb_decay_ = config_.ep_strength.default_len;
peah29103572017-07-11 02:54:02 -0700287 }
288 data_dumper_->DumpRaw("aec3_reverb_decay", reverb_decay_);
289 data_dumper_->DumpRaw("aec3_tail_power", tail_power);
290}
291
292void AecState::EchoAudibility::Update(rtc::ArrayView<const float> x,
Per Åhgren1b4059e2017-10-15 20:19:21 +0200293 const std::array<float, kBlockSize>& s,
294 bool converged_filter) {
peah29103572017-07-11 02:54:02 -0700295 auto result_x = std::minmax_element(x.begin(), x.end());
296 auto result_s = std::minmax_element(s.begin(), s.end());
297 const float x_abs =
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200298 std::max(fabsf(*result_x.first), fabsf(*result_x.second));
peah29103572017-07-11 02:54:02 -0700299 const float s_abs =
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200300 std::max(fabsf(*result_s.first), fabsf(*result_s.second));
peah29103572017-07-11 02:54:02 -0700301
Per Åhgren1b4059e2017-10-15 20:19:21 +0200302 if (converged_filter) {
303 if (x_abs < 20.f) {
304 ++low_farend_counter_;
305 } else {
306 low_farend_counter_ = 0;
307 }
peah29103572017-07-11 02:54:02 -0700308 } else {
Per Åhgren1b4059e2017-10-15 20:19:21 +0200309 if (x_abs < 100.f) {
310 ++low_farend_counter_;
311 } else {
312 low_farend_counter_ = 0;
313 }
peah29103572017-07-11 02:54:02 -0700314 }
315
316 // The echo is deemed as not audible if the echo estimate is on the level of
317 // the quantization noise in the FFTs and the nearend level is sufficiently
318 // strong to mask that by ensuring that the playout and AGC gains do not boost
319 // any residual echo that is below the quantization noise level. Furthermore,
320 // cases where the render signal is very close to zero are also identified as
321 // not producing audible echo.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200322 inaudible_echo_ = (max_nearend_ > 500 && s_abs < 30.f) ||
323 (!converged_filter && x_abs < 500);
peah29103572017-07-11 02:54:02 -0700324 inaudible_echo_ = inaudible_echo_ || low_farend_counter_ > 20;
325}
326
327void AecState::EchoAudibility::UpdateWithOutput(rtc::ArrayView<const float> e) {
328 const float e_max = *std::max_element(e.begin(), e.end());
329 const float e_min = *std::min_element(e.begin(), e.end());
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200330 const float e_abs = std::max(fabsf(e_max), fabsf(e_min));
peah29103572017-07-11 02:54:02 -0700331
332 if (max_nearend_ < e_abs) {
333 max_nearend_ = e_abs;
334 max_nearend_counter_ = 0;
335 } else {
336 if (++max_nearend_counter_ > 5 * kNumBlocksPerSecond) {
337 max_nearend_ *= 0.995f;
338 }
339 }
peah522d71b2017-02-23 05:16:26 -0800340}
341
342} // namespace webrtc