blob: 92ad5cf0dd35b20f51b32cc72b30793e962d8c87 [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
peah8cee56f2017-08-24 22:36:53 -070054AecState::AecState(const AudioProcessing::Config::EchoCanceller3& config)
peah522d71b2017-02-23 05:16:26 -080055 : data_dumper_(
56 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
peah8cee56f2017-08-24 22:36:53 -070057 erle_estimator_(config.param.erle.min,
58 config.param.erle.max_l,
59 config.param.erle.max_h),
peah8cee56f2017-08-24 22:36:53 -070060 config_(config),
61 reverb_decay_(config_.param.ep_strength.default_len) {}
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) {
67 if (echo_path_variability.AudioPathChanged()) {
68 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;
peah86afe9d2017-04-06 15:45:32 -070073 previous_max_sample_ = 0.f;
peah6d822ad2017-04-10 13:52:14 -070074
75 if (echo_path_variability.delay_change) {
76 force_zero_gain_counter_ = 0;
peahe52a2032017-04-19 09:03:40 -070077 blocks_with_filter_adaptation_ = 0;
78 render_received_ = false;
peah6d822ad2017-04-10 13:52:14 -070079 force_zero_gain_ = true;
Per Åhgren1b4059e2017-10-15 20:19:21 +020080 capture_block_counter_ = 0;
peah103ac7e2017-04-12 05:40:55 -070081 }
82 if (echo_path_variability.gain_change) {
Per Åhgren1b4059e2017-10-15 20:19:21 +020083 capture_block_counter_ = kNumBlocksPerSecond;
peah6d822ad2017-04-10 13:52:14 -070084 }
peah86afe9d2017-04-06 15:45:32 -070085 }
86}
87
peah522d71b2017-02-23 05:16:26 -080088void AecState::Update(const std::vector<std::array<float, kFftLengthBy2Plus1>>&
peah86afe9d2017-04-06 15:45:32 -070089 adaptive_filter_frequency_response,
peah29103572017-07-11 02:54:02 -070090 const std::array<float, kAdaptiveFilterTimeDomainLength>&
91 adaptive_filter_impulse_response,
Per Åhgren1b4059e2017-10-15 20:19:21 +020092 bool converged_filter,
peah522d71b2017-02-23 05:16:26 -080093 const rtc::Optional<size_t>& external_delay_samples,
peah86afe9d2017-04-06 15:45:32 -070094 const RenderBuffer& render_buffer,
peah522d71b2017-02-23 05:16:26 -080095 const std::array<float, kFftLengthBy2Plus1>& E2_main,
peah522d71b2017-02-23 05:16:26 -080096 const std::array<float, kFftLengthBy2Plus1>& Y2,
97 rtc::ArrayView<const float> x,
peah29103572017-07-11 02:54:02 -070098 const std::array<float, kBlockSize>& s,
peah522d71b2017-02-23 05:16:26 -080099 bool echo_leakage_detected) {
peah86afe9d2017-04-06 15:45:32 -0700100 // Store input parameters.
101 echo_leakage_detected_ = echo_leakage_detected;
102
103 // Update counters.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200104 ++capture_block_counter_;
peah86afe9d2017-04-06 15:45:32 -0700105
peah6d822ad2017-04-10 13:52:14 -0700106 // Force zero echo suppression gain after an echo path change to allow at
107 // least some render data to be collected in order to avoid an initial echo
108 // burst.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200109 force_zero_gain_ = (++force_zero_gain_counter_) < kNumBlocksPerSecond / 5;
peah6d822ad2017-04-10 13:52:14 -0700110
peah86afe9d2017-04-06 15:45:32 -0700111 // Estimate delays.
Per Åhgren40659c32017-10-17 12:56:21 +0200112 filter_delay_ = rtc::Optional<size_t>(
113 EstimateFilterDelay(adaptive_filter_frequency_response));
peah522d71b2017-02-23 05:16:26 -0800114 external_delay_ =
115 external_delay_samples
116 ? rtc::Optional<size_t>(*external_delay_samples / kBlockSize)
117 : rtc::Optional<size_t>();
118
peah86afe9d2017-04-06 15:45:32 -0700119 // Update the ERL and ERLE measures.
Per Åhgren40659c32017-10-17 12:56:21 +0200120 if (converged_filter && capture_block_counter_ >= 2 * kNumBlocksPerSecond) {
peah86afe9d2017-04-06 15:45:32 -0700121 const auto& X2 = render_buffer.Spectrum(*filter_delay_);
peah522d71b2017-02-23 05:16:26 -0800122 erle_estimator_.Update(X2, Y2, E2_main);
123 erl_estimator_.Update(X2, Y2);
peah522d71b2017-02-23 05:16:26 -0800124 }
peah86afe9d2017-04-06 15:45:32 -0700125
Per Åhgren1b4059e2017-10-15 20:19:21 +0200126 // Update the echo audibility evaluator.
127 echo_audibility_.Update(x, s, converged_filter);
128
peah86afe9d2017-04-06 15:45:32 -0700129 // Detect and flag echo saturation.
peahe52a2032017-04-19 09:03:40 -0700130 // TODO(peah): Add the delay in this computation to ensure that the render and
131 // capture signals are properly aligned.
peah86afe9d2017-04-06 15:45:32 -0700132 RTC_DCHECK_LT(0, x.size());
133 const float max_sample = fabs(*std::max_element(
134 x.begin(), x.end(), [](float a, float b) { return a * a < b * b; }));
Per Åhgren1b4059e2017-10-15 20:19:21 +0200135
136 if (config_.param.ep_strength.echo_can_saturate) {
137 const bool saturated_echo =
138 (previous_max_sample_ > 200.f) && SaturatedCapture();
139
140 // Counts the blocks since saturation.
141 constexpr size_t kSaturationLeakageBlocks = 20;
142 blocks_since_last_saturation_ =
143 saturated_echo ? 0 : blocks_since_last_saturation_ + 1;
144
145 echo_saturation_ = blocks_since_last_saturation_ < kSaturationLeakageBlocks;
146 } else {
147 echo_saturation_ = false;
148 }
peah86afe9d2017-04-06 15:45:32 -0700149 previous_max_sample_ = max_sample;
150
peah86afe9d2017-04-06 15:45:32 -0700151 // Flag whether the linear filter estimate is usable.
152 usable_linear_estimate_ =
Per Åhgren1b4059e2017-10-15 20:19:21 +0200153 (!echo_saturation_) && (converged_filter || SufficientFilterUpdates()) &&
Per Åhgren40659c32017-10-17 12:56:21 +0200154 capture_block_counter_ >= 2 * kNumBlocksPerSecond && external_delay_;
peah86afe9d2017-04-06 15:45:32 -0700155
156 // After an amount of active render samples for which an echo should have been
157 // detected in the capture signal if the ERL was not infinite, flag that a
Per Åhgren1b4059e2017-10-15 20:19:21 +0200158 // transparent mode should be entered.
159 const float x_energy = std::inner_product(x.begin(), x.end(), x.begin(), 0.f);
160 const bool active_render_block =
161 x_energy > (config_.param.render_levels.active_render_limit *
162 config_.param.render_levels.active_render_limit) *
163 kFftLengthBy2;
164 if (active_render_block) {
165 render_received_ = true;
166 }
167 blocks_with_filter_adaptation_ +=
168 (active_render_block && (!SaturatedCapture()) ? 1 : 0);
169
170 transparent_mode_ = !converged_filter &&
peah5e6685f2017-07-11 04:19:58 -0700171 (!render_received_ || blocks_with_filter_adaptation_ >=
Per Åhgren1b4059e2017-10-15 20:19:21 +0200172 5 * kNumBlocksPerSecond);
peah29103572017-07-11 02:54:02 -0700173
174 // Update the room reverb estimate.
175 UpdateReverb(adaptive_filter_impulse_response);
176}
177
178void AecState::UpdateReverb(
179 const std::array<float, kAdaptiveFilterTimeDomainLength>&
180 impulse_response) {
181 if ((!(filter_delay_ && usable_linear_estimate_)) ||
182 (*filter_delay_ > kAdaptiveFilterLength - 4)) {
183 return;
184 }
185
186 // Form the data to match against by squaring the impulse response
187 // coefficients.
188 std::array<float, kAdaptiveFilterTimeDomainLength> matching_data;
189 std::transform(impulse_response.begin(), impulse_response.end(),
190 matching_data.begin(), [](float a) { return a * a; });
191
192 // Avoid matching against noise in the model by subtracting an estimate of the
193 // model noise power.
194 constexpr size_t kTailLength = 64;
195 constexpr size_t tail_index = kAdaptiveFilterTimeDomainLength - kTailLength;
196 const float tail_power = *std::max_element(matching_data.begin() + tail_index,
197 matching_data.end());
198 std::for_each(matching_data.begin(), matching_data.begin() + tail_index,
199 [tail_power](float& a) { a = std::max(0.f, a - tail_power); });
200
201 // Identify the peak index of the impulse response.
202 const size_t peak_index = *std::max_element(
203 matching_data.begin(), matching_data.begin() + tail_index);
204
205 if (peak_index + 128 < tail_index) {
206 size_t start_index = peak_index + 64;
207 // Compute the matching residual error for the current candidate to match.
208 float residual_sqr_sum = 0.f;
209 float d_k = reverb_decay_to_test_;
210 for (size_t k = start_index; k < tail_index; ++k) {
211 if (matching_data[start_index + 1] == 0.f) {
212 break;
213 }
214
215 float residual = matching_data[k] - matching_data[peak_index] * d_k;
216 residual_sqr_sum += residual * residual;
217 d_k *= reverb_decay_to_test_;
218 }
219
220 // If needed, update the best candidate for the reverb decay.
221 if (reverb_decay_candidate_residual_ < 0.f ||
222 residual_sqr_sum < reverb_decay_candidate_residual_) {
223 reverb_decay_candidate_residual_ = residual_sqr_sum;
224 reverb_decay_candidate_ = reverb_decay_to_test_;
225 }
226 }
227
228 // Compute the next reverb candidate to evaluate such that all candidates will
229 // be evaluated within one second.
230 reverb_decay_to_test_ += (0.9965f - 0.9f) / (5 * kNumBlocksPerSecond);
231
232 // If all reverb candidates have been evaluated, choose the best one as the
233 // reverb decay.
234 if (reverb_decay_to_test_ >= 0.9965f) {
235 if (reverb_decay_candidate_residual_ < 0.f) {
236 // Transform the decay to be in the unit of blocks.
237 reverb_decay_ = powf(reverb_decay_candidate_, kFftLengthBy2);
238
239 // Limit the estimated reverb_decay_ to the maximum one needed in practice
240 // to minimize the impact of incorrect estimates.
peah8cee56f2017-08-24 22:36:53 -0700241 reverb_decay_ =
242 std::min(config_.param.ep_strength.default_len, reverb_decay_);
peah29103572017-07-11 02:54:02 -0700243 }
244 reverb_decay_to_test_ = 0.9f;
245 reverb_decay_candidate_residual_ = -1.f;
246 }
247
248 // For noisy impulse responses, assume a fixed tail length.
249 if (tail_power > 0.0005f) {
peah8cee56f2017-08-24 22:36:53 -0700250 reverb_decay_ = config_.param.ep_strength.default_len;
peah29103572017-07-11 02:54:02 -0700251 }
252 data_dumper_->DumpRaw("aec3_reverb_decay", reverb_decay_);
253 data_dumper_->DumpRaw("aec3_tail_power", tail_power);
254}
255
256void AecState::EchoAudibility::Update(rtc::ArrayView<const float> x,
Per Åhgren1b4059e2017-10-15 20:19:21 +0200257 const std::array<float, kBlockSize>& s,
258 bool converged_filter) {
peah29103572017-07-11 02:54:02 -0700259 auto result_x = std::minmax_element(x.begin(), x.end());
260 auto result_s = std::minmax_element(s.begin(), s.end());
261 const float x_abs =
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200262 std::max(fabsf(*result_x.first), fabsf(*result_x.second));
peah29103572017-07-11 02:54:02 -0700263 const float s_abs =
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200264 std::max(fabsf(*result_s.first), fabsf(*result_s.second));
peah29103572017-07-11 02:54:02 -0700265
Per Åhgren1b4059e2017-10-15 20:19:21 +0200266 if (converged_filter) {
267 if (x_abs < 20.f) {
268 ++low_farend_counter_;
269 } else {
270 low_farend_counter_ = 0;
271 }
peah29103572017-07-11 02:54:02 -0700272 } else {
Per Åhgren1b4059e2017-10-15 20:19:21 +0200273 if (x_abs < 100.f) {
274 ++low_farend_counter_;
275 } else {
276 low_farend_counter_ = 0;
277 }
peah29103572017-07-11 02:54:02 -0700278 }
279
280 // The echo is deemed as not audible if the echo estimate is on the level of
281 // the quantization noise in the FFTs and the nearend level is sufficiently
282 // strong to mask that by ensuring that the playout and AGC gains do not boost
283 // any residual echo that is below the quantization noise level. Furthermore,
284 // cases where the render signal is very close to zero are also identified as
285 // not producing audible echo.
Per Åhgren1b4059e2017-10-15 20:19:21 +0200286 inaudible_echo_ = (max_nearend_ > 500 && s_abs < 30.f) ||
287 (!converged_filter && x_abs < 500);
peah29103572017-07-11 02:54:02 -0700288 inaudible_echo_ = inaudible_echo_ || low_farend_counter_ > 20;
289}
290
291void AecState::EchoAudibility::UpdateWithOutput(rtc::ArrayView<const float> e) {
292 const float e_max = *std::max_element(e.begin(), e.end());
293 const float e_min = *std::min_element(e.begin(), e.end());
Raphael Kubo da Costa07438142017-10-16 17:00:02 +0200294 const float e_abs = std::max(fabsf(e_max), fabsf(e_min));
peah29103572017-07-11 02:54:02 -0700295
296 if (max_nearend_ < e_abs) {
297 max_nearend_ = e_abs;
298 max_nearend_counter_ = 0;
299 } else {
300 if (++max_nearend_counter_ > 5 * kNumBlocksPerSecond) {
301 max_nearend_ *= 0.995f;
302 }
303 }
peah522d71b2017-02-23 05:16:26 -0800304}
305
306} // namespace webrtc