blob: f22db20759d630777fbcdaddc68fb2f5cb8f7af8 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
alessiob3ec96df2017-05-22 06:57:06 -070016#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020017#include <type_traits>
18#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Yves Gerey988cc082018-10-23 12:03:01 +020020#include "absl/types/optional.h"
21#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/include/audio_util.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020024#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/common.h"
Yves Gerey988cc082018-10-23 12:03:01 +020027#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 21:42:56 +010028#include "modules/audio_processing/logging/apm_data_dumper.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/ref_counted_object.h"
34#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020036#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000038
Michael Graczyk86c6d332015-07-23 11:41:39 -070039#define RETURN_ON_ERR(expr) \
40 do { \
41 int err = (expr); \
42 if (err != kNoError) { \
43 return err; \
44 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000045 } while (0)
46
niklase@google.com470e71d2011-07-07 08:21:25 +000047namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070048
kwibergd59d3bb2016-09-13 07:49:33 -070049constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020050constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070051
Michael Graczyk86c6d332015-07-23 11:41:39 -070052namespace {
53
54static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
55 switch (layout) {
56 case AudioProcessing::kMono:
57 case AudioProcessing::kStereo:
58 return false;
59 case AudioProcessing::kMonoAndKeyboard:
60 case AudioProcessing::kStereoAndKeyboard:
61 return true;
62 }
63
kwiberg9e2be5f2016-09-14 05:23:22 -070064 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070065 return false;
66}
aluebsdf6416a2016-03-16 18:26:35 -070067
peah2ace3f92016-09-10 04:42:27 -070068bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070069 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
70 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
71}
72
Per Åhgren0cbb58e2019-10-29 22:59:44 +010073// Checks whether the legacy ns functionality should be enforced.
74bool DetectLegacyNsEnforcement() {
75 return field_trial::IsEnabled("WebRTC-NewNoiseSuppressionKillSwitch");
76}
77
Per Åhgrenc0424252019-12-10 13:04:15 +010078// Checks whether the high-pass filter should be done in the full-band.
79bool EnforceSplitBandHpf() {
80 return field_trial::IsEnabled("WebRTC-FullBandHpfKillSwitch");
81}
82
Per Åhgrenb2b58d82019-12-02 14:59:40 +010083// Checks whether AEC3 should be allowed to decide what the default
84// configuration should be based on the render and capture channel configuration
85// at hand.
86bool UseSetupSpecificDefaultAec3Congfig() {
87 return !field_trial::IsEnabled(
88 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
89}
90
Per Åhgrenc8626b62019-08-23 15:49:51 +020091// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020092int SuitableProcessRate(int minimum_rate,
93 int max_splitting_rate,
94 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020095 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020096 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020097 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070098 if (rate >= uppermost_native_rate) {
99 return uppermost_native_rate;
100 }
101 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700102 return rate;
103 }
104 }
peah2ace3f92016-09-10 04:42:27 -0700105 RTC_NOTREACHED();
106 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700107}
108
Sam Zackrisson23513132019-01-11 15:10:32 +0100109NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
110 AudioProcessing::Config::NoiseSuppression::Level level) {
111 using NsConfig = AudioProcessing::Config::NoiseSuppression;
112 switch (level) {
113 case NsConfig::kLow:
saza0bad15f2019-10-16 11:46:11 +0200114 return NoiseSuppression::Level::kLow;
Sam Zackrisson23513132019-01-11 15:10:32 +0100115 case NsConfig::kModerate:
saza0bad15f2019-10-16 11:46:11 +0200116 return NoiseSuppression::Level::kModerate;
Sam Zackrisson23513132019-01-11 15:10:32 +0100117 case NsConfig::kHigh:
saza0bad15f2019-10-16 11:46:11 +0200118 return NoiseSuppression::Level::kHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100119 case NsConfig::kVeryHigh:
saza0bad15f2019-10-16 11:46:11 +0200120 return NoiseSuppression::Level::kVeryHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100121 default:
122 RTC_NOTREACHED();
123 }
124}
125
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100126GainControl::Mode Agc1ConfigModeToInterfaceMode(
127 AudioProcessing::Config::GainController1::Mode mode) {
128 using Agc1Config = AudioProcessing::Config::GainController1;
129 switch (mode) {
130 case Agc1Config::kAdaptiveAnalog:
131 return GainControl::kAdaptiveAnalog;
132 case Agc1Config::kAdaptiveDigital:
133 return GainControl::kAdaptiveDigital;
134 case Agc1Config::kFixedDigital:
135 return GainControl::kFixedDigital;
136 }
137}
138
peah9e6a2902017-05-15 07:19:21 -0700139// Maximum lengths that frame of samples being passed from the render side to
140// the capture side can have (does not apply to AEC3).
141static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
142static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
143
peah764e3642016-10-22 05:04:30 -0700144// Maximum number of frames to buffer in the render queue.
145// TODO(peah): Decrease this once we properly handle hugely unbalanced
146// reverse and forward call numbers.
147static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700148} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000149
150// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000151static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000152
saza1d600522019-10-18 13:29:43 +0200153AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100154 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200155 bool render_pre_processor_enabled,
156 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100157 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200158 render_pre_processor_enabled_(render_pre_processor_enabled),
159 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700160
saza1d600522019-10-18 13:29:43 +0200161bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200162 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700163 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700164 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700165 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700167 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200168 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200169 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200170 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700171 bool transient_suppressor_enabled) {
172 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200173 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700174 changed |=
175 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700176 changed |=
177 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700178 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
179 changed |=
peah2ace3f92016-09-10 04:42:27 -0700180 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200181 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200182 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200183 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200184 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700185 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
186 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200187 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700188 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700189 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700190 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700191 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700192 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200193 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200194 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200195 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700196 transient_suppressor_enabled_ = transient_suppressor_enabled;
197 }
198
199 changed |= first_update_;
200 first_update_ = false;
201 return changed;
202}
203
saza1d600522019-10-18 13:29:43 +0200204bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700205 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200206 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700207}
208
saza1d600522019-10-18 13:29:43 +0200209bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
210 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200211 // If echo controller is present, assume it performs active processing.
212 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
213}
214
saza1d600522019-10-18 13:29:43 +0200215bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200216 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100217 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
218 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200219 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700220}
221
saza1d600522019-10-18 13:29:43 +0200222bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700223 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200224 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
225 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700226}
227
saza1d600522019-10-18 13:29:43 +0200228bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200229 return capture_analyzer_enabled_;
230}
231
saza1d600522019-10-18 13:29:43 +0200232bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700233 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100234 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
235 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700236}
237
saza1d600522019-10-18 13:29:43 +0200238bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100239 const {
240 return render_pre_processor_enabled_;
241}
242
saza1d600522019-10-18 13:29:43 +0200243bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700244 const {
peah2ace3f92016-09-10 04:42:27 -0700245 return false;
peah2ace3f92016-09-10 04:42:27 -0700246}
247
saza1d600522019-10-18 13:29:43 +0200248bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100249 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
250 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200251}
252
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100253AudioProcessingBuilder::AudioProcessingBuilder() = default;
254AudioProcessingBuilder::~AudioProcessingBuilder() = default;
255
256AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
257 std::unique_ptr<CustomProcessing> capture_post_processing) {
258 capture_post_processing_ = std::move(capture_post_processing);
259 return *this;
260}
261
262AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
263 std::unique_ptr<CustomProcessing> render_pre_processing) {
264 render_pre_processing_ = std::move(render_pre_processing);
265 return *this;
266}
267
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200268AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
269 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
270 capture_analyzer_ = std::move(capture_analyzer);
271 return *this;
272}
273
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100274AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
275 std::unique_ptr<EchoControlFactory> echo_control_factory) {
276 echo_control_factory_ = std::move(echo_control_factory);
277 return *this;
278}
279
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100280AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200281 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100282 echo_detector_ = std::move(echo_detector);
283 return *this;
284}
285
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100286AudioProcessing* AudioProcessingBuilder::Create() {
287 webrtc::Config config;
288 return Create(config);
289}
290
291AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100292 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
293 config, std::move(capture_post_processing_),
294 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200295 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100296 if (apm->Initialize() != AudioProcessing::kNoError) {
297 delete apm;
298 apm = nullptr;
299 }
300 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100301}
302
peah88ac8532016-09-12 16:47:25 -0700303AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200304 : AudioProcessingImpl(config,
305 /*capture_post_processor=*/nullptr,
306 /*render_pre_processor=*/nullptr,
307 /*echo_control_factory=*/nullptr,
308 /*echo_detector=*/nullptr,
309 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000310
Per Åhgren13735822018-02-12 21:42:56 +0100311int AudioProcessingImpl::instance_count_ = 0;
312
Sam Zackrisson0beac582017-09-25 12:04:02 +0200313AudioProcessingImpl::AudioProcessingImpl(
314 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100315 std::unique_ptr<CustomProcessing> capture_post_processor,
316 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200317 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200318 rtc::scoped_refptr<EchoDetector> echo_detector,
319 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100320 : data_dumper_(
321 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgren0cbb58e2019-10-29 22:59:44 +0100322 enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100323 use_setup_specific_default_aec3_config_(
324 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200325 capture_runtime_settings_(kRuntimeSettingQueueSize),
326 render_runtime_settings_(kRuntimeSettingQueueSize),
327 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
328 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200329 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200330 submodule_states_(!!capture_post_processor,
331 !!render_pre_processor,
332 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200333 submodules_(std::move(capture_post_processor),
334 std::move(render_pre_processor),
335 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100336 std::move(capture_analyzer)),
337 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
338 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000339#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Per Åhgren3daedb62019-11-22 12:11:40 +0100340 /* enabled= */ false,
341 /* enabled_agc2_level_estimator= */ false,
342 /* digital_adaptive_disabled= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000343#else
Per Åhgren3daedb62019-11-22 12:11:40 +0100344 config.Get<ExperimentalAgc>().enabled,
345 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
346 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000347#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200348 !field_trial::IsEnabled(
349 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
350 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100351 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
352 EnforceSplitBandHpf()),
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200353 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200354 RTC_LOG(LS_INFO) << "Injected APM submodules:"
355 << "\nEcho control factory: " << !!echo_control_factory_
356 << "\nEcho detector: " << !!submodules_.echo_detector
357 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
358 << "\nCapture post processor: "
359 << !!submodules_.capture_post_processor
360 << "\nRender pre processor: "
361 << !!submodules_.render_pre_processor;
362
Sam Zackrisson421c8592019-02-11 13:39:46 +0100363 // Mark Echo Controller enabled if a factory is injected.
364 capture_nonlocked_.echo_controller_enabled =
365 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000366
saza1d600522019-10-18 13:29:43 +0200367 submodules_.gain_control.reset(new GainControlImpl());
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200368
Sam Zackrisson421c8592019-02-11 13:39:46 +0100369 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200370 if (!submodules_.echo_detector) {
371 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100372 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800373 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000374
Per Åhgrenc0734712020-01-02 15:15:36 +0100375 // TODO(webrtc:5298): Remove once the use of ExperimentalNs has been
376 // deprecated.
377#if !(defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS))
378 config_.transient_suppression.enabled = config.Get<ExperimentalNs>().enabled;
379#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000380}
381
Per Åhgren0e3198e2019-11-18 08:52:22 +0100382AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000383
niklase@google.com470e71d2011-07-07 08:21:25 +0000384int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800385 // Run in a single-threaded manner during initialization.
386 rtc::CritScope cs_render(&crit_render_);
387 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000388 return InitializeLocked();
389}
390
peahde65ddc2016-09-16 15:02:15 -0700391int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
392 int capture_output_sample_rate_hz,
393 int render_input_sample_rate_hz,
394 ChannelLayout capture_input_layout,
395 ChannelLayout capture_output_layout,
396 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700397 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700398 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
399 LayoutHasKeyboard(capture_input_layout)},
400 {capture_output_sample_rate_hz,
401 ChannelsFromLayout(capture_output_layout),
402 LayoutHasKeyboard(capture_output_layout)},
403 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
404 LayoutHasKeyboard(render_input_layout)},
405 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
406 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700407
408 return Initialize(processing_config);
409}
410
411int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800412 // Run in a single-threaded manner during initialization.
413 rtc::CritScope cs_render(&crit_render_);
414 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700415 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000416}
417
peahdf3efa82015-11-28 12:35:15 -0800418int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800419 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800420 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200421 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800422 return kNoError;
423 }
peahdf3efa82015-11-28 12:35:15 -0800424
425 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800426 return InitializeLocked(processing_config);
427}
428
niklase@google.com470e71d2011-07-07 08:21:25 +0000429int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200430 UpdateActiveSubmoduleStates();
431
Per Åhgrend47941e2019-08-22 11:51:13 +0200432 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800433 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200434 ? formats_.render_processing_format.sample_rate_hz()
435 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800436 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
437 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200438 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800439 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200440 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700441 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200442 render_audiobuffer_sample_rate_hz,
443 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700444 if (formats_.api_format.reverse_input_stream() !=
445 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800446 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800447 formats_.api_format.reverse_input_stream().num_channels(),
448 formats_.api_format.reverse_input_stream().num_frames(),
449 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800450 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700451 } else {
peahdf3efa82015-11-28 12:35:15 -0800452 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700453 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700454 } else {
peahdf3efa82015-11-28 12:35:15 -0800455 render_.render_audio.reset(nullptr);
456 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700457 }
peahce4d9152017-05-19 01:28:05 -0700458
Per Åhgrend47941e2019-08-22 11:51:13 +0200459 capture_.capture_audio.reset(new AudioBuffer(
460 formats_.api_format.input_stream().sample_rate_hz(),
461 formats_.api_format.input_stream().num_channels(),
462 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
463 formats_.api_format.output_stream().num_channels(),
464 formats_.api_format.output_stream().sample_rate_hz(),
465 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000466
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200467 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
468 formats_.api_format.output_stream().sample_rate_hz() &&
469 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
470 capture_.capture_fullband_audio.reset(
471 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
472 formats_.api_format.input_stream().num_channels(),
473 formats_.api_format.output_stream().sample_rate_hz(),
474 formats_.api_format.output_stream().num_channels(),
475 formats_.api_format.output_stream().sample_rate_hz(),
476 formats_.api_format.output_stream().num_channels()));
477 } else {
478 capture_.capture_fullband_audio.reset();
479 }
480
peah764e3642016-10-22 05:04:30 -0700481 AllocateRenderQueue();
482
saza1d600522019-10-18 13:29:43 +0200483 submodules_.gain_control->Initialize(num_proc_channels(),
484 proc_sample_rate_hz());
Per Åhgren3daedb62019-11-22 12:11:40 +0100485 if (constants_.use_experimental_agc) {
486 if (!submodules_.agc_manager.get() ||
487 submodules_.agc_manager->num_channels() !=
488 static_cast<int>(num_proc_channels()) ||
489 submodules_.agc_manager->sample_rate_hz() !=
490 capture_nonlocked_.split_rate) {
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100491 int stream_analog_level = -1;
492 const bool re_creation = !!submodules_.agc_manager;
493 if (re_creation) {
494 stream_analog_level = submodules_.agc_manager->stream_analog_level();
495 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100496 submodules_.agc_manager.reset(new AgcManagerDirect(
497 num_proc_channels(), constants_.agc_startup_min_volume,
498 constants_.agc_clipped_level_min,
499 constants_.use_experimental_agc_agc2_level_estimation,
500 constants_.use_experimental_agc_agc2_digital_adaptive,
501 capture_nonlocked_.split_rate));
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100502 if (re_creation) {
503 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
504 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100505 }
saza1d600522019-10-18 13:29:43 +0200506 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 12:11:40 +0100507 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 08:52:22 +0100508 submodules_.gain_control.get());
saza1d600522019-10-18 13:29:43 +0200509 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 15:02:15 -0700510 }
Per Åhgrenc0734712020-01-02 15:15:36 +0100511 InitializeTransientSuppressor();
Per Åhgren4011de02019-12-03 11:48:48 +0000512 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200513 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700514 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200515 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700516 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200517 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200518 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200519 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100520 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800521
aleloi868f32f2017-05-23 07:20:05 -0700522 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200523 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700524 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000525 return kNoError;
526}
527
Michael Graczyk86c6d332015-07-23 11:41:39 -0700528int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200529 UpdateActiveSubmoduleStates();
530
Michael Graczyk86c6d332015-07-23 11:41:39 -0700531 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700532 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
533 return kBadSampleRateError;
534 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000535 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700536
Peter Kasting69558702016-01-12 16:26:35 -0800537 const size_t num_in_channels = config.input_stream().num_channels();
538 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700539
540 // Need at least one input channel.
541 // Need either one output channel or as many outputs as there are inputs.
542 if (num_in_channels == 0 ||
543 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700544 return kBadNumberChannelsError;
545 }
546
peahdf3efa82015-11-28 12:35:15 -0800547 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000548
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200549 // Choose maximum rate to use for the split filtering.
550 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
551 config_.pipeline.maximum_internal_processing_rate == 32000);
552 int max_splitting_rate = 48000;
553 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
554 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
555 }
556
Per Åhgrenc8626b62019-08-23 15:49:51 +0200557 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700558 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700559 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200560 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700561 submodule_states_.CaptureMultiBandSubModulesActive() ||
562 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200563 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000564
peahde65ddc2016-09-16 15:02:15 -0700565 capture_nonlocked_.capture_processing_format =
566 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700567
peah2ce640f2017-04-07 03:57:48 -0700568 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200569 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200570 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700571 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
572 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200573 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700574 submodule_states_.CaptureMultiBandSubModulesActive() ||
575 submodule_states_.RenderMultiBandSubModulesActive());
576 } else {
577 render_processing_rate = capture_processing_rate;
578 }
579
peahde65ddc2016-09-16 15:02:15 -0700580 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700581 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700582 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
583 kSampleRate8kHz) {
584 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000585 } else {
peahde65ddc2016-09-16 15:02:15 -0700586 render_processing_rate =
587 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000588 }
589
Per Åhgrenc8626b62019-08-23 15:49:51 +0200590 RTC_DCHECK_NE(8000, render_processing_rate);
591
peahce4d9152017-05-19 01:28:05 -0700592 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200593 // By default, downmix the render stream to mono for analysis. This has been
594 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100595 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
596 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200597 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100598 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200599 ? formats_.api_format.reverse_input_stream().num_channels()
600 : 1;
601 formats_.render_processing_format =
602 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700603 } else {
604 formats_.render_processing_format = StreamConfig(
605 formats_.api_format.reverse_input_stream().sample_rate_hz(),
606 formats_.api_format.reverse_input_stream().num_channels());
607 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000608
peahde65ddc2016-09-16 15:02:15 -0700609 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
610 kSampleRate32kHz ||
611 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
612 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800613 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000614 } else {
peahdf3efa82015-11-28 12:35:15 -0800615 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700616 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000617 }
618
619 return InitializeLocked();
620}
621
peah88ac8532016-09-12 16:47:25 -0700622void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200623 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
624
peah88ac8532016-09-12 16:47:25 -0700625 // Run in a single-threaded manner when applying the settings.
626 rtc::CritScope cs_render(&crit_render_);
627 rtc::CritScope cs_capture(&crit_capture_);
628
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200629 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100630 config_.pipeline.multi_channel_render !=
631 config.pipeline.multi_channel_render ||
632 config_.pipeline.multi_channel_capture !=
Per Åhgrenc0424252019-12-10 13:04:15 +0100633 config.pipeline.multi_channel_capture ||
634 config_.pipeline.maximum_internal_processing_rate !=
635 config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200636
Per Åhgren200feba2019-03-06 04:16:46 +0100637 const bool aec_config_changed =
638 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100639 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100640
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100641 const bool agc1_config_changed =
642 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
643 config_.gain_controller1.mode != config.gain_controller1.mode ||
644 config_.gain_controller1.target_level_dbfs !=
645 config.gain_controller1.target_level_dbfs ||
646 config_.gain_controller1.compression_gain_db !=
647 config.gain_controller1.compression_gain_db ||
648 config_.gain_controller1.enable_limiter !=
649 config.gain_controller1.enable_limiter ||
650 config_.gain_controller1.analog_level_minimum !=
651 config.gain_controller1.analog_level_minimum ||
652 config_.gain_controller1.analog_level_maximum !=
653 config.gain_controller1.analog_level_maximum;
654
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100655 const bool agc2_config_changed =
656 config_.gain_controller2.enabled != config.gain_controller2.enabled;
657
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200658 const bool voice_detection_config_changed =
659 config_.voice_detection.enabled != config.voice_detection.enabled;
660
saza0bad15f2019-10-16 11:46:11 +0200661 const bool ns_config_changed =
662 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
663 config_.noise_suppression.level != config.noise_suppression.level;
664
Per Åhgrenc0734712020-01-02 15:15:36 +0100665 const bool ts_config_changed = config_.transient_suppression.enabled !=
666 config.transient_suppression.enabled;
667
Yves Gerey499bc6c2018-10-10 18:29:07 +0200668 config_ = config;
669
Per Åhgren200feba2019-03-06 04:16:46 +0100670 if (aec_config_changed) {
671 InitializeEchoController();
672 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200673
saza0bad15f2019-10-16 11:46:11 +0200674 if (ns_config_changed) {
675 InitializeNoiseSuppressor();
676 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100677
Per Åhgrenc0734712020-01-02 15:15:36 +0100678 if (ts_config_changed) {
679 InitializeTransientSuppressor();
680 }
681
Per Åhgren4011de02019-12-03 11:48:48 +0000682 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800683
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100684 if (agc1_config_changed) {
685 ApplyAgc1Config(config_.gain_controller1);
686 }
687
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100688 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700689 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100690 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
691 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100692 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100693 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700694 config_.gain_controller2 = AudioProcessing::Config::GainController2();
695 }
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100696 if (agc2_config_changed) {
697 InitializeGainController2();
698 }
Alex Loikob5c9a792018-04-16 16:31:22 +0200699 InitializePreAmplifier();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100700
saza1d600522019-10-18 13:29:43 +0200701 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
702 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100703 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100704
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200705 if (voice_detection_config_changed) {
706 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100707 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200708
709 // Reinitialization must happen after all submodule configuration to avoid
710 // additional reinitializations on the next capture / render processing call.
711 if (pipeline_config_changed) {
712 InitializeLocked(formats_.api_format);
713 }
peah88ac8532016-09-12 16:47:25 -0700714}
715
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100716void AudioProcessingImpl::ApplyAgc1Config(
717 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100718 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100719 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100720
Per Åhgren0e3198e2019-11-18 08:52:22 +0100721 if (!submodules_.agc_manager) {
722 error = submodules_.gain_control->set_mode(
723 Agc1ConfigModeToInterfaceMode(config.mode));
724 RTC_DCHECK_EQ(kNoError, error);
725 error = submodules_.gain_control->set_target_level_dbfs(
726 config.target_level_dbfs);
727 RTC_DCHECK_EQ(kNoError, error);
728 error = submodules_.gain_control->set_compression_gain_db(
729 config.compression_gain_db);
730 RTC_DCHECK_EQ(kNoError, error);
731 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
732 RTC_DCHECK_EQ(kNoError, error);
733 error = submodules_.gain_control->set_analog_level_limits(
734 config.analog_level_minimum, config.analog_level_maximum);
735 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100736 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100737}
738
Per Åhgrenc0734712020-01-02 15:15:36 +0100739// TODO(webrtc:5298): Remove.
peah88ac8532016-09-12 16:47:25 -0700740void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000741}
742
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000743int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800744 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700745 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000746}
747
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200748int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
749 return capture_.capture_fullband_audio
750 ? capture_.capture_fullband_audio->num_frames() * 100
751 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
752}
753
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000754int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800755 // Used as callback from submodules, hence locking is not allowed.
756 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000757}
758
Peter Kasting69558702016-01-12 16:26:35 -0800759size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800760 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700761 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000762}
763
Peter Kasting69558702016-01-12 16:26:35 -0800764size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800765 // Used as callback from submodules, hence locking is not allowed.
766 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000767}
768
Peter Kasting69558702016-01-12 16:26:35 -0800769size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800770 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100771 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
772 constants_.multi_channel_capture_support;
773 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200774 return 1;
775 }
776 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800777}
778
Peter Kasting69558702016-01-12 16:26:35 -0800779size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800780 // Used as callback from submodules, hence locking is not allowed.
781 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000782}
783
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000784void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800785 rtc::CritScope cs(&crit_capture_);
786 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200787 if (submodules_.agc_manager.get()) {
788 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000789 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000790}
791
Alessio Bazzicac054e782018-04-16 12:10:09 +0200792void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200793 switch (setting.type()) {
794 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100795 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200796 render_runtime_settings_enqueuer_.Enqueue(setting);
797 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200798 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100799 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200800 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100801 capture_runtime_settings_enqueuer_.Enqueue(setting);
802 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200803 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200804 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100805 render_runtime_settings_enqueuer_.Enqueue(setting);
806 return;
807 case RuntimeSetting::Type::kNotSpecified:
808 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200809 return;
810 }
811 // The language allows the enum to have a non-enumerator
812 // value. Check that this doesn't happen.
813 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200814}
815
816AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
817 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200818 : runtime_settings_(*runtime_settings) {
819 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200820}
821
822AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
823 default;
824
825void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
826 RuntimeSetting setting) {
827 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200828 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200829 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200830 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200831 RTC_LOG(LS_ERROR)
832 << "The runtime settings queue is full. Oldest setting discarded.";
833 }
834 if (remaining_attempts == 0)
835 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
836}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000837
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000838int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700839 const StreamConfig& input_config,
840 const StreamConfig& output_config,
841 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800842 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800843 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700844 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800845 {
Sam Zackrisson308bc642019-12-23 10:22:08 +0100846 // Acquire the capture lock in order to:
847 // - Safely call the function that retrieves the render side data. This
848 // function accesses APM getters that need the capture lock held when
849 // being called.
850 // - Access api_format. The lock is released immediately due to the
851 // conditional reinitialization.
852
peahdf3efa82015-11-28 12:35:15 -0800853 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700854 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800855
856 if (!src || !dest) {
857 return kNullPointerError;
858 }
859
860 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700861 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000862 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000863
Oskar Sundbom4b276482019-05-23 14:28:00 +0200864 if (processing_config.input_stream() != input_config) {
865 processing_config.input_stream() = input_config;
866 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800867 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200868
869 if (processing_config.output_stream() != output_config) {
870 processing_config.output_stream() = output_config;
871 reinitialization_required = true;
872 }
873
874 if (reinitialization_required) {
875 // Reinitialize.
876 rtc::CritScope cs_render(&crit_render_);
877 rtc::CritScope cs_capture(&crit_capture_);
878 RETURN_ON_ERR(InitializeLocked(processing_config));
879 }
880
peahdf3efa82015-11-28 12:35:15 -0800881 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700882 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
883 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000884
aleloi868f32f2017-05-23 07:20:05 -0700885 if (aec_dump_) {
886 RecordUnprocessedCaptureStream(src);
887 }
888
Per Åhgrena1351272019-08-15 12:15:46 +0200889 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800890 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200891 if (capture_.capture_fullband_audio) {
892 capture_.capture_fullband_audio->CopyFrom(
893 src, formats_.api_format.input_stream());
894 }
peahde65ddc2016-09-16 15:02:15 -0700895 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200896 if (capture_.capture_fullband_audio) {
897 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
898 dest);
899 } else {
900 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
901 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000902
aleloi868f32f2017-05-23 07:20:05 -0700903 if (aec_dump_) {
904 RecordProcessedCaptureStream(dest);
905 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000906 return kNoError;
907}
908
Alex Loiko73ec0192018-05-15 10:52:28 +0200909void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200910 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200911 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200912 if (aec_dump_) {
913 aec_dump_->WriteRuntimeSetting(setting);
914 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200915 switch (setting.type()) {
916 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200917 if (config_.pre_amplifier.enabled) {
918 float value;
919 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200920 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200921 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200922 }
923 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200924 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100925 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100926 if (!submodules_.agc_manager) {
927 float value;
928 setting.GetFloat(&value);
929 int int_value = static_cast<int>(value + .5f);
930 config_.gain_controller1.compression_gain_db = int_value;
931 int error =
932 submodules_.gain_control->set_compression_gain_db(int_value);
933 RTC_DCHECK_EQ(kNoError, error);
934 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100935 break;
936 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200937 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100938 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200939 float value;
940 setting.GetFloat(&value);
941 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200942 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200943 }
944 break;
945 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200946 case RuntimeSetting::Type::kPlayoutVolumeChange: {
947 int value;
948 setting.GetInt(&value);
949 capture_.playout_volume = value;
950 break;
951 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100952 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
953 RTC_NOTREACHED();
954 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200955 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
956 RTC_NOTREACHED();
957 break;
958 case RuntimeSetting::Type::kNotSpecified:
959 RTC_NOTREACHED();
960 break;
961 }
962 }
963}
964
965void AudioProcessingImpl::HandleRenderRuntimeSettings() {
966 RuntimeSetting setting;
967 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200968 if (aec_dump_) {
969 aec_dump_->WriteRuntimeSetting(setting);
970 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200971 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100972 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100973 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200974 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200975 if (submodules_.render_pre_processor) {
976 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200977 }
978 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100979 case RuntimeSetting::Type::kCapturePreGain: // fall-through
980 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200981 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200982 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200983 RTC_NOTREACHED();
984 break;
985 }
986 }
987}
988
peah9e6a2902017-05-15 07:19:21 -0700989void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800990 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700991
saza1d600522019-10-18 13:29:43 +0200992 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200993 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
994 num_reverse_channels(),
995 &aecm_render_queue_buffer_);
996 RTC_DCHECK(aecm_render_signal_queue_);
997 // Insert the samples into the queue.
998 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
999 // The data queue is full and needs to be emptied.
1000 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001001
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001002 // Retry the insert (should always work).
1003 bool result =
1004 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1005 RTC_DCHECK(result);
1006 }
peah764e3642016-10-22 05:04:30 -07001007 }
peah701d6282016-10-25 05:42:20 -07001008
Per Åhgren0e3198e2019-11-18 08:52:22 +01001009 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001010 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001011 // Insert the samples into the queue.
1012 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1013 // The data queue is full and needs to be emptied.
1014 EmptyQueuedRenderAudio();
1015
1016 // Retry the insert (should always work).
1017 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1018 RTC_DCHECK(result);
1019 }
1020 }
peah9e6a2902017-05-15 07:19:21 -07001021}
ivoc9f4a4a02016-10-28 05:39:16 -07001022
peah9e6a2902017-05-15 07:19:21 -07001023void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001024 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1025
1026 // Insert the samples into the queue.
1027 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1028 // The data queue is full and needs to be emptied.
1029 EmptyQueuedRenderAudio();
1030
1031 // Retry the insert (should always work).
1032 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1033 RTC_DCHECK(result);
1034 }
peah764e3642016-10-22 05:04:30 -07001035}
1036
1037void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001038 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001039 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001040
ivoc9f4a4a02016-10-28 05:39:16 -07001041 const size_t new_red_render_queue_element_max_size =
1042 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1043
peaha0624602016-10-25 04:45:24 -07001044 // Reallocate the queues if the queue item sizes are too small to fit the
1045 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001046
1047 if (agc_render_queue_element_max_size_ <
1048 new_agc_render_queue_element_max_size) {
1049 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1050
1051 std::vector<int16_t> template_queue_element(
1052 agc_render_queue_element_max_size_);
1053
1054 agc_render_signal_queue_.reset(
1055 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1056 kMaxNumFramesToBuffer, template_queue_element,
1057 RenderQueueItemVerifier<int16_t>(
1058 agc_render_queue_element_max_size_)));
1059
1060 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1061 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1062 } else {
1063 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001064 }
ivoc9f4a4a02016-10-28 05:39:16 -07001065
1066 if (red_render_queue_element_max_size_ <
1067 new_red_render_queue_element_max_size) {
1068 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1069
1070 std::vector<float> template_queue_element(
1071 red_render_queue_element_max_size_);
1072
1073 red_render_signal_queue_.reset(
1074 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1075 kMaxNumFramesToBuffer, template_queue_element,
1076 RenderQueueItemVerifier<float>(
1077 red_render_queue_element_max_size_)));
1078
1079 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1080 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1081 } else {
1082 red_render_signal_queue_->Clear();
1083 }
peah764e3642016-10-22 05:04:30 -07001084}
1085
1086void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1087 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001088 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001089 RTC_DCHECK(aecm_render_signal_queue_);
1090 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001091 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001092 aecm_capture_queue_buffer_);
1093 }
peah701d6282016-10-25 05:42:20 -07001094 }
1095
1096 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001097 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001098 }
ivoc9f4a4a02016-10-28 05:39:16 -07001099
1100 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001101 RTC_DCHECK(submodules_.echo_detector);
1102 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001103 }
peah764e3642016-10-22 05:04:30 -07001104}
1105
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001106int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001107 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peah192164e2015-11-17 02:16:45 -08001108
peahdf3efa82015-11-28 12:35:15 -08001109 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001110 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001111 {
Sam Zackrisson308bc642019-12-23 10:22:08 +01001112 // Acquire the capture lock in order to:
1113 // - Safely call the function that retrieves the render side data. This
1114 // function accesses APM getters that need the capture lock held when
1115 // being called.
1116 // - Access api_format. The lock is released immediately due to the
1117 // conditional reinitialization.
peahdf3efa82015-11-28 12:35:15 -08001118 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson308bc642019-12-23 10:22:08 +01001119 EmptyQueuedRenderAudio();
1120
1121 if (!frame) {
1122 return kNullPointerError;
1123 }
1124 // Must be a native rate.
1125 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1126 frame->sample_rate_hz_ != kSampleRate16kHz &&
1127 frame->sample_rate_hz_ != kSampleRate32kHz &&
1128 frame->sample_rate_hz_ != kSampleRate48kHz) {
1129 return kBadSampleRateError;
1130 }
1131
peahdf3efa82015-11-28 12:35:15 -08001132 // TODO(ajm): The input and output rates and channels are currently
1133 // constrained to be identical in the int16 interface.
1134 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001135
1136 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001137 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001138
Oskar Sundbom4b276482019-05-23 14:28:00 +02001139 reinitialization_required =
1140 reinitialization_required ||
1141 processing_config.input_stream().sample_rate_hz() !=
1142 frame->sample_rate_hz_ ||
1143 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1144 processing_config.output_stream().sample_rate_hz() !=
1145 frame->sample_rate_hz_ ||
1146 processing_config.output_stream().num_channels() != frame->num_channels_;
1147
1148 if (reinitialization_required) {
1149 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1150 processing_config.input_stream().set_num_channels(frame->num_channels_);
1151 processing_config.output_stream().set_sample_rate_hz(
1152 frame->sample_rate_hz_);
1153 processing_config.output_stream().set_num_channels(frame->num_channels_);
1154
1155 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001156 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001157 rtc::CritScope cs_capture(&crit_capture_);
1158 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001159 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001160
peahdf3efa82015-11-28 12:35:15 -08001161 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001162 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001163 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001164 return kBadDataLengthError;
1165 }
1166
aleloi868f32f2017-05-23 07:20:05 -07001167 if (aec_dump_) {
1168 RecordUnprocessedCaptureStream(*frame);
1169 }
1170
Per Åhgrend47941e2019-08-22 11:51:13 +02001171 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001172 if (capture_.capture_fullband_audio) {
1173 capture_.capture_fullband_audio->CopyFrom(frame);
1174 }
peahde65ddc2016-09-16 15:02:15 -07001175 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001176 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001177 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001178 if (capture_.capture_fullband_audio) {
1179 capture_.capture_fullband_audio->CopyTo(frame);
1180 } else {
1181 capture_.capture_audio->CopyTo(frame);
1182 }
Per Åhgrena1351272019-08-15 12:15:46 +02001183 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001184 if (capture_.stats.voice_detected) {
1185 frame->vad_activity_ = *capture_.stats.voice_detected
1186 ? AudioFrame::kVadActive
1187 : AudioFrame::kVadPassive;
1188 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001189
aleloi868f32f2017-05-23 07:20:05 -07001190 if (aec_dump_) {
1191 RecordProcessedCaptureStream(*frame);
1192 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001193
1194 return kNoError;
1195}
1196
peahde65ddc2016-09-16 15:02:15 -07001197int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001198 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001199
peahb58a1582016-03-15 09:34:24 -07001200 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001201 // TODO(peah): Simplify once the public API Enable functions for these
1202 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001203 RTC_DCHECK_LE(
1204 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001205
peahde65ddc2016-09-16 15:02:15 -07001206 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001207 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001208
Per Åhgrenc0424252019-12-10 13:04:15 +01001209 if (submodules_.high_pass_filter &&
1210 config_.high_pass_filter.apply_in_full_band &&
1211 !constants_.enforce_split_band_hpf) {
1212 submodules_.high_pass_filter->Process(capture_buffer,
1213 /*use_split_band_data=*/false);
1214 }
1215
saza1d600522019-10-18 13:29:43 +02001216 if (submodules_.pre_amplifier) {
1217 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001218 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001219 capture_buffer->num_frames()));
1220 }
1221
Per Åhgren928146f2019-08-20 09:19:21 +02001222 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001223 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001224 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001225 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1226 if (log_rms) {
1227 capture_rms_interval_counter_ = 0;
1228 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001229 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1230 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1231 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1232 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001233 }
1234
saza1d600522019-10-18 13:29:43 +02001235 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001236 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001237 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001238 capture_.echo_path_gain_change =
1239 capture_.prev_analog_mic_level != analog_mic_level &&
1240 capture_.prev_analog_mic_level != -1;
1241 capture_.prev_analog_mic_level = analog_mic_level;
1242
Per Åhgrend2650d12018-10-02 17:00:59 +02001243 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001244 if (submodules_.pre_amplifier) {
1245 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001246 capture_.echo_path_gain_change =
1247 capture_.echo_path_gain_change ||
1248 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001249 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001250 capture_.prev_pre_amp_gain = pre_amp_gain;
1251 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001252
1253 // Detect volume change.
1254 capture_.echo_path_gain_change =
1255 capture_.echo_path_gain_change ||
1256 (capture_.prev_playout_volume != capture_.playout_volume &&
1257 capture_.prev_playout_volume >= 0);
1258 capture_.prev_playout_volume = capture_.playout_volume;
1259
saza1d600522019-10-18 13:29:43 +02001260 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001261 }
1262
Per Åhgren3daedb62019-11-22 12:11:40 +01001263 if (constants_.use_experimental_agc &&
1264 submodules_.gain_control->is_enabled()) {
1265 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001266 }
1267
peah2ace3f92016-09-10 04:42:27 -07001268 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1269 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001270 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1271 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001272 }
1273
Per Åhgrene14cb992019-11-27 09:34:22 +01001274 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1275 constants_.multi_channel_capture_support;
1276 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001277 // Force down-mixing of the number of channels after the detection of
1278 // capture signal saturation.
1279 // TODO(peah): Look into ensuring that this kind of tampering with the
1280 // AudioBuffer functionality should not be needed.
1281 capture_buffer->set_num_channels(1);
1282 }
1283
Per Åhgrenc0424252019-12-10 13:04:15 +01001284 if (submodules_.high_pass_filter &&
1285 (!config_.high_pass_filter.apply_in_full_band ||
1286 constants_.enforce_split_band_hpf)) {
1287 submodules_.high_pass_filter->Process(capture_buffer,
1288 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001289 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001290
Per Åhgrene35b32c2019-11-22 18:22:04 +01001291 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001292 RTC_DCHECK(
1293 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001294
1295 if (!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1296 !linear_aec_buffer || submodules_.echo_control_mobile) {
1297 if (submodules_.noise_suppressor) {
1298 submodules_.noise_suppressor->Analyze(*capture_buffer);
1299 } else if (submodules_.legacy_noise_suppressor) {
1300 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
1301 }
saza0bad15f2019-10-16 11:46:11 +02001302 }
peahb58a1582016-03-15 09:34:24 -07001303
saza1d600522019-10-18 13:29:43 +02001304 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001305 // Ensure that the stream delay was set before the call to the
1306 // AECM ProcessCaptureAudio function.
1307 if (!was_stream_delay_set()) {
1308 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001309 }
1310
saza1d600522019-10-18 13:29:43 +02001311 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001312 submodules_.noise_suppressor->Process(capture_buffer);
1313 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001314 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001315 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001316 }
peahe0eae3c2016-12-14 01:16:23 -08001317
saza1d600522019-10-18 13:29:43 +02001318 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001319 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001320 } else {
saza1d600522019-10-18 13:29:43 +02001321 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001322 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1323
1324 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001325 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001326 }
1327
saza1d600522019-10-18 13:29:43 +02001328 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001329 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001330 }
1331
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001332 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
1333 linear_aec_buffer) {
1334 if (submodules_.noise_suppressor) {
1335 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
1336 } else if (submodules_.legacy_noise_suppressor) {
1337 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(
1338 linear_aec_buffer);
1339 }
1340 }
1341
saza1d600522019-10-18 13:29:43 +02001342 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001343 submodules_.noise_suppressor->Process(capture_buffer);
1344 } else if (submodules_.legacy_noise_suppressor) {
1345 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001346 }
Per Åhgren46537a32017-06-07 10:08:10 +02001347 }
ivoc9f4a4a02016-10-28 05:39:16 -07001348
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001349 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001350 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001351 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001352 } else {
1353 capture_.stats.voice_detected = absl::nullopt;
1354 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001355
Per Åhgren3daedb62019-11-22 12:11:40 +01001356 if (constants_.use_experimental_agc &&
1357 submodules_.gain_control->is_enabled()) {
1358 submodules_.agc_manager->Process(capture_buffer);
1359
1360 absl::optional<int> new_digital_gain =
1361 submodules_.agc_manager->GetDigitalComressionGain();
1362 if (new_digital_gain) {
1363 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1364 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001365 }
Per Åhgren200feba2019-03-06 04:16:46 +01001366 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001367 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001368 capture_buffer, /*stream_has_echo*/ false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001369
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001370 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001371 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001372 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1373 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001374 }
1375
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001376 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001377 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001378 bool ec_active = ec ? ec->ActiveProcessing() : false;
1379 // Only update the fullband buffer if the multiband processing has changed
1380 // the signal. Keep the original signal otherwise.
1381 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1382 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1383 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001384 capture_buffer = capture_.capture_fullband_audio.get();
1385 }
1386
peah9e6a2902017-05-15 07:19:21 -07001387 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001388 RTC_DCHECK(submodules_.echo_detector);
1389 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1390 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001391 }
1392
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001393 // TODO(aluebs): Investigate if the transient suppression placement should be
1394 // before or after the AGC.
Per Åhgrenc0734712020-01-02 15:15:36 +01001395 if (submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001396 float voice_probability = submodules_.agc_manager.get()
1397 ? submodules_.agc_manager->voice_probability()
1398 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001399
saza1d600522019-10-18 13:29:43 +02001400 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001401 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001402 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001403 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001404 capture_buffer->num_frames_per_band(),
1405 capture_.keyboard_info.keyboard_data,
1406 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001407 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001408 }
1409
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001410 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001411 if (submodules_.capture_analyzer) {
1412 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001413 }
1414
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001415 if (submodules_.gain_controller2) {
saza1d600522019-10-18 13:29:43 +02001416 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001417 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001418 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001419 }
1420
saza1d600522019-10-18 13:29:43 +02001421 if (submodules_.capture_post_processor) {
1422 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001423 }
1424
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001425 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001426 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001427 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1428 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001429 } else {
1430 capture_.stats.output_rms_dbfs = absl::nullopt;
1431 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001432
Per Åhgren928146f2019-08-20 09:19:21 +02001433 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001434 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001435 capture_nonlocked_.capture_processing_format.num_frames()));
1436 if (log_rms) {
1437 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1438 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1439 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1440 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1441 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1442 }
1443
Per Åhgren0e3198e2019-11-18 08:52:22 +01001444 if (submodules_.agc_manager) {
1445 int level = recommended_stream_analog_level();
1446 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1447 &level);
1448 }
1449
Per Åhgrencf4c8722019-12-30 14:32:14 +01001450 // Compute echo-related stats.
1451 if (submodules_.echo_controller) {
1452 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1453 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1454 capture_.stats.echo_return_loss_enhancement =
1455 ec_metrics.echo_return_loss_enhancement;
1456 capture_.stats.delay_ms = ec_metrics.delay_ms;
1457 }
1458 if (config_.residual_echo_detector.enabled) {
1459 RTC_DCHECK(submodules_.echo_detector);
1460 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1461 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1462 capture_.stats.residual_echo_likelihood_recent_max =
1463 ed_metrics.echo_likelihood_recent_max;
1464 }
1465
1466 // Pass stats for reporting.
1467 stats_reporter_.UpdateStatistics(capture_.stats);
1468
peahdf3efa82015-11-28 12:35:15 -08001469 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001470 return kNoError;
1471}
1472
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001473int AudioProcessingImpl::AnalyzeReverseStream(
1474 const float* const* data,
1475 const StreamConfig& reverse_config) {
1476 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1477 rtc::CritScope cs(&crit_render_);
1478 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1479}
1480
peahde65ddc2016-09-16 15:02:15 -07001481int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1482 const StreamConfig& input_config,
1483 const StreamConfig& output_config,
1484 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001485 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001486 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001487 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001488 if (submodule_states_.RenderMultiBandProcessingActive() ||
1489 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001490 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1491 dest);
peah2ace3f92016-09-10 04:42:27 -07001492 } else if (formats_.api_format.reverse_input_stream() !=
1493 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001494 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1495 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001496 } else {
peahde65ddc2016-09-16 15:02:15 -07001497 CopyAudioIfNeeded(src, input_config.num_frames(),
1498 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001499 }
1500
1501 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001502}
1503
peahdf3efa82015-11-28 12:35:15 -08001504int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001505 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001506 const StreamConfig& input_config,
1507 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001508 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001509 return kNullPointerError;
1510 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001511
peahde65ddc2016-09-16 15:02:15 -07001512 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001513 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001514 }
1515
peahdf3efa82015-11-28 12:35:15 -08001516 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001517 processing_config.reverse_input_stream() = input_config;
1518 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001519
peahdf3efa82015-11-28 12:35:15 -08001520 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001521 RTC_DCHECK_EQ(input_config.num_frames(),
1522 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001523
aleloi868f32f2017-05-23 07:20:05 -07001524 if (aec_dump_) {
1525 const size_t channel_size =
1526 formats_.api_format.reverse_input_stream().num_frames();
1527 const size_t num_channels =
1528 formats_.api_format.reverse_input_stream().num_channels();
1529 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001530 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001531 }
peahdf3efa82015-11-28 12:35:15 -08001532 render_.render_audio->CopyFrom(src,
1533 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001534 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001535}
1536
1537int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001538 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001539 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001540 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001541 return kNullPointerError;
1542 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001543 // Must be a native rate.
1544 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1545 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001546 frame->sample_rate_hz_ != kSampleRate32kHz &&
1547 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001548 return kBadSampleRateError;
1549 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001550
Michael Graczyk86c6d332015-07-23 11:41:39 -07001551 if (frame->num_channels_ <= 0) {
1552 return kBadNumberChannelsError;
1553 }
1554
peahdf3efa82015-11-28 12:35:15 -08001555 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001556 processing_config.reverse_input_stream().set_sample_rate_hz(
1557 frame->sample_rate_hz_);
1558 processing_config.reverse_input_stream().set_num_channels(
1559 frame->num_channels_);
1560 processing_config.reverse_output_stream().set_sample_rate_hz(
1561 frame->sample_rate_hz_);
1562 processing_config.reverse_output_stream().set_num_channels(
1563 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001564
peahdf3efa82015-11-28 12:35:15 -08001565 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001566 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001567 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001568 return kBadDataLengthError;
1569 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001570
aleloi868f32f2017-05-23 07:20:05 -07001571 if (aec_dump_) {
1572 aec_dump_->WriteRenderStreamMessage(*frame);
1573 }
1574
Per Åhgrend47941e2019-08-22 11:51:13 +02001575 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001576 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001577 if (submodule_states_.RenderMultiBandProcessingActive() ||
1578 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001579 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001580 }
aluebsb0319552016-03-17 20:39:53 -07001581 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001582}
niklase@google.com470e71d2011-07-07 08:21:25 +00001583
peahde65ddc2016-09-16 15:02:15 -07001584int AudioProcessingImpl::ProcessRenderStreamLocked() {
1585 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001586
Alex Loiko73ec0192018-05-15 10:52:28 +02001587 HandleRenderRuntimeSettings();
1588
saza1d600522019-10-18 13:29:43 +02001589 if (submodules_.render_pre_processor) {
1590 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001591 }
1592
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001593 QueueNonbandedRenderAudio(render_buffer);
1594
peah2ace3f92016-09-10 04:42:27 -07001595 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001596 SampleRateSupportsMultiBand(
1597 formats_.render_processing_format.sample_rate_hz())) {
1598 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001599 }
1600
peahce4d9152017-05-19 01:28:05 -07001601 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1602 QueueBandedRenderAudio(render_buffer);
1603 }
1604
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001605 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001606 if (submodules_.echo_controller) {
1607 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001608 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001609
peah2ace3f92016-09-10 04:42:27 -07001610 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001611 SampleRateSupportsMultiBand(
1612 formats_.render_processing_format.sample_rate_hz())) {
1613 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001614 }
1615
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001616 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001617}
1618
1619int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001620 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001621 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001622 capture_.was_stream_delay_set = true;
1623 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001624
niklase@google.com470e71d2011-07-07 08:21:25 +00001625 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001626 delay = 0;
1627 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001628 }
1629
1630 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1631 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001632 delay = 500;
1633 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001634 }
1635
peahdf3efa82015-11-28 12:35:15 -08001636 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001637 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001638}
1639
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001640bool AudioProcessingImpl::GetLinearAecOutput(
1641 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1642 rtc::CritScope cs(&crit_capture_);
1643 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1644
1645 RTC_DCHECK(linear_aec_buffer);
1646 if (linear_aec_buffer) {
1647 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1648 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1649
1650 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1651 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1652 rtc::ArrayView<const float> channel_view =
1653 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1654 linear_aec_buffer->num_frames());
1655 std::copy(channel_view.begin(), channel_view.end(),
1656 linear_output[ch].begin());
1657 }
1658 return true;
1659 }
1660 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1661 RTC_NOTREACHED();
1662 return false;
1663}
1664
niklase@google.com470e71d2011-07-07 08:21:25 +00001665int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001666 // Used as callback from submodules, hence locking is not allowed.
1667 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001668}
1669
1670bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001671 // Used as callback from submodules, hence locking is not allowed.
1672 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001673}
1674
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001675void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001676 rtc::CritScope cs(&crit_capture_);
1677 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001678}
1679
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001680void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001681 rtc::CritScope cs(&crit_capture_);
1682 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001683}
1684
1685int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001686 rtc::CritScope cs(&crit_capture_);
1687 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001688}
1689
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001690void AudioProcessingImpl::set_stream_analog_level(int level) {
1691 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001692
1693 if (submodules_.agc_manager) {
1694 submodules_.agc_manager->set_stream_analog_level(level);
1695 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1696 1, &level);
1697 } else {
1698 int error = submodules_.gain_control->set_stream_analog_level(level);
1699 RTC_DCHECK_EQ(kNoError, error);
1700 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001701}
1702
1703int AudioProcessingImpl::recommended_stream_analog_level() const {
1704 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001705 if (submodules_.agc_manager) {
1706 return submodules_.agc_manager->stream_analog_level();
1707 }
1708 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001709}
1710
aleloi868f32f2017-05-23 07:20:05 -07001711void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1712 RTC_DCHECK(aec_dump);
1713 rtc::CritScope cs_render(&crit_render_);
1714 rtc::CritScope cs_capture(&crit_capture_);
1715
1716 // The previously attached AecDump will be destroyed with the
1717 // 'aec_dump' parameter, which is after locks are released.
1718 aec_dump_.swap(aec_dump);
1719 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001720 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001721}
1722
1723void AudioProcessingImpl::DetachAecDump() {
1724 // The d-tor of a task-queue based AecDump blocks until all pending
1725 // tasks are done. This construction avoids blocking while holding
1726 // the render and capture locks.
1727 std::unique_ptr<AecDump> aec_dump = nullptr;
1728 {
1729 rtc::CritScope cs_render(&crit_render_);
1730 rtc::CritScope cs_capture(&crit_capture_);
1731 aec_dump = std::move(aec_dump_);
1732 }
1733}
1734
Sam Zackrisson4d364492018-03-02 16:03:21 +01001735void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1736 std::unique_ptr<AudioGenerator> audio_generator) {
1737 // TODO(bugs.webrtc.org/8882) Stub.
1738 // Reset internal audio generator with audio_generator.
1739}
1740
1741void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1742 // TODO(bugs.webrtc.org/8882) Stub.
1743 // Delete audio generator, if one is attached.
1744}
1745
peah8271d042016-11-22 07:24:52 -08001746void AudioProcessingImpl::MutateConfig(
1747 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1748 rtc::CritScope cs_render(&crit_render_);
1749 rtc::CritScope cs_capture(&crit_capture_);
1750 mutator(&config_);
1751 ApplyConfig(config_);
1752}
1753
1754AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1755 rtc::CritScope cs_render(&crit_render_);
1756 rtc::CritScope cs_capture(&crit_capture_);
1757 return config_;
1758}
1759
peah2ace3f92016-09-10 04:42:27 -07001760bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1761 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001762 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
1763 config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001764 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001765 submodules_.gain_control->is_enabled(), !!submodules_.gain_controller2,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001766 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
Per Åhgrenc0734712020-01-02 15:15:36 +01001767 config_.voice_detection.enabled, !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001768}
1769
Per Åhgrenc0734712020-01-02 15:15:36 +01001770void AudioProcessingImpl::InitializeTransientSuppressor() {
1771 if (config_.transient_suppression.enabled) {
1772 if (!submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001773 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001774 }
saza1d600522019-10-18 13:29:43 +02001775 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1776 capture_nonlocked_.split_rate,
1777 num_proc_channels());
Per Åhgrenc0734712020-01-02 15:15:36 +01001778 } else {
1779 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001780 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001781}
1782
Per Åhgren4011de02019-12-03 11:48:48 +00001783void AudioProcessingImpl::InitializeHighPassFilter() {
Per Åhgrenb8106462019-12-04 08:34:12 +01001784 bool high_pass_filter_needed_by_aec =
1785 config_.echo_canceller.enabled &&
1786 config_.echo_canceller.enforce_high_pass_filtering &&
1787 !config_.echo_canceller.mobile_mode;
1788 if (submodule_states_.HighPassFilteringRequired() ||
1789 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001790 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1791 !constants_.enforce_split_band_hpf;
1792 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1793 : proc_split_sample_rate_hz();
1794 size_t num_channels =
1795 use_full_band ? num_output_channels() : num_proc_channels();
1796
1797 submodules_.high_pass_filter.reset(new HighPassFilter(rate, num_channels));
peah8271d042016-11-22 07:24:52 -08001798 } else {
saza1d600522019-10-18 13:29:43 +02001799 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001800 }
1801}
alessiob3ec96df2017-05-22 06:57:06 -07001802
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001803void AudioProcessingImpl::InitializeVoiceDetector() {
1804 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001805 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001806 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1807 } else {
saza1d600522019-10-18 13:29:43 +02001808 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001809 }
1810}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001811void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001812 bool use_echo_controller =
1813 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001814 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001815
1816 if (use_echo_controller) {
1817 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001818 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001819 submodules_.echo_controller = echo_control_factory_->Create(
1820 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001821 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001822 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001823 EchoCanceller3Config config =
1824 use_setup_specific_default_aec3_config_
1825 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1826 num_proc_channels())
1827 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001828 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001829 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001830 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001831 }
1832
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001833 // Setup the storage for returning the linear AEC output.
1834 if (config_.echo_canceller.export_linear_aec_output) {
1835 constexpr int kLinearOutputRateHz = 16000;
1836 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1837 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1838 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1839 } else {
1840 capture_.linear_aec_output.reset();
1841 }
1842
Per Åhgren200feba2019-03-06 04:16:46 +01001843 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001844
saza1d600522019-10-18 13:29:43 +02001845 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001846 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001847 return;
peahe0eae3c2016-12-14 01:16:23 -08001848 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001849
saza1d600522019-10-18 13:29:43 +02001850 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001851 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001852 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001853
1854 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001855 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001856 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001857 return;
1858 }
1859
1860 if (config_.echo_canceller.mobile_mode) {
1861 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001862 size_t max_element_size =
1863 std::max(static_cast<size_t>(1),
1864 kMaxAllowedValuesOfSamplesPerBand *
1865 EchoControlMobileImpl::NumCancellersRequired(
1866 num_output_channels(), num_reverse_channels()));
1867
1868 std::vector<int16_t> template_queue_element(max_element_size);
1869
1870 aecm_render_signal_queue_.reset(
1871 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1872 kMaxNumFramesToBuffer, template_queue_element,
1873 RenderQueueItemVerifier<int16_t>(max_element_size)));
1874
1875 aecm_render_queue_buffer_.resize(max_element_size);
1876 aecm_capture_queue_buffer_.resize(max_element_size);
1877
saza1d600522019-10-18 13:29:43 +02001878 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001879
saza1d600522019-10-18 13:29:43 +02001880 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1881 num_reverse_channels(),
1882 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001883 return;
1884 }
1885
saza1d600522019-10-18 13:29:43 +02001886 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001887 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001888}
peah8271d042016-11-22 07:24:52 -08001889
alessiob3ec96df2017-05-22 06:57:06 -07001890void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001891 if (config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001892 if (!submodules_.gain_controller2) {
1893 // TODO(alessiob): Move the injected gain controller once injection is
1894 // implemented.
1895 submodules_.gain_controller2.reset(new GainController2());
1896 }
1897
saza1d600522019-10-18 13:29:43 +02001898 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001899 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
1900 } else {
1901 submodules_.gain_controller2.reset();
alessiob3ec96df2017-05-22 06:57:06 -07001902 }
1903}
1904
saza0bad15f2019-10-16 11:46:11 +02001905void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001906 submodules_.legacy_noise_suppressor.reset();
1907 submodules_.noise_suppressor.reset();
1908
saza0bad15f2019-10-16 11:46:11 +02001909 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001910 const bool use_legacy_ns =
1911 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1912
1913 if (!use_legacy_ns) {
1914 auto map_level =
1915 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1916 using NoiseSuppresionConfig =
1917 AudioProcessing::Config::NoiseSuppression;
1918 switch (level) {
1919 case NoiseSuppresionConfig::kLow:
1920 return NsConfig::SuppressionLevel::k6dB;
1921 case NoiseSuppresionConfig::kModerate:
1922 return NsConfig::SuppressionLevel::k12dB;
1923 case NoiseSuppresionConfig::kHigh:
1924 return NsConfig::SuppressionLevel::k18dB;
1925 case NoiseSuppresionConfig::kVeryHigh:
1926 return NsConfig::SuppressionLevel::k21dB;
1927 default:
1928 RTC_NOTREACHED();
1929 }
1930 };
1931
1932 NsConfig cfg;
1933 cfg.target_level = map_level(config_.noise_suppression.level);
1934 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1935 cfg, proc_sample_rate_hz(), num_proc_channels());
1936 } else {
1937 auto ns_level =
1938 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1939 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1940 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1941 }
saza0bad15f2019-10-16 11:46:11 +02001942 }
1943}
1944
Alex Loikob5c9a792018-04-16 16:31:22 +02001945void AudioProcessingImpl::InitializePreAmplifier() {
1946 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001947 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001948 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1949 } else {
saza1d600522019-10-18 13:29:43 +02001950 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001951 }
1952}
1953
ivoc9f4a4a02016-10-28 05:39:16 -07001954void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001955 RTC_DCHECK(submodules_.echo_detector);
1956 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001957 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001958 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001959}
1960
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001961void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001962 if (submodules_.capture_analyzer) {
1963 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1964 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001965 }
1966}
1967
Sam Zackrisson0beac582017-09-25 12:04:02 +02001968void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001969 if (submodules_.capture_post_processor) {
1970 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001971 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001972 }
1973}
1974
Alex Loiko5825aa62017-12-18 16:02:40 +01001975void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001976 if (submodules_.render_pre_processor) {
1977 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001978 formats_.render_processing_format.sample_rate_hz(),
1979 formats_.render_processing_format.num_channels());
1980 }
1981}
1982
Per Åhgrenea4c5df2019-05-03 09:00:08 +02001983void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001984
aleloi868f32f2017-05-23 07:20:05 -07001985void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1986 if (!aec_dump_) {
1987 return;
1988 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001989
1990 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07001991 // TODO(peah): Add semicolon-separated concatenations of experiment
1992 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001993 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1994 experiments_description += "AgcClippingLevelExperiment;";
1995 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001996 if (capture_nonlocked_.echo_controller_enabled) {
1997 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001998 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001999 if (config_.gain_controller2.enabled) {
2000 experiments_description += "GainController2;";
2001 }
aleloi868f32f2017-05-23 07:20:05 -07002002
2003 InternalAPMConfig apm_config;
2004
Per Åhgren200feba2019-03-06 04:16:46 +01002005 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002006 apm_config.aec_delay_agnostic_enabled = false;
2007 apm_config.aec_extended_filter_enabled = false;
2008 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002009
saza1d600522019-10-18 13:29:43 +02002010 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002011 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002012 submodules_.echo_control_mobile &&
2013 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002014 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002015 submodules_.echo_control_mobile
2016 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002017 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002018
saza1d600522019-10-18 13:29:43 +02002019 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
2020 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07002021 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02002022 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01002023 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002024
2025 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2026
saza0bad15f2019-10-16 11:46:11 +02002027 apm_config.ns_enabled = config_.noise_suppression.enabled;
2028 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002029
2030 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002031 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002032 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002033 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2034 apm_config.pre_amplifier_fixed_gain_factor =
2035 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002036
2037 if (!forced && apm_config == apm_config_for_aec_dump_) {
2038 return;
2039 }
2040 aec_dump_->WriteConfig(apm_config);
2041 apm_config_for_aec_dump_ = apm_config;
2042}
2043
2044void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2045 const float* const* src) {
2046 RTC_DCHECK(aec_dump_);
2047 WriteAecDumpConfigMessage(false);
2048
2049 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2050 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2051 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002052 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002053 RecordAudioProcessingState();
2054}
2055
2056void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2057 const AudioFrame& capture_frame) {
2058 RTC_DCHECK(aec_dump_);
2059 WriteAecDumpConfigMessage(false);
2060
2061 aec_dump_->AddCaptureStreamInput(capture_frame);
2062 RecordAudioProcessingState();
2063}
2064
2065void AudioProcessingImpl::RecordProcessedCaptureStream(
2066 const float* const* processed_capture_stream) {
2067 RTC_DCHECK(aec_dump_);
2068
2069 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2070 const size_t num_channels =
2071 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002072 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2073 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002074 aec_dump_->WriteCaptureStreamMessage();
2075}
2076
2077void AudioProcessingImpl::RecordProcessedCaptureStream(
2078 const AudioFrame& processed_capture_frame) {
2079 RTC_DCHECK(aec_dump_);
2080
2081 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2082 aec_dump_->WriteCaptureStreamMessage();
2083}
2084
2085void AudioProcessingImpl::RecordAudioProcessingState() {
2086 RTC_DCHECK(aec_dump_);
2087 AecDump::AudioProcessingState audio_proc_state;
2088 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002089 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002090 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002091 audio_proc_state.keypress = capture_.key_pressed;
2092 aec_dump_->AddAudioProcessingState(audio_proc_state);
2093}
2094
Per Åhgrenc0734712020-01-02 15:15:36 +01002095AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002096 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002097 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002098 output_will_be_muted(false),
2099 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002100 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002101 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002102 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002103 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002104 prev_pre_amp_gain(-1.f),
2105 playout_volume(-1),
2106 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002107
2108AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2109
Per Åhgrena1351272019-08-15 12:15:46 +02002110void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2111 const float* const* data,
2112 const StreamConfig& stream_config) {
2113 if (stream_config.has_keyboard()) {
2114 keyboard_data = data[stream_config.num_channels()];
2115 } else {
2116 keyboard_data = NULL;
2117 }
2118 num_keyboard_frames = stream_config.num_frames();
2119}
2120
kwiberg83ffe452016-08-29 14:46:07 -07002121AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2122
2123AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2124
Per Åhgrencf4c8722019-12-30 14:32:14 +01002125AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2126 : stats_message_queue_(1) {}
2127
2128AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2129
2130AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
2131 rtc::CritScope cs_stats(&crit_stats_);
2132 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2133 // If the message queue is full, return the cached stats.
2134 static_cast<void>(new_stats_available);
2135
2136 return cached_stats_;
2137}
2138
2139void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2140 const AudioProcessingStats& new_stats) {
2141 AudioProcessingStats stats_to_queue = new_stats;
2142 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2143 // If the message queue is full, discard the new stats.
2144 static_cast<void>(stats_message_passed);
2145}
2146
niklase@google.com470e71d2011-07-07 08:21:25 +00002147} // namespace webrtc