blob: 613256673069a56ad976dd9abd3a55d0e4f98555 [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/suppression_gain.h"
peah522d71b2017-02-23 05:16:26 -080012
peah522d71b2017-02-23 05:16:26 -080013#include <math.h>
14#include <algorithm>
15#include <functional>
peah86afe9d2017-04-06 15:45:32 -070016#include <numeric>
peah522d71b2017-02-23 05:16:26 -080017
Gustaf Ullberg8406c432018-06-19 12:31:33 +020018#include "modules/audio_processing/aec3/moving_average.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "modules/audio_processing/aec3/vector_math.h"
Gustaf Ullberg216af842018-04-26 12:39:11 +020020#include "modules/audio_processing/logging/apm_data_dumper.h"
21#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/checks.h"
Gustaf Ullberg0e6375e2018-05-04 11:29:02 +020023#include "system_wrappers/include/field_trial.h"
peahcf02cf12017-04-05 14:18:07 -070024
peah522d71b2017-02-23 05:16:26 -080025namespace webrtc {
26namespace {
27
Gustaf Ullbergec642172018-07-03 13:48:32 +020028bool EnableNewSuppression() {
29 return !field_trial::IsEnabled("WebRTC-Aec3NewSuppressionKillSwitch");
30}
31
peah1d680892017-05-23 04:07:10 -070032// Adjust the gains according to the presence of known external filters.
33void AdjustForExternalFilters(std::array<float, kFftLengthBy2Plus1>* gain) {
peaha2376e72017-02-27 01:15:24 -080034 // Limit the low frequency gains to avoid the impact of the high-pass filter
35 // on the lower-frequency gain influencing the overall achieved gain.
peah1d680892017-05-23 04:07:10 -070036 (*gain)[0] = (*gain)[1] = std::min((*gain)[1], (*gain)[2]);
peaha2376e72017-02-27 01:15:24 -080037
38 // Limit the high frequency gains to avoid the impact of the anti-aliasing
39 // filter on the upper-frequency gains influencing the overall achieved
40 // gain. TODO(peah): Update this when new anti-aliasing filters are
41 // implemented.
peah86afe9d2017-04-06 15:45:32 -070042 constexpr size_t kAntiAliasingImpactLimit = (64 * 2000) / 8000;
peah1d680892017-05-23 04:07:10 -070043 const float min_upper_gain = (*gain)[kAntiAliasingImpactLimit];
44 std::for_each(
45 gain->begin() + kAntiAliasingImpactLimit, gain->end() - 1,
46 [min_upper_gain](float& a) { a = std::min(a, min_upper_gain); });
47 (*gain)[kFftLengthBy2] = (*gain)[kFftLengthBy2Minus1];
peaha2376e72017-02-27 01:15:24 -080048}
49
Per Åhgrenb02644f2018-04-17 11:52:17 +020050// Scales the echo according to assessed audibility at the other end.
51void WeightEchoForAudibility(const EchoCanceller3Config& config,
52 rtc::ArrayView<const float> echo,
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +020053 rtc::ArrayView<float> weighted_echo) {
Per Åhgrenb02644f2018-04-17 11:52:17 +020054 RTC_DCHECK_EQ(kFftLengthBy2Plus1, echo.size());
55 RTC_DCHECK_EQ(kFftLengthBy2Plus1, weighted_echo.size());
Per Åhgrenb02644f2018-04-17 11:52:17 +020056
57 auto weigh = [](float threshold, float normalizer, size_t begin, size_t end,
58 rtc::ArrayView<const float> echo,
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +020059 rtc::ArrayView<float> weighted_echo) {
Per Åhgrenb02644f2018-04-17 11:52:17 +020060 for (size_t k = begin; k < end; ++k) {
61 if (echo[k] < threshold) {
62 float tmp = (threshold - echo[k]) * normalizer;
63 weighted_echo[k] = echo[k] * std::max(0.f, 1.f - tmp * tmp);
64 } else {
65 weighted_echo[k] = echo[k];
66 }
Per Åhgrenb02644f2018-04-17 11:52:17 +020067 }
68 };
69
70 float threshold = config.echo_audibility.floor_power *
71 config.echo_audibility.audibility_threshold_lf;
72 float normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +020073 weigh(threshold, normalizer, 0, 3, echo, weighted_echo);
Per Åhgrenb02644f2018-04-17 11:52:17 +020074
75 threshold = config.echo_audibility.floor_power *
76 config.echo_audibility.audibility_threshold_mf;
77 normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +020078 weigh(threshold, normalizer, 3, 7, echo, weighted_echo);
Per Åhgrenb02644f2018-04-17 11:52:17 +020079
80 threshold = config.echo_audibility.floor_power *
81 config.echo_audibility.audibility_threshold_hf;
82 normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +020083 weigh(threshold, normalizer, 7, kFftLengthBy2Plus1, echo, weighted_echo);
Per Åhgrenb02644f2018-04-17 11:52:17 +020084}
85
peah1d680892017-05-23 04:07:10 -070086// Computes the gain to reduce the echo to a non audible level.
Gustaf Ullbergec642172018-07-03 13:48:32 +020087void GainToNoAudibleEchoFallback(
Gustaf Ullbergbd83b912017-10-18 12:32:42 +020088 const EchoCanceller3Config& config,
peah1d680892017-05-23 04:07:10 -070089 bool low_noise_render,
90 bool saturated_echo,
Per Åhgrenc65ce782017-10-09 13:01:39 +020091 bool linear_echo_estimate,
peah1d680892017-05-23 04:07:10 -070092 const std::array<float, kFftLengthBy2Plus1>& nearend,
Per Åhgrenb02644f2018-04-17 11:52:17 +020093 const std::array<float, kFftLengthBy2Plus1>& weighted_echo,
peah1d680892017-05-23 04:07:10 -070094 const std::array<float, kFftLengthBy2Plus1>& masker,
95 const std::array<float, kFftLengthBy2Plus1>& min_gain,
96 const std::array<float, kFftLengthBy2Plus1>& max_gain,
Per Åhgrenb02644f2018-04-17 11:52:17 +020097 const std::array<float, kFftLengthBy2Plus1>& one_by_weighted_echo,
peah1d680892017-05-23 04:07:10 -070098 std::array<float, kFftLengthBy2Plus1>* gain) {
Per Åhgrenc65ce782017-10-09 13:01:39 +020099 float nearend_masking_margin = 0.f;
Per Åhgren63b494d2017-12-06 11:32:38 +0100100 if (linear_echo_estimate) {
101 nearend_masking_margin =
102 low_noise_render
103 ? config.gain_mask.m9
104 : (saturated_echo ? config.gain_mask.m2 : config.gain_mask.m3);
Per Åhgrenc65ce782017-10-09 13:01:39 +0200105 } else {
Per Åhgren63b494d2017-12-06 11:32:38 +0100106 nearend_masking_margin = config.gain_mask.m7;
Per Åhgrenc65ce782017-10-09 13:01:39 +0200107 }
Per Åhgren7ddd4632017-10-25 02:59:45 +0200108
Per Åhgrend309b002017-10-09 23:50:44 +0200109 RTC_DCHECK_LE(0.f, nearend_masking_margin);
110 RTC_DCHECK_GT(1.f, nearend_masking_margin);
Per Åhgrend309b002017-10-09 23:50:44 +0200111
Per Åhgren63b494d2017-12-06 11:32:38 +0100112 const float masker_margin =
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200113 linear_echo_estimate ? config.gain_mask.m0 : config.gain_mask.m8;
peah1d680892017-05-23 04:07:10 -0700114
115 for (size_t k = 0; k < gain->size(); ++k) {
Jesús de Vicente Peña075cb2b2018-06-13 15:13:55 +0200116 // TODO(devicentepena): Experiment by removing the reverberation estimation
117 // from the nearend signal before computing the gains.
Per Åhgren7106d932017-10-09 08:25:18 +0200118 const float unity_gain_masker = std::max(nearend[k], masker[k]);
119 RTC_DCHECK_LE(0.f, nearend_masking_margin * unity_gain_masker);
Per Åhgrenb02644f2018-04-17 11:52:17 +0200120 if (weighted_echo[k] <= nearend_masking_margin * unity_gain_masker ||
Per Åhgren7106d932017-10-09 08:25:18 +0200121 unity_gain_masker <= 0.f) {
peah1d680892017-05-23 04:07:10 -0700122 (*gain)[k] = 1.f;
123 } else {
Per Åhgrend309b002017-10-09 23:50:44 +0200124 RTC_DCHECK_LT(0.f, unity_gain_masker);
Per Åhgrend309b002017-10-09 23:50:44 +0200125 (*gain)[k] =
Per Åhgrenb02644f2018-04-17 11:52:17 +0200126 std::max(0.f, (1.f - config.gain_mask.gain_curve_slope *
127 weighted_echo[k] / unity_gain_masker) *
128 config.gain_mask.gain_curve_offset);
129 (*gain)[k] = std::max(masker_margin * masker[k] * one_by_weighted_echo[k],
130 (*gain)[k]);
peah1d680892017-05-23 04:07:10 -0700131 }
132
133 (*gain)[k] = std::min(std::max((*gain)[k], min_gain[k]), max_gain[k]);
134 }
135}
136
Per Åhgren85a11a32017-10-02 14:42:06 +0200137// TODO(peah): Make adaptive to take the actual filter error into account.
138constexpr size_t kUpperAccurateBandPlus1 = 29;
139
Per Åhgren85a11a32017-10-02 14:42:06 +0200140// Limits the gain in the frequencies for which the adaptive filter has not
141// converged. Currently, these frequencies are not hardcoded to the frequencies
142// which are typically not excited by speech.
143// TODO(peah): Make adaptive to take the actual filter error into account.
144void AdjustNonConvergedFrequencies(
145 std::array<float, kFftLengthBy2Plus1>* gain) {
146 constexpr float oneByBandsInSum =
147 1 / static_cast<float>(kUpperAccurateBandPlus1 - 20);
148 const float hf_gain_bound =
149 std::accumulate(gain->begin() + 20,
150 gain->begin() + kUpperAccurateBandPlus1, 0.f) *
151 oneByBandsInSum;
152
153 std::for_each(gain->begin() + kUpperAccurateBandPlus1, gain->end(),
154 [hf_gain_bound](float& a) { a = std::min(a, hf_gain_bound); });
155}
156
peah1d680892017-05-23 04:07:10 -0700157} // namespace
158
Gustaf Ullberg216af842018-04-26 12:39:11 +0200159int SuppressionGain::instance_count_ = 0;
160
Per Åhgrenfde4aa92018-08-27 14:19:35 +0200161float SuppressionGain::UpperBandsGain(
162 const std::array<float, kFftLengthBy2Plus1>& echo_spectrum,
163 const std::array<float, kFftLengthBy2Plus1>& comfort_noise_spectrum,
164 const absl::optional<int>& narrow_peak_band,
165 bool saturated_echo,
166 const std::vector<std::vector<float>>& render,
167 const std::array<float, kFftLengthBy2Plus1>& low_band_gain) const {
168 RTC_DCHECK_LT(0, render.size());
169 if (render.size() == 1) {
170 return 1.f;
171 }
172
173 if (narrow_peak_band &&
174 (*narrow_peak_band > static_cast<int>(kFftLengthBy2Plus1 - 10))) {
175 return 0.001f;
176 }
177
178 constexpr size_t kLowBandGainLimit = kFftLengthBy2 / 2;
179 const float gain_below_8_khz = *std::min_element(
180 low_band_gain.begin() + kLowBandGainLimit, low_band_gain.end());
181
182 // Always attenuate the upper bands when there is saturated echo.
183 if (saturated_echo) {
184 return std::min(0.001f, gain_below_8_khz);
185 }
186
187 // Compute the upper and lower band energies.
188 const auto sum_of_squares = [](float a, float b) { return a + b * b; };
189 const float low_band_energy =
190 std::accumulate(render[0].begin(), render[0].end(), 0.f, sum_of_squares);
191 float high_band_energy = 0.f;
192 for (size_t k = 1; k < render.size(); ++k) {
193 const float energy = std::accumulate(render[k].begin(), render[k].end(),
194 0.f, sum_of_squares);
195 high_band_energy = std::max(high_band_energy, energy);
196 }
197
198 // If there is more power in the lower frequencies than the upper frequencies,
199 // or if the power in upper frequencies is low, do not bound the gain in the
200 // upper bands.
201 float anti_howling_gain;
202 constexpr float kThreshold = kBlockSize * 10.f * 10.f / 4.f;
203 if (high_band_energy < std::max(low_band_energy, kThreshold)) {
204 anti_howling_gain = 1.f;
205 } else {
206 // In all other cases, bound the gain for upper frequencies.
207 RTC_DCHECK_LE(low_band_energy, high_band_energy);
208 RTC_DCHECK_NE(0.f, high_band_energy);
209 anti_howling_gain = 0.01f * sqrtf(low_band_energy / high_band_energy);
210 }
211
212 // Bound the upper gain during significant echo activity.
213 auto low_frequency_energy = [](rtc::ArrayView<const float> spectrum) {
214 RTC_DCHECK_LE(16, spectrum.size());
215 return std::accumulate(spectrum.begin() + 1, spectrum.begin() + 16, 0.f);
216 };
217 const float echo_sum = low_frequency_energy(echo_spectrum);
218 const float noise_sum = low_frequency_energy(comfort_noise_spectrum);
219 const auto& cfg = config_.suppressor.high_bands_suppression;
220 float gain_bound = 1.f;
221 if (echo_sum > cfg.enr_threshold * noise_sum &&
222 !dominant_nearend_detector_.IsNearendState()) {
223 gain_bound = cfg.max_gain_during_echo;
224 }
225
226 // Choose the gain as the minimum of the lower and upper gains.
227 return std::min(std::min(gain_below_8_khz, anti_howling_gain), gain_bound);
228}
229
Gustaf Ullbergec642172018-07-03 13:48:32 +0200230// Computes the gain to reduce the echo to a non audible level.
231void SuppressionGain::GainToNoAudibleEcho(
232 const std::array<float, kFftLengthBy2Plus1>& nearend,
233 const std::array<float, kFftLengthBy2Plus1>& echo,
234 const std::array<float, kFftLengthBy2Plus1>& masker,
235 const std::array<float, kFftLengthBy2Plus1>& min_gain,
236 const std::array<float, kFftLengthBy2Plus1>& max_gain,
237 std::array<float, kFftLengthBy2Plus1>* gain) const {
Per Åhgren524e8782018-08-24 22:48:49 +0200238 const auto& p = dominant_nearend_detector_.IsNearendState() ? nearend_params_
239 : normal_params_;
Gustaf Ullbergec642172018-07-03 13:48:32 +0200240 for (size_t k = 0; k < gain->size(); ++k) {
241 float enr = echo[k] / (nearend[k] + 1.f); // Echo-to-nearend ratio.
242 float emr = echo[k] / (masker[k] + 1.f); // Echo-to-masker (noise) ratio.
243 float g = 1.0f;
Per Åhgren524e8782018-08-24 22:48:49 +0200244 if (enr > p.enr_transparent_[k] && emr > p.emr_transparent_[k]) {
245 g = (p.enr_suppress_[k] - enr) /
246 (p.enr_suppress_[k] - p.enr_transparent_[k]);
247 g = std::max(g, p.emr_transparent_[k] / emr);
Gustaf Ullbergec642172018-07-03 13:48:32 +0200248 }
249 (*gain)[k] = std::max(std::min(g, max_gain[k]), min_gain[k]);
250 }
251}
252
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200253// Compute the minimum gain as the attenuating gain to put the signal just
254// above the zero sample values.
255void SuppressionGain::GetMinGain(
256 rtc::ArrayView<const float> suppressor_input,
257 rtc::ArrayView<const float> weighted_residual_echo,
peah1d680892017-05-23 04:07:10 -0700258 bool low_noise_render,
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200259 bool saturated_echo,
260 rtc::ArrayView<float> min_gain) const {
Per Åhgren31122d62018-04-10 16:33:55 +0200261 if (!saturated_echo) {
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200262 const float min_echo_power =
263 low_noise_render ? config_.echo_audibility.low_render_limit
264 : config_.echo_audibility.normal_render_limit;
265
266 for (size_t k = 0; k < suppressor_input.size(); ++k) {
267 const float denom =
268 std::min(suppressor_input[k], weighted_residual_echo[k]);
peah1d680892017-05-23 04:07:10 -0700269 min_gain[k] = denom > 0.f ? min_echo_power / denom : 1.f;
270 min_gain[k] = std::min(min_gain[k], 1.f);
271 }
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200272 for (size_t k = 0; k < 6; ++k) {
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200273 const auto& dec = dominant_nearend_detector_.IsNearendState()
274 ? nearend_params_.max_dec_factor_lf
275 : normal_params_.max_dec_factor_lf;
276
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200277 // Make sure the gains of the low frequencies do not decrease too
278 // quickly after strong nearend.
279 if (last_nearend_[k] > last_echo_[k]) {
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200280 min_gain[k] = std::max(min_gain[k], last_gain_[k] * dec);
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200281 min_gain[k] = std::min(min_gain[k], 1.f);
Gustaf Ullberg0e6375e2018-05-04 11:29:02 +0200282 }
283 }
peah1d680892017-05-23 04:07:10 -0700284 } else {
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200285 std::fill(min_gain.begin(), min_gain.end(), 0.f);
peah1d680892017-05-23 04:07:10 -0700286 }
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200287}
peah1d680892017-05-23 04:07:10 -0700288
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200289// Compute the maximum gain by limiting the gain increase from the previous
290// gain.
291void SuppressionGain::GetMaxGain(rtc::ArrayView<float> max_gain) const {
292 const auto& inc = dominant_nearend_detector_.IsNearendState()
293 ? nearend_params_.max_inc_factor
294 : normal_params_.max_inc_factor;
295 const auto& floor = config_.suppressor.floor_first_increase;
296 for (size_t k = 0; k < max_gain.size(); ++k) {
297 max_gain[k] = std::min(std::max(last_gain_[k] * inc, floor), 1.f);
peah1d680892017-05-23 04:07:10 -0700298 }
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200299}
300
301// TODO(peah): Add further optimizations, in particular for the divisions.
302void SuppressionGain::LowerBandGain(
303 bool low_noise_render,
304 const AecState& aec_state,
305 const std::array<float, kFftLengthBy2Plus1>& suppressor_input,
306 const std::array<float, kFftLengthBy2Plus1>& nearend,
307 const std::array<float, kFftLengthBy2Plus1>& residual_echo,
308 const std::array<float, kFftLengthBy2Plus1>& comfort_noise,
309 std::array<float, kFftLengthBy2Plus1>* gain) {
310 const bool saturated_echo = aec_state.SaturatedEcho();
311
312 // Weight echo power in terms of audibility. // Precompute 1/weighted echo
313 // (note that when the echo is zero, the precomputed value is never used).
314 std::array<float, kFftLengthBy2Plus1> weighted_residual_echo;
315 WeightEchoForAudibility(config_, residual_echo, weighted_residual_echo);
316
317 std::array<float, kFftLengthBy2Plus1> min_gain;
318 GetMinGain(suppressor_input, weighted_residual_echo, low_noise_render,
319 saturated_echo, min_gain);
320
321 std::array<float, kFftLengthBy2Plus1> max_gain;
322 GetMaxGain(max_gain);
peah1d680892017-05-23 04:07:10 -0700323
324 // Iteratively compute the gain required to attenuate the echo to a non
325 // noticeable level.
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200326
Gustaf Ullbergec642172018-07-03 13:48:32 +0200327 if (enable_new_suppression_) {
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200328 GainToNoAudibleEcho(nearend, weighted_residual_echo, comfort_noise,
329 min_gain, max_gain, gain);
peah1d680892017-05-23 04:07:10 -0700330 AdjustForExternalFilters(gain);
Gustaf Ullbergec642172018-07-03 13:48:32 +0200331 } else {
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200332 const bool linear_echo_estimate = aec_state.UsableLinearEstimate();
333 std::array<float, kFftLengthBy2Plus1> masker;
334 std::array<float, kFftLengthBy2Plus1> one_by_weighted_echo;
335 std::transform(weighted_residual_echo.begin(), weighted_residual_echo.end(),
336 one_by_weighted_echo.begin(),
337 [](float e) { return e > 0.f ? 1.f / e : 1.f; });
Gustaf Ullbergec642172018-07-03 13:48:32 +0200338 gain->fill(0.f);
339 for (int k = 0; k < 2; ++k) {
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200340 std::copy(comfort_noise.begin(), comfort_noise.end(), masker.begin());
341 GainToNoAudibleEchoFallback(config_, low_noise_render, saturated_echo,
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200342 linear_echo_estimate, nearend,
343 weighted_residual_echo, masker, min_gain,
344 max_gain, one_by_weighted_echo, gain);
Gustaf Ullbergec642172018-07-03 13:48:32 +0200345 AdjustForExternalFilters(gain);
346 }
peah1d680892017-05-23 04:07:10 -0700347 }
348
Per Åhgren85a11a32017-10-02 14:42:06 +0200349 // Adjust the gain for frequencies which have not yet converged.
350 AdjustNonConvergedFrequencies(gain);
351
peah1d680892017-05-23 04:07:10 -0700352 // Store data required for the gain computation of the next block.
Gustaf Ullberg0e6375e2018-05-04 11:29:02 +0200353 std::copy(nearend.begin(), nearend.end(), last_nearend_.begin());
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200354 std::copy(weighted_residual_echo.begin(), weighted_residual_echo.end(),
355 last_echo_.begin());
peah1d680892017-05-23 04:07:10 -0700356 std::copy(gain->begin(), gain->end(), last_gain_.begin());
peah1d680892017-05-23 04:07:10 -0700357 aec3::VectorMath(optimization_).Sqrt(*gain);
Gustaf Ullberg216af842018-04-26 12:39:11 +0200358
359 // Debug outputs for the purpose of development and analysis.
360 data_dumper_->DumpRaw("aec3_suppressor_min_gain", min_gain);
361 data_dumper_->DumpRaw("aec3_suppressor_max_gain", max_gain);
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200362 data_dumper_->DumpRaw("aec3_dominant_nearend",
363 dominant_nearend_detector_.IsNearendState());
peah86afe9d2017-04-06 15:45:32 -0700364}
365
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200366SuppressionGain::SuppressionGain(const EchoCanceller3Config& config,
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200367 Aec3Optimization optimization,
368 int sample_rate_hz)
Gustaf Ullberg216af842018-04-26 12:39:11 +0200369 : data_dumper_(
370 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
371 optimization_(optimization),
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100372 config_(config),
373 state_change_duration_blocks_(
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200374 static_cast<int>(config_.filter.config_change_duration_blocks)),
Gustaf Ullbergec642172018-07-03 13:48:32 +0200375 enable_new_suppression_(EnableNewSuppression()),
Gustaf Ullberg8406c432018-06-19 12:31:33 +0200376 moving_average_(kFftLengthBy2Plus1,
Per Åhgren524e8782018-08-24 22:48:49 +0200377 config.suppressor.nearend_average_blocks),
378 nearend_params_(config_.suppressor.nearend_tuning),
379 normal_params_(config_.suppressor.normal_tuning),
380 dominant_nearend_detector_(
381 config_.suppressor.dominant_nearend_detection) {
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100382 RTC_DCHECK_LT(0, state_change_duration_blocks_);
383 one_by_state_change_duration_blocks_ = 1.f / state_change_duration_blocks_;
peah1d680892017-05-23 04:07:10 -0700384 last_gain_.fill(1.f);
Gustaf Ullberg0e6375e2018-05-04 11:29:02 +0200385 last_nearend_.fill(0.f);
peah1d680892017-05-23 04:07:10 -0700386 last_echo_.fill(0.f);
peah522d71b2017-02-23 05:16:26 -0800387}
388
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200389SuppressionGain::~SuppressionGain() = default;
390
peah522d71b2017-02-23 05:16:26 -0800391void SuppressionGain::GetGain(
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200392 const std::array<float, kFftLengthBy2Plus1>& suppressor_input_spectrum,
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200393 const std::array<float, kFftLengthBy2Plus1>& nearend_spectrum,
394 const std::array<float, kFftLengthBy2Plus1>& echo_spectrum,
Per Åhgrenfde4aa92018-08-27 14:19:35 +0200395 const std::array<float, kFftLengthBy2Plus1>& residual_echo_spectrum,
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200396 const std::array<float, kFftLengthBy2Plus1>& comfort_noise_spectrum,
397 const FftData& linear_aec_fft,
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200398 const FftData& capture_fft,
peah14c11a42017-07-11 06:13:43 -0700399 const RenderSignalAnalyzer& render_signal_analyzer,
Per Åhgren7ddd4632017-10-25 02:59:45 +0200400 const AecState& aec_state,
peah86afe9d2017-04-06 15:45:32 -0700401 const std::vector<std::vector<float>>& render,
peah86afe9d2017-04-06 15:45:32 -0700402 float* high_bands_gain,
403 std::array<float, kFftLengthBy2Plus1>* low_band_gain) {
404 RTC_DCHECK(high_bands_gain);
405 RTC_DCHECK(low_band_gain);
Per Åhgren7343f562018-08-17 10:08:34 +0200406 const auto& cfg = config_.suppressor;
407
408 if (cfg.enforce_transparent) {
409 low_band_gain->fill(1.f);
410 *high_bands_gain = cfg.enforce_empty_higher_bands ? 0.f : 1.f;
411 return;
412 }
peah86afe9d2017-04-06 15:45:32 -0700413
Gustaf Ullberg8406c432018-06-19 12:31:33 +0200414 std::array<float, kFftLengthBy2Plus1> nearend_average;
415 moving_average_.Average(nearend_spectrum, nearend_average);
416
Per Åhgren524e8782018-08-24 22:48:49 +0200417 // Update the state selection.
Per Åhgrenfde4aa92018-08-27 14:19:35 +0200418 dominant_nearend_detector_.Update(nearend_spectrum, residual_echo_spectrum,
Per Åhgren524e8782018-08-24 22:48:49 +0200419 comfort_noise_spectrum);
420
peah1d680892017-05-23 04:07:10 -0700421 // Compute gain for the lower band.
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100422 bool low_noise_render = low_render_detector_.Detect(render);
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200423 LowerBandGain(low_noise_render, aec_state, suppressor_input_spectrum,
424 nearend_average, residual_echo_spectrum, comfort_noise_spectrum,
425 low_band_gain);
peah86afe9d2017-04-06 15:45:32 -0700426
Gustaf Ullberg0cb4a252018-04-26 15:45:44 +0200427 // Limit the gain of the lower bands during start up and after resets.
428 const float gain_upper_bound = aec_state.SuppressionGainLimit();
429 if (gain_upper_bound < 1.f) {
430 for (size_t k = 0; k < low_band_gain->size(); ++k) {
431 (*low_band_gain)[k] = std::min((*low_band_gain)[k], gain_upper_bound);
432 }
433 }
434
435 // Compute the gain for the upper bands.
Jesús de Vicente Peña0faf0822018-09-24 12:48:28 +0200436 const absl::optional<int> narrow_peak_band =
437 render_signal_analyzer.NarrowPeakBand();
438
Per Åhgrenfde4aa92018-08-27 14:19:35 +0200439 *high_bands_gain =
440 UpperBandsGain(echo_spectrum, comfort_noise_spectrum, narrow_peak_band,
441 aec_state.SaturatedEcho(), render, *low_band_gain);
Per Åhgren7343f562018-08-17 10:08:34 +0200442 if (cfg.enforce_empty_higher_bands) {
443 *high_bands_gain = 0.f;
444 }
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100445}
446
447void SuppressionGain::SetInitialState(bool state) {
448 initial_state_ = state;
449 if (state) {
450 initial_state_change_counter_ = state_change_duration_blocks_;
451 } else {
452 initial_state_change_counter_ = 0;
453 }
454}
455
peah1d680892017-05-23 04:07:10 -0700456// Detects when the render signal can be considered to have low power and
457// consist of stationary noise.
458bool SuppressionGain::LowNoiseRenderDetector::Detect(
459 const std::vector<std::vector<float>>& render) {
460 float x2_sum = 0.f;
461 float x2_max = 0.f;
462 for (auto x_k : render[0]) {
463 const float x2 = x_k * x_k;
464 x2_sum += x2;
465 x2_max = std::max(x2_max, x2);
peah522d71b2017-02-23 05:16:26 -0800466 }
peah1d680892017-05-23 04:07:10 -0700467
468 constexpr float kThreshold = 50.f * 50.f * 64.f;
469 const bool low_noise_render =
470 average_power_ < kThreshold && x2_max < 3 * average_power_;
471 average_power_ = average_power_ * 0.9f + x2_sum * 0.1f;
472 return low_noise_render;
peah522d71b2017-02-23 05:16:26 -0800473}
474
Per Åhgren524e8782018-08-24 22:48:49 +0200475SuppressionGain::DominantNearendDetector::DominantNearendDetector(
476 const EchoCanceller3Config::Suppressor::DominantNearendDetection config)
477 : enr_threshold_(config.enr_threshold),
478 snr_threshold_(config.snr_threshold),
479 hold_duration_(config.hold_duration),
480 trigger_threshold_(config.trigger_threshold) {}
481
482void SuppressionGain::DominantNearendDetector::Update(
483 rtc::ArrayView<const float> nearend_spectrum,
Per Åhgrenfde4aa92018-08-27 14:19:35 +0200484 rtc::ArrayView<const float> residual_echo_spectrum,
Per Åhgren524e8782018-08-24 22:48:49 +0200485 rtc::ArrayView<const float> comfort_noise_spectrum) {
486 auto low_frequency_energy = [](rtc::ArrayView<const float> spectrum) {
487 RTC_DCHECK_LE(16, spectrum.size());
488 return std::accumulate(spectrum.begin() + 1, spectrum.begin() + 16, 0.f);
489 };
490 const float ne_sum = low_frequency_energy(nearend_spectrum);
Per Åhgrenfde4aa92018-08-27 14:19:35 +0200491 const float echo_sum = low_frequency_energy(residual_echo_spectrum);
Per Åhgren524e8782018-08-24 22:48:49 +0200492 const float noise_sum = low_frequency_energy(comfort_noise_spectrum);
493
494 // Detect strong active nearend if the nearend is sufficiently stronger than
495 // the echo and the nearend noise.
496 if (ne_sum > enr_threshold_ * echo_sum &&
497 ne_sum > snr_threshold_ * noise_sum) {
498 if (++trigger_counter_ >= trigger_threshold_) {
499 // After a period of strong active nearend activity, flag nearend mode.
500 hold_counter_ = hold_duration_;
501 trigger_counter_ = trigger_threshold_;
502 }
503 } else {
504 // Forget previously detected strong active nearend activity.
505 trigger_counter_ = std::max(0, trigger_counter_ - 1);
506 }
507
508 // Remain in any nearend mode for a certain duration.
509 hold_counter_ = std::max(0, hold_counter_ - 1);
510 nearend_state_ = hold_counter_ > 0;
511}
512
513SuppressionGain::GainParameters::GainParameters(
514 const EchoCanceller3Config::Suppressor::Tuning& tuning)
515 : max_inc_factor(tuning.max_inc_factor),
516 max_dec_factor_lf(tuning.max_dec_factor_lf) {
517 // Compute per-band masking thresholds.
518 constexpr size_t kLastLfBand = 5;
519 constexpr size_t kFirstHfBand = 8;
520 RTC_DCHECK_LT(kLastLfBand, kFirstHfBand);
521 auto& lf = tuning.mask_lf;
522 auto& hf = tuning.mask_hf;
523 RTC_DCHECK_LT(lf.enr_transparent, lf.enr_suppress);
524 RTC_DCHECK_LT(hf.enr_transparent, hf.enr_suppress);
525 for (size_t k = 0; k < kFftLengthBy2Plus1; k++) {
526 float a;
527 if (k <= kLastLfBand) {
528 a = 0.f;
529 } else if (k < kFirstHfBand) {
530 a = (k - kLastLfBand) / static_cast<float>(kFirstHfBand - kLastLfBand);
531 } else {
532 a = 1.f;
533 }
534 enr_transparent_[k] = (1 - a) * lf.enr_transparent + a * hf.enr_transparent;
535 enr_suppress_[k] = (1 - a) * lf.enr_suppress + a * hf.enr_suppress;
536 emr_transparent_[k] = (1 - a) * lf.emr_transparent + a * hf.emr_transparent;
537 }
538}
539
peah522d71b2017-02-23 05:16:26 -0800540} // namespace webrtc