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 "common_audio/include/audio_util.h"
17 #include "modules/audio_processing/agc/gain_control.h"
18 #include "modules/audio_processing/agc/gain_map_internal.h"
19 #include "modules/audio_processing/agc2/adaptive_mode_level_estimator_agc.h"
20 #include "rtc_base/atomic_ops.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 the microphone level is lowered with every clipping event.
32 const int kClippedLevelStep = 15;
33 // Proportion of clipped samples required to declare a clipping event.
34 const float kClippedRatioThreshold = 0.1f;
35 // Time in frames to wait after a clipping event before checking again.
36 const int kClippedWaitFrames = 300;
37 
38 // Amount of error we tolerate in the microphone level (presumably due to OS
39 // quantization) before we assume the user has manually adjusted the microphone.
40 const int kLevelQuantizationSlack = 25;
41 
42 const int kDefaultCompressionGain = 7;
43 const int kMaxCompressionGain = 12;
44 const int kMinCompressionGain = 2;
45 // Controls the rate of compression changes towards the target.
46 const float kCompressionGainStep = 0.05f;
47 
48 const int kMaxMicLevel = 255;
49 static_assert(kGainMapSize > kMaxMicLevel, "gain map too small");
50 const int kMinMicLevel = 12;
51 
52 // Prevent very large microphone level changes.
53 const int kMaxResidualGainChange = 15;
54 
55 // Maximum additional gain allowed to compensate for microphone level
56 // restrictions from clipping events.
57 const int kSurplusCompressionGain = 6;
58 
59 // Returns whether a fall-back solution to choose the maximum level should be
60 // chosen.
UseMaxAnalogChannelLevel()61 bool UseMaxAnalogChannelLevel() {
62   return field_trial::IsEnabled("WebRTC-UseMaxAnalogAgcChannelLevel");
63 }
64 
65 // Returns kMinMicLevel if no field trial exists or if it has been disabled.
66 // Returns a value between 0 and 255 depending on the field-trial string.
67 // Example: 'WebRTC-Audio-AgcMinMicLevelExperiment/Enabled-80' => returns 80.
GetMinMicLevel()68 int GetMinMicLevel() {
69   RTC_LOG(LS_INFO) << "[agc] GetMinMicLevel";
70   constexpr char kMinMicLevelFieldTrial[] =
71       "WebRTC-Audio-AgcMinMicLevelExperiment";
72   if (!webrtc::field_trial::IsEnabled(kMinMicLevelFieldTrial)) {
73     RTC_LOG(LS_INFO) << "[agc] Using default min mic level: " << kMinMicLevel;
74     return kMinMicLevel;
75   }
76   const auto field_trial_string =
77       webrtc::field_trial::FindFullName(kMinMicLevelFieldTrial);
78   int min_mic_level = -1;
79   sscanf(field_trial_string.c_str(), "Enabled-%d", &min_mic_level);
80   if (min_mic_level >= 0 && min_mic_level <= 255) {
81     RTC_LOG(LS_INFO) << "[agc] Experimental min mic level: " << min_mic_level;
82     return min_mic_level;
83   } else {
84     RTC_LOG(LS_WARNING) << "[agc] Invalid parameter for "
85                         << kMinMicLevelFieldTrial << ", ignored.";
86     return kMinMicLevel;
87   }
88 }
89 
ClampLevel(int mic_level,int min_mic_level)90 int ClampLevel(int mic_level, int min_mic_level) {
91   return rtc::SafeClamp(mic_level, min_mic_level, kMaxMicLevel);
92 }
93 
LevelFromGainError(int gain_error,int level,int min_mic_level)94 int LevelFromGainError(int gain_error, int level, int min_mic_level) {
95   RTC_DCHECK_GE(level, 0);
96   RTC_DCHECK_LE(level, kMaxMicLevel);
97   if (gain_error == 0) {
98     return level;
99   }
100 
101   int new_level = level;
102   if (gain_error > 0) {
103     while (kGainMap[new_level] - kGainMap[level] < gain_error &&
104            new_level < kMaxMicLevel) {
105       ++new_level;
106     }
107   } else {
108     while (kGainMap[new_level] - kGainMap[level] > gain_error &&
109            new_level > min_mic_level) {
110       --new_level;
111     }
112   }
113   return new_level;
114 }
115 
116 // Returns the proportion of samples in the buffer which are at full-scale
117 // (and presumably clipped).
ComputeClippedRatio(const float * const * audio,size_t num_channels,size_t samples_per_channel)118 float ComputeClippedRatio(const float* const* audio,
119                           size_t num_channels,
120                           size_t samples_per_channel) {
121   RTC_DCHECK_GT(samples_per_channel, 0);
122   int num_clipped = 0;
123   for (size_t ch = 0; ch < num_channels; ++ch) {
124     int num_clipped_in_ch = 0;
125     for (size_t i = 0; i < samples_per_channel; ++i) {
126       RTC_DCHECK(audio[ch]);
127       if (audio[ch][i] >= 32767.f || audio[ch][i] <= -32768.f) {
128         ++num_clipped_in_ch;
129       }
130     }
131     num_clipped = std::max(num_clipped, num_clipped_in_ch);
132   }
133   return static_cast<float>(num_clipped) / (samples_per_channel);
134 }
135 
136 }  // namespace
137 
MonoAgc(ApmDataDumper * data_dumper,int startup_min_level,int clipped_level_min,bool use_agc2_level_estimation,bool disable_digital_adaptive,int min_mic_level)138 MonoAgc::MonoAgc(ApmDataDumper* data_dumper,
139                  int startup_min_level,
140                  int clipped_level_min,
141                  bool use_agc2_level_estimation,
142                  bool disable_digital_adaptive,
143                  int min_mic_level)
144     : min_mic_level_(min_mic_level),
145       disable_digital_adaptive_(disable_digital_adaptive),
146       max_level_(kMaxMicLevel),
147       max_compression_gain_(kMaxCompressionGain),
148       target_compression_(kDefaultCompressionGain),
149       compression_(target_compression_),
150       compression_accumulator_(compression_),
151       startup_min_level_(ClampLevel(startup_min_level, min_mic_level_)),
152       clipped_level_min_(clipped_level_min) {
153   if (use_agc2_level_estimation) {
154     agc_ = std::make_unique<AdaptiveModeLevelEstimatorAgc>(data_dumper);
155   } else {
156     agc_ = std::make_unique<Agc>();
157   }
158 }
159 
160 MonoAgc::~MonoAgc() = default;
161 
Initialize()162 void MonoAgc::Initialize() {
163   max_level_ = kMaxMicLevel;
164   max_compression_gain_ = kMaxCompressionGain;
165   target_compression_ = disable_digital_adaptive_ ? 0 : kDefaultCompressionGain;
166   compression_ = disable_digital_adaptive_ ? 0 : target_compression_;
167   compression_accumulator_ = compression_;
168   capture_muted_ = false;
169   check_volume_on_next_process_ = true;
170 }
171 
Process(const int16_t * audio,size_t samples_per_channel,int sample_rate_hz)172 void MonoAgc::Process(const int16_t* audio,
173                       size_t samples_per_channel,
174                       int sample_rate_hz) {
175   new_compression_to_set_ = absl::nullopt;
176 
177   if (check_volume_on_next_process_) {
178     check_volume_on_next_process_ = false;
179     // We have to wait until the first process call to check the volume,
180     // because Chromium doesn't guarantee it to be valid any earlier.
181     CheckVolumeAndReset();
182   }
183 
184   agc_->Process(audio, samples_per_channel, sample_rate_hz);
185 
186   UpdateGain();
187   if (!disable_digital_adaptive_) {
188     UpdateCompressor();
189   }
190 }
191 
HandleClipping()192 void MonoAgc::HandleClipping() {
193   // Always decrease the maximum level, even if the current level is below
194   // threshold.
195   SetMaxLevel(std::max(clipped_level_min_, max_level_ - kClippedLevelStep));
196   if (log_to_histograms_) {
197     RTC_HISTOGRAM_BOOLEAN("WebRTC.Audio.AgcClippingAdjustmentAllowed",
198                           level_ - kClippedLevelStep >= clipped_level_min_);
199   }
200   if (level_ > clipped_level_min_) {
201     // Don't try to adjust the level if we're already below the limit. As
202     // a consequence, if the user has brought the level above the limit, we
203     // will still not react until the postproc updates the level.
204     SetLevel(std::max(clipped_level_min_, level_ - kClippedLevelStep));
205     // Reset the AGCs for all channels since the level has changed.
206     agc_->Reset();
207   }
208 }
209 
SetLevel(int new_level)210 void MonoAgc::SetLevel(int new_level) {
211   int voe_level = stream_analog_level_;
212   if (voe_level == 0) {
213     RTC_DLOG(LS_INFO)
214         << "[agc] VolumeCallbacks returned level=0, taking no action.";
215     return;
216   }
217   if (voe_level < 0 || voe_level > kMaxMicLevel) {
218     RTC_LOG(LS_ERROR) << "VolumeCallbacks returned an invalid level="
219                       << voe_level;
220     return;
221   }
222 
223   if (voe_level > level_ + kLevelQuantizationSlack ||
224       voe_level < level_ - kLevelQuantizationSlack) {
225     RTC_DLOG(LS_INFO) << "[agc] Mic volume was manually adjusted. Updating "
226                          "stored level from "
227                       << level_ << " to " << voe_level;
228     level_ = voe_level;
229     // Always allow the user to increase the volume.
230     if (level_ > max_level_) {
231       SetMaxLevel(level_);
232     }
233     // Take no action in this case, since we can't be sure when the volume
234     // was manually adjusted. The compressor will still provide some of the
235     // desired gain change.
236     agc_->Reset();
237 
238     return;
239   }
240 
241   new_level = std::min(new_level, max_level_);
242   if (new_level == level_) {
243     return;
244   }
245 
246   stream_analog_level_ = new_level;
247   RTC_DLOG(LS_INFO) << "[agc] voe_level=" << voe_level << ", level_=" << level_
248                     << ", new_level=" << new_level;
249   level_ = new_level;
250 }
251 
SetMaxLevel(int level)252 void MonoAgc::SetMaxLevel(int level) {
253   RTC_DCHECK_GE(level, clipped_level_min_);
254   max_level_ = level;
255   // Scale the |kSurplusCompressionGain| linearly across the restricted
256   // level range.
257   max_compression_gain_ =
258       kMaxCompressionGain + std::floor((1.f * kMaxMicLevel - max_level_) /
259                                            (kMaxMicLevel - clipped_level_min_) *
260                                            kSurplusCompressionGain +
261                                        0.5f);
262   RTC_DLOG(LS_INFO) << "[agc] max_level_=" << max_level_
263                     << ", max_compression_gain_=" << max_compression_gain_;
264 }
265 
SetCaptureMuted(bool muted)266 void MonoAgc::SetCaptureMuted(bool muted) {
267   if (capture_muted_ == muted) {
268     return;
269   }
270   capture_muted_ = muted;
271 
272   if (!muted) {
273     // When we unmute, we should reset things to be safe.
274     check_volume_on_next_process_ = true;
275   }
276 }
277 
CheckVolumeAndReset()278 int MonoAgc::CheckVolumeAndReset() {
279   int level = stream_analog_level_;
280   // Reasons for taking action at startup:
281   // 1) A person starting a call is expected to be heard.
282   // 2) Independent of interpretation of |level| == 0 we should raise it so the
283   // AGC can do its job properly.
284   if (level == 0 && !startup_) {
285     RTC_DLOG(LS_INFO)
286         << "[agc] VolumeCallbacks returned level=0, taking no action.";
287     return 0;
288   }
289   if (level < 0 || level > kMaxMicLevel) {
290     RTC_LOG(LS_ERROR) << "[agc] VolumeCallbacks returned an invalid level="
291                       << level;
292     return -1;
293   }
294   RTC_DLOG(LS_INFO) << "[agc] Initial GetMicVolume()=" << level;
295 
296   int minLevel = startup_ ? startup_min_level_ : min_mic_level_;
297   if (level < minLevel) {
298     level = minLevel;
299     RTC_DLOG(LS_INFO) << "[agc] Initial volume too low, raising to " << level;
300     stream_analog_level_ = level;
301   }
302   agc_->Reset();
303   level_ = level;
304   startup_ = false;
305   return 0;
306 }
307 
308 // Requests the RMS error from AGC and distributes the required gain change
309 // between the digital compression stage and volume slider. We use the
310 // compressor first, providing a slack region around the current slider
311 // position to reduce movement.
312 //
313 // If the slider needs to be moved, we check first if the user has adjusted
314 // it, in which case we take no action and cache the updated level.
UpdateGain()315 void MonoAgc::UpdateGain() {
316   int rms_error = 0;
317   if (!agc_->GetRmsErrorDb(&rms_error)) {
318     // No error update ready.
319     return;
320   }
321   // The compressor will always add at least kMinCompressionGain. In effect,
322   // this adjusts our target gain upward by the same amount and rms_error
323   // needs to reflect that.
324   rms_error += kMinCompressionGain;
325 
326   // Handle as much error as possible with the compressor first.
327   int raw_compression =
328       rtc::SafeClamp(rms_error, kMinCompressionGain, max_compression_gain_);
329 
330   // Deemphasize the compression gain error. Move halfway between the current
331   // target and the newly received target. This serves to soften perceptible
332   // intra-talkspurt adjustments, at the cost of some adaptation speed.
333   if ((raw_compression == max_compression_gain_ &&
334        target_compression_ == max_compression_gain_ - 1) ||
335       (raw_compression == kMinCompressionGain &&
336        target_compression_ == kMinCompressionGain + 1)) {
337     // Special case to allow the target to reach the endpoints of the
338     // compression range. The deemphasis would otherwise halt it at 1 dB shy.
339     target_compression_ = raw_compression;
340   } else {
341     target_compression_ =
342         (raw_compression - target_compression_) / 2 + target_compression_;
343   }
344 
345   // Residual error will be handled by adjusting the volume slider. Use the
346   // raw rather than deemphasized compression here as we would otherwise
347   // shrink the amount of slack the compressor provides.
348   const int residual_gain =
349       rtc::SafeClamp(rms_error - raw_compression, -kMaxResidualGainChange,
350                      kMaxResidualGainChange);
351   RTC_DLOG(LS_INFO) << "[agc] rms_error=" << rms_error
352                     << ", target_compression=" << target_compression_
353                     << ", residual_gain=" << residual_gain;
354   if (residual_gain == 0)
355     return;
356 
357   int old_level = level_;
358   SetLevel(LevelFromGainError(residual_gain, level_, min_mic_level_));
359   if (old_level != level_) {
360     // level_ was updated by SetLevel; log the new value.
361     RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.AgcSetLevel", level_, 1,
362                                 kMaxMicLevel, 50);
363     // Reset the AGC since the level has changed.
364     agc_->Reset();
365   }
366 }
367 
UpdateCompressor()368 void MonoAgc::UpdateCompressor() {
369   calls_since_last_gain_log_++;
370   if (calls_since_last_gain_log_ == 100) {
371     calls_since_last_gain_log_ = 0;
372     RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.Agc.DigitalGainApplied",
373                                 compression_, 0, kMaxCompressionGain,
374                                 kMaxCompressionGain + 1);
375   }
376   if (compression_ == target_compression_) {
377     return;
378   }
379 
380   // Adapt the compression gain slowly towards the target, in order to avoid
381   // highly perceptible changes.
382   if (target_compression_ > compression_) {
383     compression_accumulator_ += kCompressionGainStep;
384   } else {
385     compression_accumulator_ -= kCompressionGainStep;
386   }
387 
388   // The compressor accepts integer gains in dB. Adjust the gain when
389   // we've come within half a stepsize of the nearest integer.  (We don't
390   // check for equality due to potential floating point imprecision).
391   int new_compression = compression_;
392   int nearest_neighbor = std::floor(compression_accumulator_ + 0.5);
393   if (std::fabs(compression_accumulator_ - nearest_neighbor) <
394       kCompressionGainStep / 2) {
395     new_compression = nearest_neighbor;
396   }
397 
398   // Set the new compression gain.
399   if (new_compression != compression_) {
400     RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.Agc.DigitalGainUpdated",
401                                 new_compression, 0, kMaxCompressionGain,
402                                 kMaxCompressionGain + 1);
403     compression_ = new_compression;
404     compression_accumulator_ = new_compression;
405     new_compression_to_set_ = compression_;
406   }
407 }
408 
409 int AgcManagerDirect::instance_counter_ = 0;
410 
AgcManagerDirect(Agc * agc,int startup_min_level,int clipped_level_min,int sample_rate_hz)411 AgcManagerDirect::AgcManagerDirect(Agc* agc,
412                                    int startup_min_level,
413                                    int clipped_level_min,
414                                    int sample_rate_hz)
415     : AgcManagerDirect(/*num_capture_channels*/ 1,
416                        startup_min_level,
417                        clipped_level_min,
418                        /*use_agc2_level_estimation*/ false,
419                        /*disable_digital_adaptive*/ false,
420                        sample_rate_hz) {
421   RTC_DCHECK(channel_agcs_[0]);
422   RTC_DCHECK(agc);
423   channel_agcs_[0]->set_agc(agc);
424 }
425 
AgcManagerDirect(int num_capture_channels,int startup_min_level,int clipped_level_min,bool use_agc2_level_estimation,bool disable_digital_adaptive,int sample_rate_hz)426 AgcManagerDirect::AgcManagerDirect(int num_capture_channels,
427                                    int startup_min_level,
428                                    int clipped_level_min,
429                                    bool use_agc2_level_estimation,
430                                    bool disable_digital_adaptive,
431                                    int sample_rate_hz)
432     : data_dumper_(
433           new ApmDataDumper(rtc::AtomicOps::Increment(&instance_counter_))),
434       use_min_channel_level_(!UseMaxAnalogChannelLevel()),
435       sample_rate_hz_(sample_rate_hz),
436       num_capture_channels_(num_capture_channels),
437       disable_digital_adaptive_(disable_digital_adaptive),
438       frames_since_clipped_(kClippedWaitFrames),
439       capture_muted_(false),
440       channel_agcs_(num_capture_channels),
441       new_compressions_to_set_(num_capture_channels) {
442   const int min_mic_level = GetMinMicLevel();
443   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
444     ApmDataDumper* data_dumper_ch = ch == 0 ? data_dumper_.get() : nullptr;
445 
446     channel_agcs_[ch] = std::make_unique<MonoAgc>(
447         data_dumper_ch, startup_min_level, clipped_level_min,
448         use_agc2_level_estimation, disable_digital_adaptive_, min_mic_level);
449   }
450   RTC_DCHECK_LT(0, channel_agcs_.size());
451   channel_agcs_[0]->ActivateLogging();
452 }
453 
~AgcManagerDirect()454 AgcManagerDirect::~AgcManagerDirect() {}
455 
Initialize()456 void AgcManagerDirect::Initialize() {
457   RTC_DLOG(LS_INFO) << "AgcManagerDirect::Initialize";
458   data_dumper_->InitiateNewSetOfRecordings();
459   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
460     channel_agcs_[ch]->Initialize();
461   }
462   capture_muted_ = false;
463 
464   AggregateChannelLevels();
465 }
466 
SetupDigitalGainControl(GainControl * gain_control) const467 void AgcManagerDirect::SetupDigitalGainControl(
468     GainControl* gain_control) const {
469   RTC_DCHECK(gain_control);
470   if (gain_control->set_mode(GainControl::kFixedDigital) != 0) {
471     RTC_LOG(LS_ERROR) << "set_mode(GainControl::kFixedDigital) failed.";
472   }
473   const int target_level_dbfs = disable_digital_adaptive_ ? 0 : 2;
474   if (gain_control->set_target_level_dbfs(target_level_dbfs) != 0) {
475     RTC_LOG(LS_ERROR) << "set_target_level_dbfs() failed.";
476   }
477   const int compression_gain_db =
478       disable_digital_adaptive_ ? 0 : kDefaultCompressionGain;
479   if (gain_control->set_compression_gain_db(compression_gain_db) != 0) {
480     RTC_LOG(LS_ERROR) << "set_compression_gain_db() failed.";
481   }
482   const bool enable_limiter = !disable_digital_adaptive_;
483   if (gain_control->enable_limiter(enable_limiter) != 0) {
484     RTC_LOG(LS_ERROR) << "enable_limiter() failed.";
485   }
486 }
487 
AnalyzePreProcess(const AudioBuffer * audio)488 void AgcManagerDirect::AnalyzePreProcess(const AudioBuffer* audio) {
489   RTC_DCHECK(audio);
490   AnalyzePreProcess(audio->channels_const(), audio->num_frames());
491 }
492 
AnalyzePreProcess(const float * const * audio,size_t samples_per_channel)493 void AgcManagerDirect::AnalyzePreProcess(const float* const* audio,
494                                          size_t samples_per_channel) {
495   RTC_DCHECK(audio);
496   AggregateChannelLevels();
497   if (capture_muted_) {
498     return;
499   }
500 
501   if (frames_since_clipped_ < kClippedWaitFrames) {
502     ++frames_since_clipped_;
503     return;
504   }
505 
506   // Check for clipped samples, as the AGC has difficulty detecting pitch
507   // under clipping distortion. We do this in the preprocessing phase in order
508   // to catch clipped echo as well.
509   //
510   // If we find a sufficiently clipped frame, drop the current microphone level
511   // and enforce a new maximum level, dropped the same amount from the current
512   // maximum. This harsh treatment is an effort to avoid repeated clipped echo
513   // events. As compensation for this restriction, the maximum compression
514   // gain is increased, through SetMaxLevel().
515   float clipped_ratio =
516       ComputeClippedRatio(audio, num_capture_channels_, samples_per_channel);
517 
518   if (clipped_ratio > kClippedRatioThreshold) {
519     RTC_DLOG(LS_INFO) << "[agc] Clipping detected. clipped_ratio="
520                       << clipped_ratio;
521     for (auto& state_ch : channel_agcs_) {
522       state_ch->HandleClipping();
523     }
524     frames_since_clipped_ = 0;
525   }
526   AggregateChannelLevels();
527 }
528 
Process(const AudioBuffer * audio)529 void AgcManagerDirect::Process(const AudioBuffer* audio) {
530   AggregateChannelLevels();
531 
532   if (capture_muted_) {
533     return;
534   }
535 
536   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
537     int16_t* audio_use = nullptr;
538     std::array<int16_t, AudioBuffer::kMaxSampleRate / 100> audio_data;
539     int num_frames_per_band;
540     if (audio) {
541       FloatS16ToS16(audio->split_bands_const_f(ch)[0],
542                     audio->num_frames_per_band(), audio_data.data());
543       audio_use = audio_data.data();
544       num_frames_per_band = audio->num_frames_per_band();
545     } else {
546       // Only used for testing.
547       // TODO(peah): Change unittests to only allow on non-null audio input.
548       num_frames_per_band = 320;
549     }
550     channel_agcs_[ch]->Process(audio_use, num_frames_per_band, sample_rate_hz_);
551     new_compressions_to_set_[ch] = channel_agcs_[ch]->new_compression();
552   }
553 
554   AggregateChannelLevels();
555 }
556 
GetDigitalComressionGain()557 absl::optional<int> AgcManagerDirect::GetDigitalComressionGain() {
558   return new_compressions_to_set_[channel_controlling_gain_];
559 }
560 
SetCaptureMuted(bool muted)561 void AgcManagerDirect::SetCaptureMuted(bool muted) {
562   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
563     channel_agcs_[ch]->SetCaptureMuted(muted);
564   }
565   capture_muted_ = muted;
566 }
567 
voice_probability() const568 float AgcManagerDirect::voice_probability() const {
569   float max_prob = 0.f;
570   for (const auto& state_ch : channel_agcs_) {
571     max_prob = std::max(max_prob, state_ch->voice_probability());
572   }
573 
574   return max_prob;
575 }
576 
set_stream_analog_level(int level)577 void AgcManagerDirect::set_stream_analog_level(int level) {
578   for (size_t ch = 0; ch < channel_agcs_.size(); ++ch) {
579     channel_agcs_[ch]->set_stream_analog_level(level);
580   }
581 
582   AggregateChannelLevels();
583 }
584 
AggregateChannelLevels()585 void AgcManagerDirect::AggregateChannelLevels() {
586   stream_analog_level_ = channel_agcs_[0]->stream_analog_level();
587   channel_controlling_gain_ = 0;
588   if (use_min_channel_level_) {
589     for (size_t ch = 1; ch < channel_agcs_.size(); ++ch) {
590       int level = channel_agcs_[ch]->stream_analog_level();
591       if (level < stream_analog_level_) {
592         stream_analog_level_ = level;
593         channel_controlling_gain_ = static_cast<int>(ch);
594       }
595     }
596   } else {
597     for (size_t ch = 1; ch < channel_agcs_.size(); ++ch) {
598       int level = channel_agcs_[ch]->stream_analog_level();
599       if (level > stream_analog_level_) {
600         stream_analog_level_ = level;
601         channel_controlling_gain_ = static_cast<int>(ch);
602       }
603     }
604   }
605 }
606 
607 }  // namespace webrtc
608