blob: 2d88ab28631a88bbf2dad200047add79d406ac89 [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
peah1d680892017-05-23 04:07:10 -070050// Computes the gain to apply for the bands beyond the first band.
51float UpperBandsGain(
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +020052 const absl::optional<int>& narrow_peak_band,
peah1d680892017-05-23 04:07:10 -070053 bool saturated_echo,
54 const std::vector<std::vector<float>>& render,
55 const std::array<float, kFftLengthBy2Plus1>& low_band_gain) {
56 RTC_DCHECK_LT(0, render.size());
peah86afe9d2017-04-06 15:45:32 -070057 if (render.size() == 1) {
58 return 1.f;
59 }
60
peah14c11a42017-07-11 06:13:43 -070061 if (narrow_peak_band &&
62 (*narrow_peak_band > static_cast<int>(kFftLengthBy2Plus1 - 10))) {
63 return 0.001f;
64 }
65
peah1d680892017-05-23 04:07:10 -070066 constexpr size_t kLowBandGainLimit = kFftLengthBy2 / 2;
67 const float gain_below_8_khz = *std::min_element(
68 low_band_gain.begin() + kLowBandGainLimit, low_band_gain.end());
69
peah86afe9d2017-04-06 15:45:32 -070070 // Always attenuate the upper bands when there is saturated echo.
71 if (saturated_echo) {
peah1d680892017-05-23 04:07:10 -070072 return std::min(0.001f, gain_below_8_khz);
peah86afe9d2017-04-06 15:45:32 -070073 }
74
75 // Compute the upper and lower band energies.
peah1d680892017-05-23 04:07:10 -070076 const auto sum_of_squares = [](float a, float b) { return a + b * b; };
77 const float low_band_energy =
78 std::accumulate(render[0].begin(), render[0].end(), 0.f, sum_of_squares);
79 float high_band_energy = 0.f;
peah86afe9d2017-04-06 15:45:32 -070080 for (size_t k = 1; k < render.size(); ++k) {
peah1d680892017-05-23 04:07:10 -070081 const float energy = std::accumulate(render[k].begin(), render[k].end(),
82 0.f, sum_of_squares);
83 high_band_energy = std::max(high_band_energy, energy);
peah86afe9d2017-04-06 15:45:32 -070084 }
85
86 // If there is more power in the lower frequencies than the upper frequencies,
peah1d680892017-05-23 04:07:10 -070087 // or if the power in upper frequencies is low, do not bound the gain in the
peah86afe9d2017-04-06 15:45:32 -070088 // upper bands.
peah1d680892017-05-23 04:07:10 -070089 float anti_howling_gain;
Per Åhgren38e2d952017-11-17 14:54:28 +010090 constexpr float kThreshold = kBlockSize * 10.f * 10.f / 4.f;
peah1d680892017-05-23 04:07:10 -070091 if (high_band_energy < std::max(low_band_energy, kThreshold)) {
92 anti_howling_gain = 1.f;
93 } else {
94 // In all other cases, bound the gain for upper frequencies.
95 RTC_DCHECK_LE(low_band_energy, high_band_energy);
96 RTC_DCHECK_NE(0.f, high_band_energy);
97 anti_howling_gain = 0.01f * sqrtf(low_band_energy / high_band_energy);
peah86afe9d2017-04-06 15:45:32 -070098 }
99
peah1d680892017-05-23 04:07:10 -0700100 // Choose the gain as the minimum of the lower and upper gains.
101 return std::min(gain_below_8_khz, anti_howling_gain);
102}
103
Per Åhgrenb02644f2018-04-17 11:52:17 +0200104// Scales the echo according to assessed audibility at the other end.
105void WeightEchoForAudibility(const EchoCanceller3Config& config,
106 rtc::ArrayView<const float> echo,
107 rtc::ArrayView<float> weighted_echo,
108 rtc::ArrayView<float> one_by_weighted_echo) {
109 RTC_DCHECK_EQ(kFftLengthBy2Plus1, echo.size());
110 RTC_DCHECK_EQ(kFftLengthBy2Plus1, weighted_echo.size());
111 RTC_DCHECK_EQ(kFftLengthBy2Plus1, one_by_weighted_echo.size());
112
113 auto weigh = [](float threshold, float normalizer, size_t begin, size_t end,
114 rtc::ArrayView<const float> echo,
115 rtc::ArrayView<float> weighted_echo,
116 rtc::ArrayView<float> one_by_weighted_echo) {
117 for (size_t k = begin; k < end; ++k) {
118 if (echo[k] < threshold) {
119 float tmp = (threshold - echo[k]) * normalizer;
120 weighted_echo[k] = echo[k] * std::max(0.f, 1.f - tmp * tmp);
121 } else {
122 weighted_echo[k] = echo[k];
123 }
124 one_by_weighted_echo[k] =
125 weighted_echo[k] > 0.f ? 1.f / weighted_echo[k] : 1.f;
126 }
127 };
128
129 float threshold = config.echo_audibility.floor_power *
130 config.echo_audibility.audibility_threshold_lf;
131 float normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
132 weigh(threshold, normalizer, 0, 3, echo, weighted_echo, one_by_weighted_echo);
133
134 threshold = config.echo_audibility.floor_power *
135 config.echo_audibility.audibility_threshold_mf;
136 normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
137 weigh(threshold, normalizer, 3, 7, echo, weighted_echo, one_by_weighted_echo);
138
139 threshold = config.echo_audibility.floor_power *
140 config.echo_audibility.audibility_threshold_hf;
141 normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
142 weigh(threshold, normalizer, 7, kFftLengthBy2Plus1, echo, weighted_echo,
143 one_by_weighted_echo);
144}
145
peah1d680892017-05-23 04:07:10 -0700146// Computes the gain to reduce the echo to a non audible level.
Gustaf Ullbergec642172018-07-03 13:48:32 +0200147void GainToNoAudibleEchoFallback(
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200148 const EchoCanceller3Config& config,
peah1d680892017-05-23 04:07:10 -0700149 bool low_noise_render,
150 bool saturated_echo,
Per Åhgrenc65ce782017-10-09 13:01:39 +0200151 bool linear_echo_estimate,
peah1d680892017-05-23 04:07:10 -0700152 const std::array<float, kFftLengthBy2Plus1>& nearend,
Per Åhgrenb02644f2018-04-17 11:52:17 +0200153 const std::array<float, kFftLengthBy2Plus1>& weighted_echo,
peah1d680892017-05-23 04:07:10 -0700154 const std::array<float, kFftLengthBy2Plus1>& masker,
155 const std::array<float, kFftLengthBy2Plus1>& min_gain,
156 const std::array<float, kFftLengthBy2Plus1>& max_gain,
Per Åhgrenb02644f2018-04-17 11:52:17 +0200157 const std::array<float, kFftLengthBy2Plus1>& one_by_weighted_echo,
peah1d680892017-05-23 04:07:10 -0700158 std::array<float, kFftLengthBy2Plus1>* gain) {
Per Åhgrenc65ce782017-10-09 13:01:39 +0200159 float nearend_masking_margin = 0.f;
Per Åhgren63b494d2017-12-06 11:32:38 +0100160 if (linear_echo_estimate) {
161 nearend_masking_margin =
162 low_noise_render
163 ? config.gain_mask.m9
164 : (saturated_echo ? config.gain_mask.m2 : config.gain_mask.m3);
Per Åhgrenc65ce782017-10-09 13:01:39 +0200165 } else {
Per Åhgren63b494d2017-12-06 11:32:38 +0100166 nearend_masking_margin = config.gain_mask.m7;
Per Åhgrenc65ce782017-10-09 13:01:39 +0200167 }
Per Åhgren7ddd4632017-10-25 02:59:45 +0200168
Per Åhgrend309b002017-10-09 23:50:44 +0200169 RTC_DCHECK_LE(0.f, nearend_masking_margin);
170 RTC_DCHECK_GT(1.f, nearend_masking_margin);
Per Åhgrend309b002017-10-09 23:50:44 +0200171
Per Åhgren63b494d2017-12-06 11:32:38 +0100172 const float masker_margin =
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200173 linear_echo_estimate ? config.gain_mask.m0 : config.gain_mask.m8;
peah1d680892017-05-23 04:07:10 -0700174
175 for (size_t k = 0; k < gain->size(); ++k) {
Jesús de Vicente Peña075cb2b2018-06-13 15:13:55 +0200176 // TODO(devicentepena): Experiment by removing the reverberation estimation
177 // from the nearend signal before computing the gains.
Per Åhgren7106d932017-10-09 08:25:18 +0200178 const float unity_gain_masker = std::max(nearend[k], masker[k]);
179 RTC_DCHECK_LE(0.f, nearend_masking_margin * unity_gain_masker);
Per Åhgrenb02644f2018-04-17 11:52:17 +0200180 if (weighted_echo[k] <= nearend_masking_margin * unity_gain_masker ||
Per Åhgren7106d932017-10-09 08:25:18 +0200181 unity_gain_masker <= 0.f) {
peah1d680892017-05-23 04:07:10 -0700182 (*gain)[k] = 1.f;
183 } else {
Per Åhgrend309b002017-10-09 23:50:44 +0200184 RTC_DCHECK_LT(0.f, unity_gain_masker);
Per Åhgrend309b002017-10-09 23:50:44 +0200185 (*gain)[k] =
Per Åhgrenb02644f2018-04-17 11:52:17 +0200186 std::max(0.f, (1.f - config.gain_mask.gain_curve_slope *
187 weighted_echo[k] / unity_gain_masker) *
188 config.gain_mask.gain_curve_offset);
189 (*gain)[k] = std::max(masker_margin * masker[k] * one_by_weighted_echo[k],
190 (*gain)[k]);
peah1d680892017-05-23 04:07:10 -0700191 }
192
193 (*gain)[k] = std::min(std::max((*gain)[k], min_gain[k]), max_gain[k]);
194 }
195}
196
Per Åhgren85a11a32017-10-02 14:42:06 +0200197// TODO(peah): Make adaptive to take the actual filter error into account.
198constexpr size_t kUpperAccurateBandPlus1 = 29;
199
Per Åhgren85a11a32017-10-02 14:42:06 +0200200// Limits the gain in the frequencies for which the adaptive filter has not
201// converged. Currently, these frequencies are not hardcoded to the frequencies
202// which are typically not excited by speech.
203// TODO(peah): Make adaptive to take the actual filter error into account.
204void AdjustNonConvergedFrequencies(
205 std::array<float, kFftLengthBy2Plus1>* gain) {
206 constexpr float oneByBandsInSum =
207 1 / static_cast<float>(kUpperAccurateBandPlus1 - 20);
208 const float hf_gain_bound =
209 std::accumulate(gain->begin() + 20,
210 gain->begin() + kUpperAccurateBandPlus1, 0.f) *
211 oneByBandsInSum;
212
213 std::for_each(gain->begin() + kUpperAccurateBandPlus1, gain->end(),
214 [hf_gain_bound](float& a) { a = std::min(a, hf_gain_bound); });
215}
216
peah1d680892017-05-23 04:07:10 -0700217} // namespace
218
Gustaf Ullberg216af842018-04-26 12:39:11 +0200219int SuppressionGain::instance_count_ = 0;
220
Gustaf Ullbergec642172018-07-03 13:48:32 +0200221// Computes the gain to reduce the echo to a non audible level.
222void SuppressionGain::GainToNoAudibleEcho(
223 const std::array<float, kFftLengthBy2Plus1>& nearend,
224 const std::array<float, kFftLengthBy2Plus1>& echo,
225 const std::array<float, kFftLengthBy2Plus1>& masker,
226 const std::array<float, kFftLengthBy2Plus1>& min_gain,
227 const std::array<float, kFftLengthBy2Plus1>& max_gain,
228 std::array<float, kFftLengthBy2Plus1>* gain) const {
Per Åhgren524e8782018-08-24 22:48:49 +0200229 const auto& p = dominant_nearend_detector_.IsNearendState() ? nearend_params_
230 : normal_params_;
Gustaf Ullbergec642172018-07-03 13:48:32 +0200231 for (size_t k = 0; k < gain->size(); ++k) {
232 float enr = echo[k] / (nearend[k] + 1.f); // Echo-to-nearend ratio.
233 float emr = echo[k] / (masker[k] + 1.f); // Echo-to-masker (noise) ratio.
234 float g = 1.0f;
Per Åhgren524e8782018-08-24 22:48:49 +0200235 if (enr > p.enr_transparent_[k] && emr > p.emr_transparent_[k]) {
236 g = (p.enr_suppress_[k] - enr) /
237 (p.enr_suppress_[k] - p.enr_transparent_[k]);
238 g = std::max(g, p.emr_transparent_[k] / emr);
Gustaf Ullbergec642172018-07-03 13:48:32 +0200239 }
240 (*gain)[k] = std::max(std::min(g, max_gain[k]), min_gain[k]);
241 }
242}
243
peah1d680892017-05-23 04:07:10 -0700244// TODO(peah): Add further optimizations, in particular for the divisions.
245void SuppressionGain::LowerBandGain(
246 bool low_noise_render,
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100247 const AecState& aec_state,
peah1d680892017-05-23 04:07:10 -0700248 const std::array<float, kFftLengthBy2Plus1>& nearend,
249 const std::array<float, kFftLengthBy2Plus1>& echo,
250 const std::array<float, kFftLengthBy2Plus1>& comfort_noise,
251 std::array<float, kFftLengthBy2Plus1>* gain) {
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100252 const bool saturated_echo = aec_state.SaturatedEcho();
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100253 const bool linear_echo_estimate = aec_state.UsableLinearEstimate();
Per Åhgren524e8782018-08-24 22:48:49 +0200254 const auto& params = dominant_nearend_detector_.IsNearendState()
255 ? nearend_params_
256 : normal_params_;
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100257
Per Åhgrenb02644f2018-04-17 11:52:17 +0200258 // Weight echo power in terms of audibility. // Precompute 1/weighted echo
259 // (note that when the echo is zero, the precomputed value is never used).
260 std::array<float, kFftLengthBy2Plus1> weighted_echo;
261 std::array<float, kFftLengthBy2Plus1> one_by_weighted_echo;
262 WeightEchoForAudibility(config_, echo, weighted_echo, one_by_weighted_echo);
peah1d680892017-05-23 04:07:10 -0700263
264 // Compute the minimum gain as the attenuating gain to put the signal just
265 // above the zero sample values.
266 std::array<float, kFftLengthBy2Plus1> min_gain;
peah8cee56f2017-08-24 22:36:53 -0700267 const float min_echo_power =
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200268 low_noise_render ? config_.echo_audibility.low_render_limit
269 : config_.echo_audibility.normal_render_limit;
Per Åhgren31122d62018-04-10 16:33:55 +0200270 if (!saturated_echo) {
peah1d680892017-05-23 04:07:10 -0700271 for (size_t k = 0; k < nearend.size(); ++k) {
Per Åhgrenb02644f2018-04-17 11:52:17 +0200272 const float denom = std::min(nearend[k], weighted_echo[k]);
peah1d680892017-05-23 04:07:10 -0700273 min_gain[k] = denom > 0.f ? min_echo_power / denom : 1.f;
274 min_gain[k] = std::min(min_gain[k], 1.f);
275 }
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200276 for (size_t k = 0; k < 6; ++k) {
277 // 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]) {
280 min_gain[k] =
Per Åhgren524e8782018-08-24 22:48:49 +0200281 std::max(min_gain[k], last_gain_[k] * params.max_dec_factor_lf);
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200282 min_gain[k] = std::min(min_gain[k], 1.f);
Gustaf Ullberg0e6375e2018-05-04 11:29:02 +0200283 }
284 }
peah1d680892017-05-23 04:07:10 -0700285 } else {
286 min_gain.fill(0.f);
287 }
288
289 // Compute the maximum gain by limiting the gain increase from the previous
290 // gain.
291 std::array<float, kFftLengthBy2Plus1> max_gain;
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200292 for (size_t k = 0; k < gain->size(); ++k) {
Per Åhgren524e8782018-08-24 22:48:49 +0200293 max_gain[k] = std::min(std::max(last_gain_[k] * params.max_inc_factor,
294 config_.suppressor.floor_first_increase),
295 1.f);
peah1d680892017-05-23 04:07:10 -0700296 }
297
298 // Iteratively compute the gain required to attenuate the echo to a non
299 // noticeable level.
Gustaf Ullberg216af842018-04-26 12:39:11 +0200300 std::array<float, kFftLengthBy2Plus1> masker;
Gustaf Ullbergec642172018-07-03 13:48:32 +0200301 if (enable_new_suppression_) {
302 GainToNoAudibleEcho(nearend, weighted_echo, comfort_noise, min_gain,
303 max_gain, gain);
peah1d680892017-05-23 04:07:10 -0700304 AdjustForExternalFilters(gain);
Gustaf Ullbergec642172018-07-03 13:48:32 +0200305 } else {
306 gain->fill(0.f);
307 for (int k = 0; k < 2; ++k) {
Gustaf Ullbergecb2d562018-08-23 15:11:38 +0200308 std::copy(comfort_noise.begin(), comfort_noise.end(), masker.begin());
309 GainToNoAudibleEchoFallback(config_, low_noise_render, saturated_echo,
310 linear_echo_estimate, nearend, weighted_echo,
311 masker, min_gain, max_gain,
312 one_by_weighted_echo, gain);
Gustaf Ullbergec642172018-07-03 13:48:32 +0200313 AdjustForExternalFilters(gain);
314 }
peah1d680892017-05-23 04:07:10 -0700315 }
316
Per Åhgren85a11a32017-10-02 14:42:06 +0200317 // Adjust the gain for frequencies which have not yet converged.
318 AdjustNonConvergedFrequencies(gain);
319
peah1d680892017-05-23 04:07:10 -0700320 // Store data required for the gain computation of the next block.
Gustaf Ullberg0e6375e2018-05-04 11:29:02 +0200321 std::copy(nearend.begin(), nearend.end(), last_nearend_.begin());
Per Åhgrenb02644f2018-04-17 11:52:17 +0200322 std::copy(weighted_echo.begin(), weighted_echo.end(), last_echo_.begin());
peah1d680892017-05-23 04:07:10 -0700323 std::copy(gain->begin(), gain->end(), last_gain_.begin());
peah1d680892017-05-23 04:07:10 -0700324 aec3::VectorMath(optimization_).Sqrt(*gain);
Gustaf Ullberg216af842018-04-26 12:39:11 +0200325
326 // Debug outputs for the purpose of development and analysis.
327 data_dumper_->DumpRaw("aec3_suppressor_min_gain", min_gain);
328 data_dumper_->DumpRaw("aec3_suppressor_max_gain", max_gain);
329 data_dumper_->DumpRaw("aec3_suppressor_masker", masker);
peah86afe9d2017-04-06 15:45:32 -0700330}
331
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200332SuppressionGain::SuppressionGain(const EchoCanceller3Config& config,
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200333 Aec3Optimization optimization,
334 int sample_rate_hz)
Gustaf Ullberg216af842018-04-26 12:39:11 +0200335 : data_dumper_(
336 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
337 optimization_(optimization),
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100338 config_(config),
339 state_change_duration_blocks_(
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200340 static_cast<int>(config_.filter.config_change_duration_blocks)),
Gustaf Ullbergec642172018-07-03 13:48:32 +0200341 enable_new_suppression_(EnableNewSuppression()),
Gustaf Ullberg8406c432018-06-19 12:31:33 +0200342 moving_average_(kFftLengthBy2Plus1,
Per Åhgren524e8782018-08-24 22:48:49 +0200343 config.suppressor.nearend_average_blocks),
344 nearend_params_(config_.suppressor.nearend_tuning),
345 normal_params_(config_.suppressor.normal_tuning),
346 dominant_nearend_detector_(
347 config_.suppressor.dominant_nearend_detection) {
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100348 RTC_DCHECK_LT(0, state_change_duration_blocks_);
349 one_by_state_change_duration_blocks_ = 1.f / state_change_duration_blocks_;
peah1d680892017-05-23 04:07:10 -0700350 last_gain_.fill(1.f);
Gustaf Ullberg0e6375e2018-05-04 11:29:02 +0200351 last_nearend_.fill(0.f);
peah1d680892017-05-23 04:07:10 -0700352 last_echo_.fill(0.f);
peah522d71b2017-02-23 05:16:26 -0800353}
354
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200355SuppressionGain::~SuppressionGain() = default;
356
peah522d71b2017-02-23 05:16:26 -0800357void SuppressionGain::GetGain(
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200358 const std::array<float, kFftLengthBy2Plus1>& nearend_spectrum,
359 const std::array<float, kFftLengthBy2Plus1>& echo_spectrum,
360 const std::array<float, kFftLengthBy2Plus1>& comfort_noise_spectrum,
361 const FftData& linear_aec_fft,
Per Åhgren47d7fbd2018-04-24 12:44:29 +0200362 const FftData& capture_fft,
peah14c11a42017-07-11 06:13:43 -0700363 const RenderSignalAnalyzer& render_signal_analyzer,
Per Åhgren7ddd4632017-10-25 02:59:45 +0200364 const AecState& aec_state,
peah86afe9d2017-04-06 15:45:32 -0700365 const std::vector<std::vector<float>>& render,
peah86afe9d2017-04-06 15:45:32 -0700366 float* high_bands_gain,
367 std::array<float, kFftLengthBy2Plus1>* low_band_gain) {
368 RTC_DCHECK(high_bands_gain);
369 RTC_DCHECK(low_band_gain);
Per Åhgren7343f562018-08-17 10:08:34 +0200370 const auto& cfg = config_.suppressor;
371
372 if (cfg.enforce_transparent) {
373 low_band_gain->fill(1.f);
374 *high_bands_gain = cfg.enforce_empty_higher_bands ? 0.f : 1.f;
375 return;
376 }
peah86afe9d2017-04-06 15:45:32 -0700377
Gustaf Ullberg8406c432018-06-19 12:31:33 +0200378 std::array<float, kFftLengthBy2Plus1> nearend_average;
379 moving_average_.Average(nearend_spectrum, nearend_average);
380
Per Åhgren524e8782018-08-24 22:48:49 +0200381 // Update the state selection.
382 dominant_nearend_detector_.Update(nearend_spectrum, echo_spectrum,
383 comfort_noise_spectrum);
384
peah1d680892017-05-23 04:07:10 -0700385 // Compute gain for the lower band.
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100386 bool low_noise_render = low_render_detector_.Detect(render);
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +0200387 const absl::optional<int> narrow_peak_band =
peah14c11a42017-07-11 06:13:43 -0700388 render_signal_analyzer.NarrowPeakBand();
Gustaf Ullberg8406c432018-06-19 12:31:33 +0200389 LowerBandGain(low_noise_render, aec_state, nearend_average, echo_spectrum,
Gustaf Ullberg5bb98972018-04-25 12:54:59 +0200390 comfort_noise_spectrum, low_band_gain);
peah86afe9d2017-04-06 15:45:32 -0700391
Gustaf Ullberg0cb4a252018-04-26 15:45:44 +0200392 // Limit the gain of the lower bands during start up and after resets.
393 const float gain_upper_bound = aec_state.SuppressionGainLimit();
394 if (gain_upper_bound < 1.f) {
395 for (size_t k = 0; k < low_band_gain->size(); ++k) {
396 (*low_band_gain)[k] = std::min((*low_band_gain)[k], gain_upper_bound);
397 }
398 }
399
400 // Compute the gain for the upper bands.
401 *high_bands_gain = UpperBandsGain(narrow_peak_band, aec_state.SaturatedEcho(),
402 render, *low_band_gain);
Per Åhgren7343f562018-08-17 10:08:34 +0200403 if (cfg.enforce_empty_higher_bands) {
404 *high_bands_gain = 0.f;
405 }
Per Åhgren5f1a31c2018-03-08 15:54:41 +0100406}
407
408void SuppressionGain::SetInitialState(bool state) {
409 initial_state_ = state;
410 if (state) {
411 initial_state_change_counter_ = state_change_duration_blocks_;
412 } else {
413 initial_state_change_counter_ = 0;
414 }
415}
416
peah1d680892017-05-23 04:07:10 -0700417// Detects when the render signal can be considered to have low power and
418// consist of stationary noise.
419bool SuppressionGain::LowNoiseRenderDetector::Detect(
420 const std::vector<std::vector<float>>& render) {
421 float x2_sum = 0.f;
422 float x2_max = 0.f;
423 for (auto x_k : render[0]) {
424 const float x2 = x_k * x_k;
425 x2_sum += x2;
426 x2_max = std::max(x2_max, x2);
peah522d71b2017-02-23 05:16:26 -0800427 }
peah1d680892017-05-23 04:07:10 -0700428
429 constexpr float kThreshold = 50.f * 50.f * 64.f;
430 const bool low_noise_render =
431 average_power_ < kThreshold && x2_max < 3 * average_power_;
432 average_power_ = average_power_ * 0.9f + x2_sum * 0.1f;
433 return low_noise_render;
peah522d71b2017-02-23 05:16:26 -0800434}
435
Per Åhgren524e8782018-08-24 22:48:49 +0200436SuppressionGain::DominantNearendDetector::DominantNearendDetector(
437 const EchoCanceller3Config::Suppressor::DominantNearendDetection config)
438 : enr_threshold_(config.enr_threshold),
439 snr_threshold_(config.snr_threshold),
440 hold_duration_(config.hold_duration),
441 trigger_threshold_(config.trigger_threshold) {}
442
443void SuppressionGain::DominantNearendDetector::Update(
444 rtc::ArrayView<const float> nearend_spectrum,
445 rtc::ArrayView<const float> echo_spectrum,
446 rtc::ArrayView<const float> comfort_noise_spectrum) {
447 auto low_frequency_energy = [](rtc::ArrayView<const float> spectrum) {
448 RTC_DCHECK_LE(16, spectrum.size());
449 return std::accumulate(spectrum.begin() + 1, spectrum.begin() + 16, 0.f);
450 };
451 const float ne_sum = low_frequency_energy(nearend_spectrum);
452 const float echo_sum = low_frequency_energy(echo_spectrum);
453 const float noise_sum = low_frequency_energy(comfort_noise_spectrum);
454
455 // Detect strong active nearend if the nearend is sufficiently stronger than
456 // the echo and the nearend noise.
457 if (ne_sum > enr_threshold_ * echo_sum &&
458 ne_sum > snr_threshold_ * noise_sum) {
459 if (++trigger_counter_ >= trigger_threshold_) {
460 // After a period of strong active nearend activity, flag nearend mode.
461 hold_counter_ = hold_duration_;
462 trigger_counter_ = trigger_threshold_;
463 }
464 } else {
465 // Forget previously detected strong active nearend activity.
466 trigger_counter_ = std::max(0, trigger_counter_ - 1);
467 }
468
469 // Remain in any nearend mode for a certain duration.
470 hold_counter_ = std::max(0, hold_counter_ - 1);
471 nearend_state_ = hold_counter_ > 0;
472}
473
474SuppressionGain::GainParameters::GainParameters(
475 const EchoCanceller3Config::Suppressor::Tuning& tuning)
476 : max_inc_factor(tuning.max_inc_factor),
477 max_dec_factor_lf(tuning.max_dec_factor_lf) {
478 // Compute per-band masking thresholds.
479 constexpr size_t kLastLfBand = 5;
480 constexpr size_t kFirstHfBand = 8;
481 RTC_DCHECK_LT(kLastLfBand, kFirstHfBand);
482 auto& lf = tuning.mask_lf;
483 auto& hf = tuning.mask_hf;
484 RTC_DCHECK_LT(lf.enr_transparent, lf.enr_suppress);
485 RTC_DCHECK_LT(hf.enr_transparent, hf.enr_suppress);
486 for (size_t k = 0; k < kFftLengthBy2Plus1; k++) {
487 float a;
488 if (k <= kLastLfBand) {
489 a = 0.f;
490 } else if (k < kFirstHfBand) {
491 a = (k - kLastLfBand) / static_cast<float>(kFirstHfBand - kLastLfBand);
492 } else {
493 a = 1.f;
494 }
495 enr_transparent_[k] = (1 - a) * lf.enr_transparent + a * hf.enr_transparent;
496 enr_suppress_[k] = (1 - a) * lf.enr_suppress + a * hf.enr_suppress;
497 emr_transparent_[k] = (1 - a) * lf.emr_transparent + a * hf.emr_transparent;
498 }
499}
500
peah522d71b2017-02-23 05:16:26 -0800501} // namespace webrtc