xref: /aosp_15_r20/external/webrtc/modules/audio_processing/agc/agc_manager_direct.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2013 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/agc/agc_manager_direct.h"
12 
13 #include <algorithm>
14 #include <cmath>
15 
16 #include "api/array_view.h"
17 #include "common_audio/include/audio_util.h"
18 #include "modules/audio_processing/agc/gain_control.h"
19 #include "modules/audio_processing/agc2/gain_map_internal.h"
20 #include "modules/audio_processing/include/audio_frame_view.h"
21 #include "rtc_base/checks.h"
22 #include "rtc_base/logging.h"
23 #include "rtc_base/numerics/safe_minmax.h"
24 #include "system_wrappers/include/field_trial.h"
25 #include "system_wrappers/include/metrics.h"
26 
27 namespace webrtc {
28 
29 namespace {
30 
31 // Amount of error we tolerate in the microphone level (presumably due to OS
32 // quantization) before we assume the user has manually adjusted the microphone.
33 constexpr int kLevelQuantizationSlack = 25;
34 
35 constexpr int kDefaultCompressionGain = 7;
36 constexpr int kMaxCompressionGain = 12;
37 constexpr int kMinCompressionGain = 2;
38 // Controls the rate of compression changes towards the target.
39 constexpr float kCompressionGainStep = 0.05f;
40 
41 constexpr int kMaxMicLevel = 255;
42 static_assert(kGainMapSize > kMaxMicLevel, "gain map too small");
43 constexpr int kMinMicLevel = 12;
44 
45 // Prevent very large microphone level changes.
46 constexpr int kMaxResidualGainChange = 15;
47 
48 // Maximum additional gain allowed to compensate for microphone level
49 // restrictions from clipping events.
50 constexpr int kSurplusCompressionGain = 6;
51 
52 // Target speech level (dBFs) and speech probability threshold used to compute
53 // the RMS error override in `GetSpeechLevelErrorDb()`. These are only used for
54 // computing the error override and they are not passed to `agc_`.
55 // TODO(webrtc:7494): Move these to a config and pass in the ctor.
56 constexpr float kOverrideTargetSpeechLevelDbfs = -18.0f;
57 constexpr float kOverrideSpeechProbabilitySilenceThreshold = 0.5f;
58 // The minimum number of frames between `UpdateGain()` calls.
59 // TODO(webrtc:7494): Move this to a config and pass in the ctor with
60 // kOverrideWaitFrames = 100. Default value zero needed for the unit tests.
61 constexpr int kOverrideWaitFrames = 0;
62 
63 using AnalogAgcConfig =
64     AudioProcessing::Config::GainController1::AnalogGainController;
65 
66 // If the "WebRTC-Audio-2ndAgcMinMicLevelExperiment" field trial is specified,
67 // parses it and returns a value between 0 and 255 depending on the field-trial
68 // string. Returns an unspecified value if the field trial is not specified, if
69 // disabled or if it cannot be parsed. Example:
70 // 'WebRTC-Audio-2ndAgcMinMicLevelExperiment/Enabled-80' => returns 80.
GetMinMicLevelOverride()71 absl::optional<int> GetMinMicLevelOverride() {
72   constexpr char kMinMicLevelFieldTrial[] =
73       "WebRTC-Audio-2ndAgcMinMicLevelExperiment";
74   if (!webrtc::field_trial::IsEnabled(kMinMicLevelFieldTrial)) {
75     return absl::nullopt;
76   }
77   const auto field_trial_string =
78       webrtc::field_trial::FindFullName(kMinMicLevelFieldTrial);
79   int min_mic_level = -1;
80   sscanf(field_trial_string.c_str(), "Enabled-%d", &min_mic_level);
81   if (min_mic_level >= 0 && min_mic_level <= 255) {
82     return min_mic_level;
83   } else {
84     RTC_LOG(LS_WARNING) << "[agc] Invalid parameter for "
85                         << kMinMicLevelFieldTrial << ", ignored.";
86     return absl::nullopt;
87   }
88 }
89 
LevelFromGainError(int gain_error,int level,int min_mic_level)90 int LevelFromGainError(int gain_error, int level, int min_mic_level) {
91   RTC_DCHECK_GE(level, 0);
92   RTC_DCHECK_LE(level, kMaxMicLevel);
93   if (gain_error == 0) {
94     return level;
95   }
96 
97   int new_level = level;
98   if (gain_error > 0) {
99     while (kGainMap[new_level] - kGainMap[level] < gain_error &&
100            new_level < kMaxMicLevel) {
101       ++new_level;
102     }
103   } else {
104     while (kGainMap[new_level] - kGainMap[level] > gain_error &&
105            new_level > min_mic_level) {
106       --new_level;
107     }
108   }
109   return new_level;
110 }
111 
112 // Returns the proportion of samples in the buffer which are at full-scale
113 // (and presumably clipped).
ComputeClippedRatio(const float * const * audio,size_t num_channels,size_t samples_per_channel)114 float ComputeClippedRatio(const float* const* audio,
115                           size_t num_channels,
116                           size_t samples_per_channel) {
117   RTC_DCHECK_GT(samples_per_channel, 0);
118   int num_clipped = 0;
119   for (size_t ch = 0; ch < num_channels; ++ch) {
120     int num_clipped_in_ch = 0;
121     for (size_t i = 0; i < samples_per_channel; ++i) {
122       RTC_DCHECK(audio[ch]);
123       if (audio[ch][i] >= 32767.0f || audio[ch][i] <= -32768.0f) {
124         ++num_clipped_in_ch;
125       }
126     }
127     num_clipped = std::max(num_clipped, num_clipped_in_ch);
128   }
129   return static_cast<float>(num_clipped) / (samples_per_channel);
130 }
131 
LogClippingMetrics(int clipping_rate)132 void LogClippingMetrics(int clipping_rate) {
133   RTC_LOG(LS_INFO) << "Input clipping rate: " << clipping_rate << "%";
134   RTC_HISTOGRAM_COUNTS_LINEAR(/*name=*/"WebRTC.Audio.Agc.InputClippingRate",
135                               /*sample=*/clipping_rate, /*min=*/0, /*max=*/100,
136                               /*bucket_count=*/50);
137 }
138 
139 // Computes the speech level error in dB. `speech_level_dbfs` is required to be
140 // in the range [-90.0f, 30.0f] and `speech_probability` in the range
141 // [0.0f, 1.0f].
GetSpeechLevelErrorDb(float speech_level_dbfs,float speech_probability)142 int GetSpeechLevelErrorDb(float speech_level_dbfs, float speech_probability) {
143   constexpr float kMinSpeechLevelDbfs = -90.0f;
144   constexpr float kMaxSpeechLevelDbfs = 30.0f;
145   RTC_DCHECK_GE(speech_level_dbfs, kMinSpeechLevelDbfs);
146   RTC_DCHECK_LE(speech_level_dbfs, kMaxSpeechLevelDbfs);
147   RTC_DCHECK_GE(speech_probability, 0.0f);
148   RTC_DCHECK_LE(speech_probability, 1.0f);
149 
150   if (speech_probability < kOverrideSpeechProbabilitySilenceThreshold) {
151     return 0;
152   }
153 
154   const float speech_level = rtc::SafeClamp<float>(
155       speech_level_dbfs, kMinSpeechLevelDbfs, kMaxSpeechLevelDbfs);
156 
157   return std::round(kOverrideTargetSpeechLevelDbfs - speech_level);
158 }
159 
160 }  // namespace
161 
MonoAgc(ApmDataDumper * data_dumper,int clipped_level_min,bool disable_digital_adaptive,int min_mic_level)162 MonoAgc::MonoAgc(ApmDataDumper* data_dumper,
163                  int clipped_level_min,
164                  bool disable_digital_adaptive,
165                  int min_mic_level)
166     : min_mic_level_(min_mic_level),
167       disable_digital_adaptive_(disable_digital_adaptive),
168       agc_(std::make_unique<Agc>()),
169       max_level_(kMaxMicLevel),
170       max_compression_gain_(kMaxCompressionGain),
171       target_compression_(kDefaultCompressionGain),
172       compression_(target_compression_),
173       compression_accumulator_(compression_),
174       clipped_level_min_(clipped_level_min) {}
175 
176 MonoAgc::~MonoAgc() = default;
177 
Initialize()178 void MonoAgc::Initialize() {
179   max_level_ = kMaxMicLevel;
180   max_compression_gain_ = kMaxCompressionGain;
181   target_compression_ = disable_digital_adaptive_ ? 0 : kDefaultCompressionGain;
182   compression_ = disable_digital_adaptive_ ? 0 : target_compression_;
183   compression_accumulator_ = compression_;
184   capture_output_used_ = true;
185   check_volume_on_next_process_ = true;
186   frames_since_update_gain_ = 0;
187   is_first_frame_ = true;
188 }
189 
Process(rtc::ArrayView<const int16_t> audio,absl::optional<int> rms_error_override)190 void MonoAgc::Process(rtc::ArrayView<const int16_t> audio,
191                       absl::optional<int> rms_error_override) {
192   new_compression_to_set_ = absl::nullopt;
193 
194   if (check_volume_on_next_process_) {
195     check_volume_on_next_process_ = false;
196     // We have to wait until the first process call to check the volume,
197     // because Chromium doesn't guarantee it to be valid any earlier.
198     CheckVolumeAndReset();
199   }
200 
201   agc_->Process(audio);
202 
203   // Always check if `agc_` has a new error available. If yes, `agc_` gets
204   // reset.
205   // TODO(webrtc:7494) Replace the `agc_` call `GetRmsErrorDb()` with `Reset()`
206   // if an error override is used.
207   int rms_error = 0;
208   bool update_gain = agc_->GetRmsErrorDb(&rms_error);
209   if (rms_error_override.has_value()) {
210     if (is_first_frame_ || frames_since_update_gain_ < kOverrideWaitFrames) {
211       update_gain = false;
212     } else {
213       rms_error = *rms_error_override;
214       update_gain = true;
215     }
216   }
217 
218   if (update_gain) {
219     UpdateGain(rms_error);
220   }
221 
222   if (!disable_digital_adaptive_) {
223     UpdateCompressor();
224   }
225 
226   is_first_frame_ = false;
227   if (frames_since_update_gain_ < kOverrideWaitFrames) {
228     ++frames_since_update_gain_;
229   }
230 }
231 
HandleClipping(int clipped_level_step)232 void MonoAgc::HandleClipping(int clipped_level_step) {
233   RTC_DCHECK_GT(clipped_level_step, 0);
234   // Always decrease the maximum level, even if the current level is below
235   // threshold.
236   SetMaxLevel(std::max(clipped_level_min_, max_level_ - clipped_level_step));
237   if (log_to_histograms_) {
238     RTC_HISTOGRAM_BOOLEAN("WebRTC.Audio.AgcClippingAdjustmentAllowed",
239                           level_ - clipped_level_step >= clipped_level_min_);
240   }
241   if (level_ > clipped_level_min_) {
242     // Don't try to adjust the level if we're already below the limit. As
243     // a consequence, if the user has brought the level above the limit, we
244     // will still not react until the postproc updates the level.
245     SetLevel(std::max(clipped_level_min_, level_ - clipped_level_step));
246     // Reset the AGCs for all channels since the level has changed.
247     agc_->Reset();
248     frames_since_update_gain_ = 0;
249     is_first_frame_ = false;
250   }
251 }
252 
SetLevel(int new_level)253 void MonoAgc::SetLevel(int new_level) {
254   int voe_level = recommended_input_volume_;
255   if (voe_level == 0) {
256     RTC_DLOG(LS_INFO)
257         << "[agc] VolumeCallbacks returned level=0, taking no action.";
258     return;
259   }
260   if (voe_level < 0 || voe_level > kMaxMicLevel) {
261     RTC_LOG(LS_ERROR) << "VolumeCallbacks returned an invalid level="
262                       << voe_level;
263     return;
264   }
265 
266   // Detect manual input volume adjustments by checking if the current level
267   // `voe_level` is outside of the `[level_ - kLevelQuantizationSlack, level_ +
268   // kLevelQuantizationSlack]` range where `level_` is the last input volume
269   // known by this gain controller.
270   if (voe_level > level_ + kLevelQuantizationSlack ||
271       voe_level < level_ - kLevelQuantizationSlack) {
272     RTC_DLOG(LS_INFO) << "[agc] Mic volume was manually adjusted. Updating "
273                          "stored level from "
274                       << level_ << " to " << voe_level;
275     level_ = voe_level;
276     // Always allow the user to increase the volume.
277     if (level_ > max_level_) {
278       SetMaxLevel(level_);
279     }
280     // Take no action in this case, since we can't be sure when the volume
281     // was manually adjusted. The compressor will still provide some of the
282     // desired gain change.
283     agc_->Reset();
284     frames_since_update_gain_ = 0;
285     is_first_frame_ = false;
286     return;
287   }
288 
289   new_level = std::min(new_level, max_level_);
290   if (new_level == level_) {
291     return;
292   }
293 
294   recommended_input_volume_ = new_level;
295   RTC_DLOG(LS_INFO) << "[agc] voe_level=" << voe_level << ", level_=" << level_
296                     << ", new_level=" << new_level;
297   level_ = new_level;
298 }
299 
SetMaxLevel(int level)300 void MonoAgc::SetMaxLevel(int level) {
301   RTC_DCHECK_GE(level, clipped_level_min_);
302   max_level_ = level;
303   // Scale the `kSurplusCompressionGain` linearly across the restricted
304   // level range.
305   max_compression_gain_ =
306       kMaxCompressionGain + std::floor((1.f * kMaxMicLevel - max_level_) /
307                                            (kMaxMicLevel - clipped_level_min_) *
308                                            kSurplusCompressionGain +
309                                        0.5f);
310   RTC_DLOG(LS_INFO) << "[agc] max_level_=" << max_level_
311                     << ", max_compression_gain_=" << max_compression_gain_;
312 }
313 
HandleCaptureOutputUsedChange(bool capture_output_used)314 void MonoAgc::HandleCaptureOutputUsedChange(bool capture_output_used) {
315   if (capture_output_used_ == capture_output_used) {
316     return;
317   }
318   capture_output_used_ = capture_output_used;
319 
320   if (capture_output_used) {
321     // When we start using the output, we should reset things to be safe.
322     check_volume_on_next_process_ = true;
323   }
324 }
325 
CheckVolumeAndReset()326 int MonoAgc::CheckVolumeAndReset() {
327   int level = recommended_input_volume_;
328   // Reasons for taking action at startup:
329   // 1) A person starting a call is expected to be heard.
330   // 2) Independent of interpretation of `level` == 0 we should raise it so the
331   // AGC can do its job properly.
332   if (level == 0 && !startup_) {
333     RTC_DLOG(LS_INFO)
334         << "[agc] VolumeCallbacks returned level=0, taking no action.";
335     return 0;
336   }
337   if (level < 0 || level > kMaxMicLevel) {
338     RTC_LOG(LS_ERROR) << "[agc] VolumeCallbacks returned an invalid level="
339                       << level;
340     return -1;
341   }
342   RTC_DLOG(LS_INFO) << "[agc] Initial GetMicVolume()=" << level;
343 
344   if (level < min_mic_level_) {
345     level = min_mic_level_;
346     RTC_DLOG(LS_INFO) << "[agc] Initial volume too low, raising to " << level;
347     recommended_input_volume_ = level;
348   }
349   agc_->Reset();
350   level_ = level;
351   startup_ = false;
352   frames_since_update_gain_ = 0;
353   is_first_frame_ = true;
354   return 0;
355 }
356 
357 // Distributes the required gain change between the digital compression stage
358 // and volume slider. We use the compressor first, providing a slack region
359 // around the current slider position to reduce movement.
360 //
361 // If the slider needs to be moved, we check first if the user has adjusted
362 // it, in which case we take no action and cache the updated level.
UpdateGain(int rms_error_db)363 void MonoAgc::UpdateGain(int rms_error_db) {
364   int rms_error = rms_error_db;
365 
366   // Always reset the counter regardless of whether the gain is changed
367   // or not. This matches with the bahvior of `agc_` where the histogram is
368   // reset every time an RMS error is successfully read.
369   frames_since_update_gain_ = 0;
370 
371   // The compressor will always add at least kMinCompressionGain. In effect,
372   // this adjusts our target gain upward by the same amount and rms_error
373   // needs to reflect that.
374   rms_error += kMinCompressionGain;
375 
376   // Handle as much error as possible with the compressor first.
377   int raw_compression =
378       rtc::SafeClamp(rms_error, kMinCompressionGain, max_compression_gain_);
379 
380   // Deemphasize the compression gain error. Move halfway between the current
381   // target and the newly received target. This serves to soften perceptible
382   // intra-talkspurt adjustments, at the cost of some adaptation speed.
383   if ((raw_compression == max_compression_gain_ &&
384        target_compression_ == max_compression_gain_ - 1) ||
385       (raw_compression == kMinCompressionGain &&
386        target_compression_ == kMinCompressionGain + 1)) {
387     // Special case to allow the target to reach the endpoints of the
388     // compression range. The deemphasis would otherwise halt it at 1 dB shy.
389     target_compression_ = raw_compression;
390   } else {
391     target_compression_ =
392         (raw_compression - target_compression_) / 2 + target_compression_;
393   }
394 
395   // Residual error will be handled by adjusting the volume slider. Use the
396   // raw rather than deemphasized compression here as we would otherwise
397   // shrink the amount of slack the compressor provides.
398   const int residual_gain =
399       rtc::SafeClamp(rms_error - raw_compression, -kMaxResidualGainChange,
400                      kMaxResidualGainChange);
401   RTC_DLOG(LS_INFO) << "[agc] rms_error=" << rms_error
402                     << ", target_compression=" << target_compression_
403                     << ", residual_gain=" << residual_gain;
404   if (residual_gain == 0)
405     return;
406 
407   int old_level = level_;
408   SetLevel(LevelFromGainError(residual_gain, level_, min_mic_level_));
409   if (old_level != level_) {
410     // level_ was updated by SetLevel; log the new value.
411     RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.AgcSetLevel", level_, 1,
412                                 kMaxMicLevel, 50);
413     // Reset the AGC since the level has changed.
414     agc_->Reset();
415   }
416 }
417 
UpdateCompressor()418 void MonoAgc::UpdateCompressor() {
419   if (compression_ == target_compression_) {
420     return;
421   }
422 
423   // Adapt the compression gain slowly towards the target, in order to avoid
424   // highly perceptible changes.
425   if (target_compression_ > compression_) {
426     compression_accumulator_ += kCompressionGainStep;
427   } else {
428     compression_accumulator_ -= kCompressionGainStep;
429   }
430 
431   // The compressor accepts integer gains in dB. Adjust the gain when
432   // we've come within half a stepsize of the nearest integer.  (We don't
433   // check for equality due to potential floating point imprecision).
434   int new_compression = compression_;
435   int nearest_neighbor = std::floor(compression_accumulator_ + 0.5);
436   if (std::fabs(compression_accumulator_ - nearest_neighbor) <
437       kCompressionGainStep / 2) {
438     new_compression = nearest_neighbor;
439   }
440 
441   // Set the new compression gain.
442   if (new_compression != compression_) {
443     compression_ = new_compression;
444     compression_accumulator_ = new_compression;
445     new_compression_to_set_ = compression_;
446   }
447 }
448 
449 std::atomic<int> AgcManagerDirect::instance_counter_(0);
450 
AgcManagerDirect(const AudioProcessing::Config::GainController1::AnalogGainController & analog_config,Agc * agc)451 AgcManagerDirect::AgcManagerDirect(
452     const AudioProcessing::Config::GainController1::AnalogGainController&
453         analog_config,
454     Agc* agc)
455     : AgcManagerDirect(/*num_capture_channels=*/1, analog_config) {
456   RTC_DCHECK(channel_agcs_[0]);
457   RTC_DCHECK(agc);
458   channel_agcs_[0]->set_agc(agc);
459 }
460 
AgcManagerDirect(int num_capture_channels,const AnalogAgcConfig & analog_config)461 AgcManagerDirect::AgcManagerDirect(int num_capture_channels,
462                                    const AnalogAgcConfig& analog_config)
463     : analog_controller_enabled_(analog_config.enabled),
464       min_mic_level_override_(GetMinMicLevelOverride()),
465       data_dumper_(new ApmDataDumper(instance_counter_.fetch_add(1) + 1)),
466       num_capture_channels_(num_capture_channels),
467       disable_digital_adaptive_(!analog_config.enable_digital_adaptive),
468       frames_since_clipped_(analog_config.clipped_wait_frames),
469       capture_output_used_(true),
470       clipped_level_step_(analog_config.clipped_level_step),
471       clipped_ratio_threshold_(analog_config.clipped_ratio_threshold),
472       clipped_wait_frames_(analog_config.clipped_wait_frames),
473       channel_agcs_(num_capture_channels),
474       new_compressions_to_set_(num_capture_channels),
475       clipping_predictor_(
476           CreateClippingPredictor(num_capture_channels,
477                                   analog_config.clipping_predictor)),
478       use_clipping_predictor_step_(
479           !!clipping_predictor_ &&
480           analog_config.clipping_predictor.use_predicted_step),
481       clipping_rate_log_(0.0f),
482       clipping_rate_log_counter_(0) {
483   RTC_LOG(LS_INFO) << "[agc] analog controller enabled: "
484                    << (analog_controller_enabled_ ? "yes" : "no");
485   const int min_mic_level = min_mic_level_override_.value_or(kMinMicLevel);
486   RTC_LOG(LS_INFO) << "[agc] Min mic level: " << min_mic_level
487                    << " (overridden: "
488                    << (min_mic_level_override_.has_value() ? "yes" : "no")
489                    << ")";
490   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
491     ApmDataDumper* data_dumper_ch = ch == 0 ? data_dumper_.get() : nullptr;
492 
493     channel_agcs_[ch] = std::make_unique<MonoAgc>(
494         data_dumper_ch, analog_config.clipped_level_min,
495         disable_digital_adaptive_, min_mic_level);
496   }
497   RTC_DCHECK(!channel_agcs_.empty());
498   RTC_DCHECK_GT(clipped_level_step_, 0);
499   RTC_DCHECK_LE(clipped_level_step_, 255);
500   RTC_DCHECK_GT(clipped_ratio_threshold_, 0.0f);
501   RTC_DCHECK_LT(clipped_ratio_threshold_, 1.0f);
502   RTC_DCHECK_GT(clipped_wait_frames_, 0);
503   channel_agcs_[0]->ActivateLogging();
504 }
505 
~AgcManagerDirect()506 AgcManagerDirect::~AgcManagerDirect() {}
507 
Initialize()508 void AgcManagerDirect::Initialize() {
509   RTC_DLOG(LS_INFO) << "AgcManagerDirect::Initialize";
510   data_dumper_->InitiateNewSetOfRecordings();
511   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
512     channel_agcs_[ch]->Initialize();
513   }
514   capture_output_used_ = true;
515 
516   AggregateChannelLevels();
517   clipping_rate_log_ = 0.0f;
518   clipping_rate_log_counter_ = 0;
519 }
520 
SetupDigitalGainControl(GainControl & gain_control) const521 void AgcManagerDirect::SetupDigitalGainControl(
522     GainControl& gain_control) const {
523   if (gain_control.set_mode(GainControl::kFixedDigital) != 0) {
524     RTC_LOG(LS_ERROR) << "set_mode(GainControl::kFixedDigital) failed.";
525   }
526   const int target_level_dbfs = disable_digital_adaptive_ ? 0 : 2;
527   if (gain_control.set_target_level_dbfs(target_level_dbfs) != 0) {
528     RTC_LOG(LS_ERROR) << "set_target_level_dbfs() failed.";
529   }
530   const int compression_gain_db =
531       disable_digital_adaptive_ ? 0 : kDefaultCompressionGain;
532   if (gain_control.set_compression_gain_db(compression_gain_db) != 0) {
533     RTC_LOG(LS_ERROR) << "set_compression_gain_db() failed.";
534   }
535   const bool enable_limiter = !disable_digital_adaptive_;
536   if (gain_control.enable_limiter(enable_limiter) != 0) {
537     RTC_LOG(LS_ERROR) << "enable_limiter() failed.";
538   }
539 }
540 
AnalyzePreProcess(const AudioBuffer & audio_buffer)541 void AgcManagerDirect::AnalyzePreProcess(const AudioBuffer& audio_buffer) {
542   const float* const* audio = audio_buffer.channels_const();
543   size_t samples_per_channel = audio_buffer.num_frames();
544   RTC_DCHECK(audio);
545 
546   AggregateChannelLevels();
547   if (!capture_output_used_) {
548     return;
549   }
550 
551   if (!!clipping_predictor_) {
552     AudioFrameView<const float> frame = AudioFrameView<const float>(
553         audio, num_capture_channels_, static_cast<int>(samples_per_channel));
554     clipping_predictor_->Analyze(frame);
555   }
556 
557   // Check for clipped samples, as the AGC has difficulty detecting pitch
558   // under clipping distortion. We do this in the preprocessing phase in order
559   // to catch clipped echo as well.
560   //
561   // If we find a sufficiently clipped frame, drop the current microphone level
562   // and enforce a new maximum level, dropped the same amount from the current
563   // maximum. This harsh treatment is an effort to avoid repeated clipped echo
564   // events. As compensation for this restriction, the maximum compression
565   // gain is increased, through SetMaxLevel().
566   float clipped_ratio =
567       ComputeClippedRatio(audio, num_capture_channels_, samples_per_channel);
568   clipping_rate_log_ = std::max(clipped_ratio, clipping_rate_log_);
569   clipping_rate_log_counter_++;
570   constexpr int kNumFramesIn30Seconds = 3000;
571   if (clipping_rate_log_counter_ == kNumFramesIn30Seconds) {
572     LogClippingMetrics(std::round(100.0f * clipping_rate_log_));
573     clipping_rate_log_ = 0.0f;
574     clipping_rate_log_counter_ = 0;
575   }
576 
577   if (frames_since_clipped_ < clipped_wait_frames_) {
578     ++frames_since_clipped_;
579     return;
580   }
581 
582   const bool clipping_detected = clipped_ratio > clipped_ratio_threshold_;
583   bool clipping_predicted = false;
584   int predicted_step = 0;
585   if (!!clipping_predictor_) {
586     for (int channel = 0; channel < num_capture_channels_; ++channel) {
587       const auto step = clipping_predictor_->EstimateClippedLevelStep(
588           channel, recommended_input_volume_, clipped_level_step_,
589           channel_agcs_[channel]->min_mic_level(), kMaxMicLevel);
590       if (step.has_value()) {
591         predicted_step = std::max(predicted_step, step.value());
592         clipping_predicted = true;
593       }
594     }
595   }
596   if (clipping_detected) {
597     RTC_DLOG(LS_INFO) << "[agc] Clipping detected. clipped_ratio="
598                       << clipped_ratio;
599   }
600   int step = clipped_level_step_;
601   if (clipping_predicted) {
602     predicted_step = std::max(predicted_step, clipped_level_step_);
603     RTC_DLOG(LS_INFO) << "[agc] Clipping predicted. step=" << predicted_step;
604     if (use_clipping_predictor_step_) {
605       step = predicted_step;
606     }
607   }
608   if (clipping_detected ||
609       (clipping_predicted && use_clipping_predictor_step_)) {
610     for (auto& state_ch : channel_agcs_) {
611       state_ch->HandleClipping(step);
612     }
613     frames_since_clipped_ = 0;
614     if (!!clipping_predictor_) {
615       clipping_predictor_->Reset();
616     }
617   }
618   AggregateChannelLevels();
619 }
620 
Process(const AudioBuffer & audio_buffer)621 void AgcManagerDirect::Process(const AudioBuffer& audio_buffer) {
622   Process(audio_buffer, /*speech_probability=*/absl::nullopt,
623           /*speech_level_dbfs=*/absl::nullopt);
624 }
625 
Process(const AudioBuffer & audio_buffer,absl::optional<float> speech_probability,absl::optional<float> speech_level_dbfs)626 void AgcManagerDirect::Process(const AudioBuffer& audio_buffer,
627                                absl::optional<float> speech_probability,
628                                absl::optional<float> speech_level_dbfs) {
629   AggregateChannelLevels();
630 
631   if (!capture_output_used_) {
632     return;
633   }
634 
635   const size_t num_frames_per_band = audio_buffer.num_frames_per_band();
636   absl::optional<int> rms_error_override = absl::nullopt;
637   if (speech_probability.has_value() && speech_level_dbfs.has_value()) {
638     rms_error_override =
639         GetSpeechLevelErrorDb(*speech_level_dbfs, *speech_probability);
640   }
641   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
642     std::array<int16_t, AudioBuffer::kMaxSampleRate / 100> audio_data;
643     int16_t* audio_use = audio_data.data();
644     FloatS16ToS16(audio_buffer.split_bands_const_f(ch)[0], num_frames_per_band,
645                   audio_use);
646     channel_agcs_[ch]->Process({audio_use, num_frames_per_band},
647                                rms_error_override);
648     new_compressions_to_set_[ch] = channel_agcs_[ch]->new_compression();
649   }
650 
651   AggregateChannelLevels();
652 }
653 
GetDigitalComressionGain()654 absl::optional<int> AgcManagerDirect::GetDigitalComressionGain() {
655   return new_compressions_to_set_[channel_controlling_gain_];
656 }
657 
HandleCaptureOutputUsedChange(bool capture_output_used)658 void AgcManagerDirect::HandleCaptureOutputUsedChange(bool capture_output_used) {
659   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
660     channel_agcs_[ch]->HandleCaptureOutputUsedChange(capture_output_used);
661   }
662   capture_output_used_ = capture_output_used;
663 }
664 
voice_probability() const665 float AgcManagerDirect::voice_probability() const {
666   float max_prob = 0.f;
667   for (const auto& state_ch : channel_agcs_) {
668     max_prob = std::max(max_prob, state_ch->voice_probability());
669   }
670 
671   return max_prob;
672 }
673 
set_stream_analog_level(int level)674 void AgcManagerDirect::set_stream_analog_level(int level) {
675   if (!analog_controller_enabled_) {
676     recommended_input_volume_ = level;
677   }
678 
679   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
680     channel_agcs_[ch]->set_stream_analog_level(level);
681   }
682 
683   AggregateChannelLevels();
684 }
685 
AggregateChannelLevels()686 void AgcManagerDirect::AggregateChannelLevels() {
687   int new_recommended_input_volume =
688       channel_agcs_[0]->recommended_analog_level();
689   channel_controlling_gain_ = 0;
690   for (size_t ch = 1; ch < channel_agcs_.size(); ++ch) {
691     int level = channel_agcs_[ch]->recommended_analog_level();
692     if (level < new_recommended_input_volume) {
693       new_recommended_input_volume = level;
694       channel_controlling_gain_ = static_cast<int>(ch);
695     }
696   }
697 
698   if (min_mic_level_override_.has_value() && new_recommended_input_volume > 0) {
699     new_recommended_input_volume =
700         std::max(new_recommended_input_volume, *min_mic_level_override_);
701   }
702 
703   if (analog_controller_enabled_) {
704     recommended_input_volume_ = new_recommended_input_volume;
705   }
706 }
707 
708 }  // namespace webrtc
709