xref: /aosp_15_r20/external/webrtc/modules/audio_processing/aec3/suppression_gain.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
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/checks.h"
25 #include "system_wrappers/include/field_trial.h"
26 
27 namespace webrtc {
28 namespace {
29 
LimitLowFrequencyGains(std::array<float,kFftLengthBy2Plus1> * gain)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 
LimitHighFrequencyGains(bool conservative_hf_suppression,std::array<float,kFftLengthBy2Plus1> * gain)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.
WeightEchoForAudibility(const EchoCanceller3Config & config,rtc::ArrayView<const float> echo,rtc::ArrayView<float> weighted_echo)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 std::atomic<int> SuppressionGain::instance_count_(0);
105 
UpperBandsGain(rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> echo_spectrum,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> comfort_noise_spectrum,const absl::optional<int> & narrow_peak_band,bool saturated_echo,const Block & render,const std::array<float,kFftLengthBy2Plus1> & low_band_gain) const106 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 Block& render,
113     const std::array<float, kFftLengthBy2Plus1>& low_band_gain) const {
114   RTC_DCHECK_LT(0, render.NumBands());
115   if (render.NumBands() == 1) {
116     return 1.f;
117   }
118   const int num_render_channels = render.NumChannels();
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 (int ch = 0; ch < num_render_channels; ++ch) {
138     const float channel_energy =
139         std::accumulate(render.begin(/*band=*/0, ch),
140                         render.end(/*band=*/0, ch), 0.0f, sum_of_squares);
141     low_band_energy = std::max(low_band_energy, channel_energy);
142   }
143   float high_band_energy = 0.f;
144   for (int k = 1; k < render.NumBands(); ++k) {
145     for (int ch = 0; ch < num_render_channels; ++ch) {
146       const float energy = std::accumulate(
147           render.begin(k, ch), render.end(k, ch), 0.f, sum_of_squares);
148       high_band_energy = std::max(high_band_energy, energy);
149     }
150   }
151 
152   // If there is more power in the lower frequencies than the upper frequencies,
153   // or if the power in upper frequencies is low, do not bound the gain in the
154   // upper bands.
155   float anti_howling_gain;
156   const float activation_threshold =
157       kBlockSize * config_.suppressor.high_bands_suppression
158                        .anti_howling_activation_threshold;
159   if (high_band_energy < std::max(low_band_energy, activation_threshold)) {
160     anti_howling_gain = 1.f;
161   } else {
162     // In all other cases, bound the gain for upper frequencies.
163     RTC_DCHECK_LE(low_band_energy, high_band_energy);
164     RTC_DCHECK_NE(0.f, high_band_energy);
165     anti_howling_gain =
166         config_.suppressor.high_bands_suppression.anti_howling_gain *
167         sqrtf(low_band_energy / high_band_energy);
168   }
169 
170   float gain_bound = 1.f;
171   if (!dominant_nearend_detector_->IsNearendState()) {
172     // Bound the upper gain during significant echo activity.
173     const auto& cfg = config_.suppressor.high_bands_suppression;
174     auto low_frequency_energy = [](rtc::ArrayView<const float> spectrum) {
175       RTC_DCHECK_LE(16, spectrum.size());
176       return std::accumulate(spectrum.begin() + 1, spectrum.begin() + 16, 0.f);
177     };
178     for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
179       const float echo_sum = low_frequency_energy(echo_spectrum[ch]);
180       const float noise_sum = low_frequency_energy(comfort_noise_spectrum[ch]);
181       if (echo_sum > cfg.enr_threshold * noise_sum) {
182         gain_bound = cfg.max_gain_during_echo;
183         break;
184       }
185     }
186   }
187 
188   // Choose the gain as the minimum of the lower and upper gains.
189   return std::min(std::min(gain_below_8_khz, anti_howling_gain), gain_bound);
190 }
191 
192 // Computes the gain to reduce the echo to a non audible level.
GainToNoAudibleEcho(const std::array<float,kFftLengthBy2Plus1> & nearend,const std::array<float,kFftLengthBy2Plus1> & echo,const std::array<float,kFftLengthBy2Plus1> & masker,std::array<float,kFftLengthBy2Plus1> * gain) const193 void SuppressionGain::GainToNoAudibleEcho(
194     const std::array<float, kFftLengthBy2Plus1>& nearend,
195     const std::array<float, kFftLengthBy2Plus1>& echo,
196     const std::array<float, kFftLengthBy2Plus1>& masker,
197     std::array<float, kFftLengthBy2Plus1>* gain) const {
198   const auto& p = dominant_nearend_detector_->IsNearendState() ? nearend_params_
199                                                                : normal_params_;
200   for (size_t k = 0; k < gain->size(); ++k) {
201     float enr = echo[k] / (nearend[k] + 1.f);  // Echo-to-nearend ratio.
202     float emr = echo[k] / (masker[k] + 1.f);   // Echo-to-masker (noise) ratio.
203     float g = 1.0f;
204     if (enr > p.enr_transparent_[k] && emr > p.emr_transparent_[k]) {
205       g = (p.enr_suppress_[k] - enr) /
206           (p.enr_suppress_[k] - p.enr_transparent_[k]);
207       g = std::max(g, p.emr_transparent_[k] / emr);
208     }
209     (*gain)[k] = g;
210   }
211 }
212 
213 // Compute the minimum gain as the attenuating gain to put the signal just
214 // above the zero sample values.
GetMinGain(rtc::ArrayView<const float> weighted_residual_echo,rtc::ArrayView<const float> last_nearend,rtc::ArrayView<const float> last_echo,bool low_noise_render,bool saturated_echo,rtc::ArrayView<float> min_gain) const215 void SuppressionGain::GetMinGain(
216     rtc::ArrayView<const float> weighted_residual_echo,
217     rtc::ArrayView<const float> last_nearend,
218     rtc::ArrayView<const float> last_echo,
219     bool low_noise_render,
220     bool saturated_echo,
221     rtc::ArrayView<float> min_gain) const {
222   if (!saturated_echo) {
223     const float min_echo_power =
224         low_noise_render ? config_.echo_audibility.low_render_limit
225                          : config_.echo_audibility.normal_render_limit;
226 
227     for (size_t k = 0; k < min_gain.size(); ++k) {
228       min_gain[k] = weighted_residual_echo[k] > 0.f
229                         ? min_echo_power / weighted_residual_echo[k]
230                         : 1.f;
231       min_gain[k] = std::min(min_gain[k], 1.f);
232     }
233 
234     if (!initial_state_ ||
235         config_.suppressor.lf_smoothing_during_initial_phase) {
236       const float& dec = dominant_nearend_detector_->IsNearendState()
237                              ? nearend_params_.max_dec_factor_lf
238                              : normal_params_.max_dec_factor_lf;
239 
240       for (int k = 0; k <= config_.suppressor.last_lf_smoothing_band; ++k) {
241         // Make sure the gains of the low frequencies do not decrease too
242         // quickly after strong nearend.
243         if (last_nearend[k] > last_echo[k] ||
244             k <= config_.suppressor.last_permanent_lf_smoothing_band) {
245           min_gain[k] = std::max(min_gain[k], last_gain_[k] * dec);
246           min_gain[k] = std::min(min_gain[k], 1.f);
247         }
248       }
249     }
250   } else {
251     std::fill(min_gain.begin(), min_gain.end(), 0.f);
252   }
253 }
254 
255 // Compute the maximum gain by limiting the gain increase from the previous
256 // gain.
GetMaxGain(rtc::ArrayView<float> max_gain) const257 void SuppressionGain::GetMaxGain(rtc::ArrayView<float> max_gain) const {
258   const auto& inc = dominant_nearend_detector_->IsNearendState()
259                         ? nearend_params_.max_inc_factor
260                         : normal_params_.max_inc_factor;
261   const auto& floor = config_.suppressor.floor_first_increase;
262   for (size_t k = 0; k < max_gain.size(); ++k) {
263     max_gain[k] = std::min(std::max(last_gain_[k] * inc, floor), 1.f);
264   }
265 }
266 
LowerBandGain(bool low_noise_render,const AecState & aec_state,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> suppressor_input,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> residual_echo,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> comfort_noise,bool clock_drift,std::array<float,kFftLengthBy2Plus1> * gain)267 void SuppressionGain::LowerBandGain(
268     bool low_noise_render,
269     const AecState& aec_state,
270     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
271         suppressor_input,
272     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>> residual_echo,
273     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>> comfort_noise,
274     bool clock_drift,
275     std::array<float, kFftLengthBy2Plus1>* gain) {
276   gain->fill(1.f);
277   const bool saturated_echo = aec_state.SaturatedEcho();
278   std::array<float, kFftLengthBy2Plus1> max_gain;
279   GetMaxGain(max_gain);
280 
281   for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
282     std::array<float, kFftLengthBy2Plus1> G;
283     std::array<float, kFftLengthBy2Plus1> nearend;
284     nearend_smoothers_[ch].Average(suppressor_input[ch], nearend);
285 
286     // Weight echo power in terms of audibility.
287     std::array<float, kFftLengthBy2Plus1> weighted_residual_echo;
288     WeightEchoForAudibility(config_, residual_echo[ch], weighted_residual_echo);
289 
290     std::array<float, kFftLengthBy2Plus1> min_gain;
291     GetMinGain(weighted_residual_echo, last_nearend_[ch], last_echo_[ch],
292                low_noise_render, saturated_echo, min_gain);
293 
294     GainToNoAudibleEcho(nearend, weighted_residual_echo, comfort_noise[0], &G);
295 
296     // Clamp gains.
297     for (size_t k = 0; k < gain->size(); ++k) {
298       G[k] = std::max(std::min(G[k], max_gain[k]), min_gain[k]);
299       (*gain)[k] = std::min((*gain)[k], G[k]);
300     }
301 
302     // Store data required for the gain computation of the next block.
303     std::copy(nearend.begin(), nearend.end(), last_nearend_[ch].begin());
304     std::copy(weighted_residual_echo.begin(), weighted_residual_echo.end(),
305               last_echo_[ch].begin());
306   }
307 
308   LimitLowFrequencyGains(gain);
309   // Use conservative high-frequency gains during clock-drift or when not in
310   // dominant nearend.
311   if (!dominant_nearend_detector_->IsNearendState() || clock_drift ||
312       config_.suppressor.conservative_hf_suppression) {
313     LimitHighFrequencyGains(config_.suppressor.conservative_hf_suppression,
314                             gain);
315   }
316 
317   // Store computed gains.
318   std::copy(gain->begin(), gain->end(), last_gain_.begin());
319 
320   // Transform gains to amplitude domain.
321   aec3::VectorMath(optimization_).Sqrt(*gain);
322 }
323 
SuppressionGain(const EchoCanceller3Config & config,Aec3Optimization optimization,int sample_rate_hz,size_t num_capture_channels)324 SuppressionGain::SuppressionGain(const EchoCanceller3Config& config,
325                                  Aec3Optimization optimization,
326                                  int sample_rate_hz,
327                                  size_t num_capture_channels)
328     : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
329       optimization_(optimization),
330       config_(config),
331       num_capture_channels_(num_capture_channels),
332       state_change_duration_blocks_(
333           static_cast<int>(config_.filter.config_change_duration_blocks)),
334       last_nearend_(num_capture_channels_, {0}),
335       last_echo_(num_capture_channels_, {0}),
336       nearend_smoothers_(
337           num_capture_channels_,
338           aec3::MovingAverage(kFftLengthBy2Plus1,
339                               config.suppressor.nearend_average_blocks)),
340       nearend_params_(config_.suppressor.last_lf_band,
341                       config_.suppressor.first_hf_band,
342                       config_.suppressor.nearend_tuning),
343       normal_params_(config_.suppressor.last_lf_band,
344                      config_.suppressor.first_hf_band,
345                      config_.suppressor.normal_tuning),
346       use_unbounded_echo_spectrum_(config.suppressor.dominant_nearend_detection
347                                        .use_unbounded_echo_spectrum) {
348   RTC_DCHECK_LT(0, state_change_duration_blocks_);
349   last_gain_.fill(1.f);
350   if (config_.suppressor.use_subband_nearend_detection) {
351     dominant_nearend_detector_ = std::make_unique<SubbandNearendDetector>(
352         config_.suppressor.subband_nearend_detection, num_capture_channels_);
353   } else {
354     dominant_nearend_detector_ = std::make_unique<DominantNearendDetector>(
355         config_.suppressor.dominant_nearend_detection, num_capture_channels_);
356   }
357   RTC_DCHECK(dominant_nearend_detector_);
358 }
359 
360 SuppressionGain::~SuppressionGain() = default;
361 
GetGain(rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> nearend_spectrum,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> echo_spectrum,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> residual_echo_spectrum,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> residual_echo_spectrum_unbounded,rtc::ArrayView<const std::array<float,kFftLengthBy2Plus1>> comfort_noise_spectrum,const RenderSignalAnalyzer & render_signal_analyzer,const AecState & aec_state,const Block & render,bool clock_drift,float * high_bands_gain,std::array<float,kFftLengthBy2Plus1> * low_band_gain)362 void SuppressionGain::GetGain(
363     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
364         nearend_spectrum,
365     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>> echo_spectrum,
366     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
367         residual_echo_spectrum,
368     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
369         residual_echo_spectrum_unbounded,
370     rtc::ArrayView<const std::array<float, kFftLengthBy2Plus1>>
371         comfort_noise_spectrum,
372     const RenderSignalAnalyzer& render_signal_analyzer,
373     const AecState& aec_state,
374     const Block& render,
375     bool clock_drift,
376     float* high_bands_gain,
377     std::array<float, kFftLengthBy2Plus1>* low_band_gain) {
378   RTC_DCHECK(high_bands_gain);
379   RTC_DCHECK(low_band_gain);
380 
381   // Choose residual echo spectrum for dominant nearend detection.
382   const auto echo = use_unbounded_echo_spectrum_
383                         ? residual_echo_spectrum_unbounded
384                         : residual_echo_spectrum;
385 
386   // Update the nearend state selection.
387   dominant_nearend_detector_->Update(nearend_spectrum, echo,
388                                      comfort_noise_spectrum, initial_state_);
389 
390   // Compute gain for the lower band.
391   bool low_noise_render = low_render_detector_.Detect(render);
392   LowerBandGain(low_noise_render, aec_state, nearend_spectrum,
393                 residual_echo_spectrum, comfort_noise_spectrum, clock_drift,
394                 low_band_gain);
395 
396   // Compute the gain for the upper bands.
397   const absl::optional<int> narrow_peak_band =
398       render_signal_analyzer.NarrowPeakBand();
399 
400   *high_bands_gain =
401       UpperBandsGain(echo_spectrum, comfort_noise_spectrum, narrow_peak_band,
402                      aec_state.SaturatedEcho(), render, *low_band_gain);
403 
404   data_dumper_->DumpRaw("aec3_dominant_nearend",
405                         dominant_nearend_detector_->IsNearendState());
406 }
407 
SetInitialState(bool state)408 void 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 
417 // Detects when the render signal can be considered to have low power and
418 // consist of stationary noise.
Detect(const Block & render)419 bool SuppressionGain::LowNoiseRenderDetector::Detect(const Block& render) {
420   float x2_sum = 0.f;
421   float x2_max = 0.f;
422   for (int ch = 0; ch < render.NumChannels(); ++ch) {
423     for (float x_k : render.View(/*band=*/0, ch)) {
424       const float x2 = x_k * x_k;
425       x2_sum += x2;
426       x2_max = std::max(x2_max, x2);
427     }
428   }
429   x2_sum = x2_sum / render.NumChannels();
430 
431   constexpr float kThreshold = 50.f * 50.f * 64.f;
432   const bool low_noise_render =
433       average_power_ < kThreshold && x2_max < 3 * average_power_;
434   average_power_ = average_power_ * 0.9f + x2_sum * 0.1f;
435   return low_noise_render;
436 }
437 
GainParameters(int last_lf_band,int first_hf_band,const EchoCanceller3Config::Suppressor::Tuning & tuning)438 SuppressionGain::GainParameters::GainParameters(
439     int last_lf_band,
440     int first_hf_band,
441     const EchoCanceller3Config::Suppressor::Tuning& tuning)
442     : max_inc_factor(tuning.max_inc_factor),
443       max_dec_factor_lf(tuning.max_dec_factor_lf) {
444   // Compute per-band masking thresholds.
445   RTC_DCHECK_LT(last_lf_band, first_hf_band);
446   auto& lf = tuning.mask_lf;
447   auto& hf = tuning.mask_hf;
448   RTC_DCHECK_LT(lf.enr_transparent, lf.enr_suppress);
449   RTC_DCHECK_LT(hf.enr_transparent, hf.enr_suppress);
450   for (int k = 0; k < static_cast<int>(kFftLengthBy2Plus1); k++) {
451     float a;
452     if (k <= last_lf_band) {
453       a = 0.f;
454     } else if (k < first_hf_band) {
455       a = (k - last_lf_band) / static_cast<float>(first_hf_band - last_lf_band);
456     } else {
457       a = 1.f;
458     }
459     enr_transparent_[k] = (1 - a) * lf.enr_transparent + a * hf.enr_transparent;
460     enr_suppress_[k] = (1 - a) * lf.enr_suppress + a * hf.enr_suppress;
461     emr_transparent_[k] = (1 - a) * lf.emr_transparent + a * hf.emr_transparent;
462   }
463 }
464 
465 }  // namespace webrtc
466