Debian Codegraph @

Xpjproject/third_party/webrtc_aec3/src/modules/audio_processing/aec3/suppression_gain.cc

raw symbols SCIP
1 /*
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
11 #include "modules/audio_processing/aec3/suppression_gain.h"
12
13 #include <math.h>
14 #include <stddef.h>
15
16 #include <algorithm>
17 #include <numeric>
18
19 #include "modules/audio_processing/aec3/dominant_nearend_detector.h"
20 #include "modules/audio_processing/aec3/moving_average.h"
21 #include "modules/audio_processing/aec3/subband_nearend_detector.h"
22 #include "modules/audio_processing/aec3/vector_math.h"
23 #include "modules/audio_processing/logging/apm_data_dumper.h"
24 #include "rtc_base/atomic_ops.h"
25 #include "rtc_base/checks.h"
26
27 namespace webrtc {
28 namespace {
29
30 void LimitLowFrequencyGains(std::array<float, kFftLengthBy2Plus1>* gain) {
31 // Limit the low frequency gains to avoid the impact of the high-pass filter
32 // on the lower-frequency gain influencing the overall achieved gain.
33 (*gain)[0] = (*gain)[1] = std::min((*gain)[1], (*gain)[2]);
34 }
35
36 void LimitHighFrequencyGains(bool conservative_hf_suppression,
37 std::array<float, kFftLengthBy2Plus1>* gain) {
38 // Limit the high frequency gains to avoid echo leakage due to an imperfect
39 // filter.
40 constexpr size_t kFirstBandToLimit = (64 * 2000) / 8000;
41 const float min_upper_gain = (*gain)[kFirstBandToLimit];
42 std::for_each(
43 gain->begin() + kFirstBandToLimit + 1, gain->end(),
44 [min_upper_gain](float& a) { a = std::min(a, min_upper_gain); });
45 (*gain)[kFftLengthBy2] = (*gain)[kFftLengthBy2Minus1];
46
47 if (conservative_hf_suppression) {
48 // Limits the gain in the frequencies for which the adaptive filter has not
49 // converged.
50 // TODO(peah): Make adaptive to take the actual filter error into account.
51 constexpr size_t kUpperAccurateBandPlus1 = 29;
52
53 constexpr float oneByBandsInSum =
54 1 / static_cast<float>(kUpperAccurateBandPlus1 - 20);
55 const float hf_gain_bound =
56 std::accumulate(gain->begin() + 20,
57 gain->begin() + kUpperAccurateBandPlus1, 0.f) *
58 oneByBandsInSum;
59
60 std::for_each(
61 gain->begin() + kUpperAccurateBandPlus1, gain->end(),
62 [hf_gain_bound](float& a) { a = std::min(a, hf_gain_bound); });
63 }
64 }
65
66 // Scales the echo according to assessed audibility at the other end.
67 void WeightEchoForAudibility(const EchoCanceller3Config& config,
68 rtc::ArrayView<const float> echo,
69 rtc::ArrayView<float> weighted_echo) {
70 RTC_DCHECK_EQ(kFftLengthBy2Plus1, echo.size());
71 RTC_DCHECK_EQ(kFftLengthBy2Plus1, weighted_echo.size());
72
73 auto weigh = [](float threshold, float normalizer, size_t begin, size_t end,
74 rtc::ArrayView<const float> echo,
75 rtc::ArrayView<float> weighted_echo) {
76 for (size_t k = begin; k < end; ++k) {
77 if (echo[k] < threshold) {
78 float tmp = (threshold - echo[k]) * normalizer;
79 weighted_echo[k] = echo[k] * std::max(0.f, 1.f - tmp * tmp);
80 } else {
81 weighted_echo[k] = echo[k];
82 }
83 }
84 };
85
86 float threshold = config.echo_audibility.floor_power *
87 config.echo_audibility.audibility_threshold_lf;
88 float normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
89 weigh(threshold, normalizer, 0, 3, echo, weighted_echo);
90
91 threshold = config.echo_audibility.floor_power *
92 config.echo_audibility.audibility_threshold_mf;
93 normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
94 weigh(threshold, normalizer, 3, 7, echo, weighted_echo);
95
96 threshold = config.echo_audibility.floor_power *
97 config.echo_audibility.audibility_threshold_hf;
98 normalizer = 1.f / (threshold - config.echo_audibility.floor_power);
99 weigh(threshold, normalizer, 7, kFftLengthBy2Plus1, echo, weighted_echo);
100 }
101
102 } // namespace
103
104 int SuppressionGain::instance_count_ = 0;
105
106 float SuppressionGain::UpperBandsGain(
107 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>> echo_spectrum,
108 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
109 comfort_noise_spectrum,
110 const absl::optional<int>& narrow_peak_band,
111 bool saturated_echo,
112 const std::vector<std::vector<std::vector<float>>>& render,
113 const std::array<float, kFftLengthBy2Plus1>& low_band_gain) const {
114 RTC_DCHECK_LT(0, render.size());
115 if (render.size() == 1) {
116 return 1.f;
117 }
118 const size_t num_render_channels = render[0].size();
119
120 if (narrow_peak_band &&
121 (*narrow_peak_band > static_cast<int>(kFftLengthBy2Plus1 - 10))) {
122 return 0.001f;
123 }
124
125 constexpr size_t kLowBandGainLimit = kFftLengthBy2 / 2;
126 const float gain_below_8_khz = *std::min_element(
127 low_band_gain.begin() + kLowBandGainLimit, low_band_gain.end());
128
129 // Always attenuate the upper bands when there is saturated echo.
130 if (saturated_echo) {
131 return std::min(0.001f, gain_below_8_khz);
132 }
133
134 // Compute the upper and lower band energies.
135 const auto sum_of_squares = [](float a, float b) { return a + b * b; };
136 float low_band_energy = 0.f;
137 for (size_t ch = 0; ch < num_render_channels; ++ch) {
138 const float channel_energy = std::accumulate(
139 render[0][0].begin(), render[0][0].end(), 0.f, sum_of_squares);
140 low_band_energy = std::max(low_band_energy, channel_energy);
141 }
142 float high_band_energy = 0.f;
143 for (size_t k = 1; k < render.size(); ++k) {
144 for (size_t ch = 0; ch < num_render_channels; ++ch) {
145 const float energy = std::accumulate(
146 render[k][ch].begin(), render[k][ch].end(), 0.f, sum_of_squares);
147 high_band_energy = std::max(high_band_energy, energy);
148 }
149 }
150
151 // If there is more power in the lower frequencies than the upper frequencies,
152 // or if the power in upper frequencies is low, do not bound the gain in the
153 // upper bands.
154 float anti_howling_gain;
155 const float activation_threshold =
156 kBlockSize * config_.suppressor.high_bands_suppression
157 .anti_howling_activation_threshold;
158 if (high_band_energy < std::max(low_band_energy, activation_threshold)) {
159 anti_howling_gain = 1.f;
160 } else {
161 // In all other cases, bound the gain for upper frequencies.
162 RTC_DCHECK_LE(low_band_energy, high_band_energy);
163 RTC_DCHECK_NE(0.f, high_band_energy);
164 anti_howling_gain =
165 config_.suppressor.high_bands_suppression.anti_howling_gain *
166 sqrtf(low_band_energy / high_band_energy);
167 }
168
169 float gain_bound = 1.f;
170 if (!dominant_nearend_detector_->IsNearendState()) {
171 // Bound the upper gain during significant echo activity.
172 const auto& cfg = config_.suppressor.high_bands_suppression;
173 auto low_frequency_energy = [](rtc::ArrayView<const float> spectrum) {
174 RTC_DCHECK_LE(16, spectrum.size());
175 return std::accumulate(spectrum.begin() + 1, spectrum.begin() + 16, 0.f);
176 };
177 for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
178 const float echo_sum = low_frequency_energy(echo_spectrum[ch]);
179 const float noise_sum = low_frequency_energy(comfort_noise_spectrum[ch]);
180 if (echo_sum > cfg.enr_threshold * noise_sum) {
181 gain_bound = cfg.max_gain_during_echo;
182 break;
183 }
184 }
185 }
186
187 // Choose the gain as the minimum of the lower and upper gains.
188 return std::min(std::min(gain_below_8_khz, anti_howling_gain), gain_bound);
189 }
190
191 // Computes the gain to reduce the echo to a non audible level.
192 void SuppressionGain::GainToNoAudibleEcho(
193 const std::array<float, kFftLengthBy2Plus1>& nearend,
194 const std::array<float, kFftLengthBy2Plus1>& echo,
195 const std::array<float, kFftLengthBy2Plus1>& masker,
196 std::array<float, kFftLengthBy2Plus1>* gain) const {
197 const auto& p = dominant_nearend_detector_->IsNearendState() ? nearend_params_
198 : normal_params_;
199 for (size_t k = 0; k < gain->size(); ++k) {
200 float enr = echo[k] / (nearend[k] + 1.f); // Echo-to-nearend ratio.
201 float emr = echo[k] / (masker[k] + 1.f); // Echo-to-masker (noise) ratio.
202 float g = 1.0f;
203 if (enr > p.enr_transparent_[k] && emr > p.emr_transparent_[k]) {
204 g = (p.enr_suppress_[k] - enr) /
205 (p.enr_suppress_[k] - p.enr_transparent_[k]);
206 g = std::max(g, p.emr_transparent_[k] / emr);
207 }
208 (*gain)[k] = g;
209 }
210 }
211
212 // Compute the minimum gain as the attenuating gain to put the signal just
213 // above the zero sample values.
214 void SuppressionGain::GetMinGain(
215 rtc::ArrayView<const float> weighted_residual_echo,
216 rtc::ArrayView<const float> last_nearend,
217 rtc::ArrayView<const float> last_echo,
218 bool low_noise_render,
219 bool saturated_echo,
220 rtc::ArrayView<float> min_gain) const {
221 if (!saturated_echo) {
222 const float min_echo_power =
223 low_noise_render ? config_.echo_audibility.low_render_limit
224 : config_.echo_audibility.normal_render_limit;
225
226 for (size_t k = 0; k < min_gain.size(); ++k) {
227 min_gain[k] = weighted_residual_echo[k] > 0.f
228 ? min_echo_power / weighted_residual_echo[k]
229 : 1.f;
230 min_gain[k] = std::min(min_gain[k], 1.f);
231 }
232
233 const bool is_nearend_state = dominant_nearend_detector_->IsNearendState();
234 for (size_t k = 0; k < 6; ++k) {
235 const auto& dec = is_nearend_state ? nearend_params_.max_dec_factor_lf
236 : normal_params_.max_dec_factor_lf;
237
238 // Make sure the gains of the low frequencies do not decrease too
239 // quickly after strong nearend.
240 if (last_nearend[k] > last_echo[k]) {
241 min_gain[k] = std::max(min_gain[k], last_gain_[k] * dec);
242 min_gain[k] = std::min(min_gain[k], 1.f);
243 }
244 }
245 } else {
246 std::fill(min_gain.begin(), min_gain.end(), 0.f);
247 }
248 }
249
250 // Compute the maximum gain by limiting the gain increase from the previous
251 // gain.
252 void SuppressionGain::GetMaxGain(rtc::ArrayView<float> max_gain) const {
253 const auto& inc = dominant_nearend_detector_->IsNearendState()
254 ? nearend_params_.max_inc_factor
255 : normal_params_.max_inc_factor;
256 const auto& floor = config_.suppressor.floor_first_increase;
257 for (size_t k = 0; k < max_gain.size(); ++k) {
258 max_gain[k] = std::min(std::max(last_gain_[k] * inc, floor), 1.f);
259 }
260 }
261
262 void SuppressionGain::LowerBandGain(
263 bool low_noise_render,
264 const AecState& aec_state,
265 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
266 suppressor_input,
267 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>> residual_echo,
268 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>> comfort_noise,
269 bool clock_drift,
270 std::array<float, kFftLengthBy2Plus1>* gain) {
271 gain->fill(1.f);
272 const bool saturated_echo = aec_state.SaturatedEcho();
273 std::array<float, kFftLengthBy2Plus1> max_gain;
274 GetMaxGain(max_gain);
275
276 for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
277 std::array<float, kFftLengthBy2Plus1> G;
278 std::array<float, kFftLengthBy2Plus1> nearend;
279 nearend_smoothers_[ch].Average(suppressor_input[ch], nearend);
280
281 // Weight echo power in terms of audibility.
282 std::array<float, kFftLengthBy2Plus1> weighted_residual_echo;
283 WeightEchoForAudibility(config_, residual_echo[ch], weighted_residual_echo);
284
285 std::array<float, kFftLengthBy2Plus1> min_gain;
286 GetMinGain(weighted_residual_echo, last_nearend_[ch], last_echo_[ch],
287 low_noise_render, saturated_echo, min_gain);
288
289 GainToNoAudibleEcho(nearend, weighted_residual_echo, comfort_noise[0], &G);
290
291 // Clamp gains.
292 for (size_t k = 0; k < gain->size(); ++k) {
293 G[k] = std::max(std::min(G[k], max_gain[k]), min_gain[k]);
294 (*gain)[k] = std::min((*gain)[k], G[k]);
295 }
296
297 // Store data required for the gain computation of the next block.
298 std::copy(nearend.begin(), nearend.end(), last_nearend_[ch].begin());
299 std::copy(weighted_residual_echo.begin(), weighted_residual_echo.end(),
300 last_echo_[ch].begin());
301 }
302
303 LimitLowFrequencyGains(gain);
304 // Use conservative high-frequency gains during clock-drift or when not in
305 // dominant nearend.
306 if (!dominant_nearend_detector_->IsNearendState() || clock_drift ||
307 config_.suppressor.conservative_hf_suppression) {
308 LimitHighFrequencyGains(config_.suppressor.conservative_hf_suppression,
309 gain);
310 }
311
312 // Store computed gains.
313 std::copy(gain->begin(), gain->end(), last_gain_.begin());
314
315 // Transform gains to amplitude domain.
316 aec3::VectorMath(optimization_).Sqrt(*gain);
317 }
318
319 SuppressionGain::SuppressionGain(const EchoCanceller3Config& config,
320 Aec3Optimization optimization,
321 int sample_rate_hz,
322 size_t num_capture_channels)
323 : data_dumper_(
324 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
325 optimization_(optimization),
326 config_(config),
327 num_capture_channels_(num_capture_channels),
328 state_change_duration_blocks_(
329 static_cast<int>(config_.filter.config_change_duration_blocks)),
330 last_nearend_(num_capture_channels_, {0}),
331 last_echo_(num_capture_channels_, {0}),
332 nearend_smoothers_(
333 num_capture_channels_,
334 aec3::MovingAverage(kFftLengthBy2Plus1,
335 config.suppressor.nearend_average_blocks)),
336 nearend_params_(config_.suppressor.nearend_tuning),
337 normal_params_(config_.suppressor.normal_tuning) {
338 RTC_DCHECK_LT(0, state_change_duration_blocks_);
339 last_gain_.fill(1.f);
340 if (config_.suppressor.use_subband_nearend_detection) {
341 dominant_nearend_detector_ = std::make_unique<SubbandNearendDetector>(
342 config_.suppressor.subband_nearend_detection, num_capture_channels_);
343 } else {
344 dominant_nearend_detector_ = std::make_unique<DominantNearendDetector>(
345 config_.suppressor.dominant_nearend_detection, num_capture_channels_);
346 }
347 RTC_DCHECK(dominant_nearend_detector_);
348 }
349
350 SuppressionGain::~SuppressionGain() = default;
351
352 void SuppressionGain::GetGain(
353 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
354 nearend_spectrum,
355 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>> echo_spectrum,
356 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
357 residual_echo_spectrum,
358 rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
359 comfort_noise_spectrum,
360 const RenderSignalAnalyzer& render_signal_analyzer,
361 const AecState& aec_state,
362 const std::vector<std::vector<std::vector<float>>>& render,
363 bool clock_drift,
364 float* high_bands_gain,
365 std::array<float, kFftLengthBy2Plus1>* low_band_gain) {
366 RTC_DCHECK(high_bands_gain);
367 RTC_DCHECK(low_band_gain);
368
369 // Update the nearend state selection.
370 dominant_nearend_detector_->Update(nearend_spectrum, residual_echo_spectrum,
371 comfort_noise_spectrum, initial_state_);
372
373 // Compute gain for the lower band.
374 bool low_noise_render = low_render_detector_.Detect(render);
375 LowerBandGain(low_noise_render, aec_state, nearend_spectrum,
376 residual_echo_spectrum, comfort_noise_spectrum, clock_drift,
377 low_band_gain);
378
379 // Compute the gain for the upper bands.
380 const absl::optional<int> narrow_peak_band =
381 render_signal_analyzer.NarrowPeakBand();
382
383 *high_bands_gain =
384 UpperBandsGain(echo_spectrum, comfort_noise_spectrum, narrow_peak_band,
385 aec_state.SaturatedEcho(), render, *low_band_gain);
386 }
387
388 void SuppressionGain::SetInitialState(bool state) {
389 initial_state_ = state;
390 if (state) {
391 initial_state_change_counter_ = state_change_duration_blocks_;
392 } else {
393 initial_state_change_counter_ = 0;
394 }
395 }
396
397 // Detects when the render signal can be considered to have low power and
398 // consist of stationary noise.
399 bool SuppressionGain::LowNoiseRenderDetector::Detect(
400 const std::vector<std::vector<std::vector<float>>>& render) {
401 float x2_sum = 0.f;
402 float x2_max = 0.f;
403 for (const auto& x_ch : render[0]) {
404 for (const auto& x_k : x_ch) {
405 const float x2 = x_k * x_k;
406 x2_sum += x2;
407 x2_max = std::max(x2_max, x2);
408 }
409 }
410 const size_t num_render_channels = render[0].size();
411 x2_sum = x2_sum / num_render_channels;
412 ;
413
414 constexpr float kThreshold = 50.f * 50.f * 64.f;
415 const bool low_noise_render =
416 average_power_ < kThreshold && x2_max < 3 * average_power_;
417 average_power_ = average_power_ * 0.9f + x2_sum * 0.1f;
418 return low_noise_render;
419 }
420
421 SuppressionGain::GainParameters::GainParameters(
422 const EchoCanceller3Config::Suppressor::Tuning& tuning)
423 : max_inc_factor(tuning.max_inc_factor),
424 max_dec_factor_lf(tuning.max_dec_factor_lf) {
425 // Compute per-band masking thresholds.
426 constexpr size_t kLastLfBand = 5;
427 constexpr size_t kFirstHfBand = 8;
428 RTC_DCHECK_LT(kLastLfBand, kFirstHfBand);
429 auto& lf = tuning.mask_lf;
430 auto& hf = tuning.mask_hf;
431 RTC_DCHECK_LT(lf.enr_transparent, lf.enr_suppress);
432 RTC_DCHECK_LT(hf.enr_transparent, hf.enr_suppress);
433 for (size_t k = 0; k < kFftLengthBy2Plus1; k++) {
434 float a;
435 if (k <= kLastLfBand) {
436 a = 0.f;
437 } else if (k < kFirstHfBand) {
438 a = (k - kLastLfBand) / static_cast<float>(kFirstHfBand - kLastLfBand);
439 } else {
440 a = 1.f;
441 }
442 enr_transparent_[k] = (1 - a) * lf.enr_transparent + a * hf.enr_transparent;
443 enr_suppress_[k] = (1 - a) * lf.enr_suppress + a * hf.enr_suppress;
444 emr_transparent_[k] = (1 - a) * lf.emr_transparent + a * hf.emr_transparent;
445 }
446 }
447
448 } // namespace webrtc