blob: e91a56747636171498289b1a96a88f7e6efa6cf3 [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 Åhgren0f14db22020-01-03 14:27:14 +0100512 InitializeHighPassFilter(true);
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
Per Åhgren0f14db22020-01-03 14:27:14 +0100668 const bool pre_amplifier_config_changed =
669 config_.pre_amplifier.enabled != config.pre_amplifier.enabled ||
670 config_.pre_amplifier.fixed_gain_factor !=
671 config.pre_amplifier.fixed_gain_factor;
672
Yves Gerey499bc6c2018-10-10 18:29:07 +0200673 config_ = config;
674
Per Åhgren200feba2019-03-06 04:16:46 +0100675 if (aec_config_changed) {
676 InitializeEchoController();
677 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200678
saza0bad15f2019-10-16 11:46:11 +0200679 if (ns_config_changed) {
680 InitializeNoiseSuppressor();
681 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100682
Per Åhgrenc0734712020-01-02 15:15:36 +0100683 if (ts_config_changed) {
684 InitializeTransientSuppressor();
685 }
686
Per Åhgren0f14db22020-01-03 14:27:14 +0100687 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800688
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100689 if (agc1_config_changed) {
690 ApplyAgc1Config(config_.gain_controller1);
691 }
692
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100693 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700694 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100695 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
696 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100697 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100698 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700699 config_.gain_controller2 = AudioProcessing::Config::GainController2();
700 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100701
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100702 if (agc2_config_changed) {
703 InitializeGainController2();
704 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100705
706 if (pre_amplifier_config_changed) {
707 InitializePreAmplifier();
708 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100709
saza1d600522019-10-18 13:29:43 +0200710 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
711 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100712 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100713
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200714 if (voice_detection_config_changed) {
715 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100716 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200717
718 // Reinitialization must happen after all submodule configuration to avoid
719 // additional reinitializations on the next capture / render processing call.
720 if (pipeline_config_changed) {
721 InitializeLocked(formats_.api_format);
722 }
peah88ac8532016-09-12 16:47:25 -0700723}
724
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100725void AudioProcessingImpl::ApplyAgc1Config(
726 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100727 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100728 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100729
Per Åhgren0e3198e2019-11-18 08:52:22 +0100730 if (!submodules_.agc_manager) {
731 error = submodules_.gain_control->set_mode(
732 Agc1ConfigModeToInterfaceMode(config.mode));
733 RTC_DCHECK_EQ(kNoError, error);
734 error = submodules_.gain_control->set_target_level_dbfs(
735 config.target_level_dbfs);
736 RTC_DCHECK_EQ(kNoError, error);
737 error = submodules_.gain_control->set_compression_gain_db(
738 config.compression_gain_db);
739 RTC_DCHECK_EQ(kNoError, error);
740 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
741 RTC_DCHECK_EQ(kNoError, error);
742 error = submodules_.gain_control->set_analog_level_limits(
743 config.analog_level_minimum, config.analog_level_maximum);
744 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100745 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100746}
747
Per Åhgrenc0734712020-01-02 15:15:36 +0100748// TODO(webrtc:5298): Remove.
peah88ac8532016-09-12 16:47:25 -0700749void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000750}
751
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000752int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800753 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700754 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000755}
756
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200757int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
758 return capture_.capture_fullband_audio
759 ? capture_.capture_fullband_audio->num_frames() * 100
760 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
761}
762
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000763int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800764 // Used as callback from submodules, hence locking is not allowed.
765 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000766}
767
Peter Kasting69558702016-01-12 16:26:35 -0800768size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800769 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700770 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000771}
772
Peter Kasting69558702016-01-12 16:26:35 -0800773size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800774 // Used as callback from submodules, hence locking is not allowed.
775 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000776}
777
Peter Kasting69558702016-01-12 16:26:35 -0800778size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800779 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100780 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
781 constants_.multi_channel_capture_support;
782 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200783 return 1;
784 }
785 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800786}
787
Peter Kasting69558702016-01-12 16:26:35 -0800788size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800789 // Used as callback from submodules, hence locking is not allowed.
790 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000791}
792
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000793void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800794 rtc::CritScope cs(&crit_capture_);
795 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200796 if (submodules_.agc_manager.get()) {
797 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000798 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000799}
800
Alessio Bazzicac054e782018-04-16 12:10:09 +0200801void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200802 switch (setting.type()) {
803 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100804 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200805 render_runtime_settings_enqueuer_.Enqueue(setting);
806 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200807 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100808 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200809 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100810 capture_runtime_settings_enqueuer_.Enqueue(setting);
811 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200812 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200813 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100814 render_runtime_settings_enqueuer_.Enqueue(setting);
815 return;
816 case RuntimeSetting::Type::kNotSpecified:
817 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200818 return;
819 }
820 // The language allows the enum to have a non-enumerator
821 // value. Check that this doesn't happen.
822 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200823}
824
825AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
826 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200827 : runtime_settings_(*runtime_settings) {
828 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200829}
830
831AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
832 default;
833
834void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
835 RuntimeSetting setting) {
836 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200837 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200838 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200839 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200840 RTC_LOG(LS_ERROR)
841 << "The runtime settings queue is full. Oldest setting discarded.";
842 }
843 if (remaining_attempts == 0)
844 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
845}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000846
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000847int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700848 const StreamConfig& input_config,
849 const StreamConfig& output_config,
850 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800851 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800852 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700853 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800854 {
Sam Zackrisson308bc642019-12-23 10:22:08 +0100855 // Acquire the capture lock in order to:
856 // - Safely call the function that retrieves the render side data. This
857 // function accesses APM getters that need the capture lock held when
858 // being called.
859 // - Access api_format. The lock is released immediately due to the
860 // conditional reinitialization.
861
peahdf3efa82015-11-28 12:35:15 -0800862 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700863 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800864
865 if (!src || !dest) {
866 return kNullPointerError;
867 }
868
869 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700870 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000871 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000872
Oskar Sundbom4b276482019-05-23 14:28:00 +0200873 if (processing_config.input_stream() != input_config) {
874 processing_config.input_stream() = input_config;
875 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800876 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200877
878 if (processing_config.output_stream() != output_config) {
879 processing_config.output_stream() = output_config;
880 reinitialization_required = true;
881 }
882
883 if (reinitialization_required) {
884 // Reinitialize.
885 rtc::CritScope cs_render(&crit_render_);
886 rtc::CritScope cs_capture(&crit_capture_);
887 RETURN_ON_ERR(InitializeLocked(processing_config));
888 }
889
peahdf3efa82015-11-28 12:35:15 -0800890 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700891 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
892 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000893
aleloi868f32f2017-05-23 07:20:05 -0700894 if (aec_dump_) {
895 RecordUnprocessedCaptureStream(src);
896 }
897
Per Åhgrena1351272019-08-15 12:15:46 +0200898 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800899 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200900 if (capture_.capture_fullband_audio) {
901 capture_.capture_fullband_audio->CopyFrom(
902 src, formats_.api_format.input_stream());
903 }
peahde65ddc2016-09-16 15:02:15 -0700904 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200905 if (capture_.capture_fullband_audio) {
906 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
907 dest);
908 } else {
909 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
910 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000911
aleloi868f32f2017-05-23 07:20:05 -0700912 if (aec_dump_) {
913 RecordProcessedCaptureStream(dest);
914 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000915 return kNoError;
916}
917
Alex Loiko73ec0192018-05-15 10:52:28 +0200918void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200919 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200920 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200921 if (aec_dump_) {
922 aec_dump_->WriteRuntimeSetting(setting);
923 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200924 switch (setting.type()) {
925 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200926 if (config_.pre_amplifier.enabled) {
927 float value;
928 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200929 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200930 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200931 }
932 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200933 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100934 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100935 if (!submodules_.agc_manager) {
936 float value;
937 setting.GetFloat(&value);
938 int int_value = static_cast<int>(value + .5f);
939 config_.gain_controller1.compression_gain_db = int_value;
940 int error =
941 submodules_.gain_control->set_compression_gain_db(int_value);
942 RTC_DCHECK_EQ(kNoError, error);
943 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100944 break;
945 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200946 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100947 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200948 float value;
949 setting.GetFloat(&value);
950 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200951 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200952 }
953 break;
954 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200955 case RuntimeSetting::Type::kPlayoutVolumeChange: {
956 int value;
957 setting.GetInt(&value);
958 capture_.playout_volume = value;
959 break;
960 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100961 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
962 RTC_NOTREACHED();
963 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200964 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
965 RTC_NOTREACHED();
966 break;
967 case RuntimeSetting::Type::kNotSpecified:
968 RTC_NOTREACHED();
969 break;
970 }
971 }
972}
973
974void AudioProcessingImpl::HandleRenderRuntimeSettings() {
975 RuntimeSetting setting;
976 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200977 if (aec_dump_) {
978 aec_dump_->WriteRuntimeSetting(setting);
979 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200980 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100981 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100982 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200983 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200984 if (submodules_.render_pre_processor) {
985 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200986 }
987 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100988 case RuntimeSetting::Type::kCapturePreGain: // fall-through
989 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200990 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200991 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200992 RTC_NOTREACHED();
993 break;
994 }
995 }
996}
997
peah9e6a2902017-05-15 07:19:21 -0700998void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800999 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001000
saza1d600522019-10-18 13:29:43 +02001001 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001002 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1003 num_reverse_channels(),
1004 &aecm_render_queue_buffer_);
1005 RTC_DCHECK(aecm_render_signal_queue_);
1006 // Insert the samples into the queue.
1007 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1008 // The data queue is full and needs to be emptied.
1009 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001010
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001011 // Retry the insert (should always work).
1012 bool result =
1013 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1014 RTC_DCHECK(result);
1015 }
peah764e3642016-10-22 05:04:30 -07001016 }
peah701d6282016-10-25 05:42:20 -07001017
Per Åhgren0e3198e2019-11-18 08:52:22 +01001018 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001019 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001020 // Insert the samples into the queue.
1021 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1022 // The data queue is full and needs to be emptied.
1023 EmptyQueuedRenderAudio();
1024
1025 // Retry the insert (should always work).
1026 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1027 RTC_DCHECK(result);
1028 }
1029 }
peah9e6a2902017-05-15 07:19:21 -07001030}
ivoc9f4a4a02016-10-28 05:39:16 -07001031
peah9e6a2902017-05-15 07:19:21 -07001032void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001033 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1034
1035 // Insert the samples into the queue.
1036 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1037 // The data queue is full and needs to be emptied.
1038 EmptyQueuedRenderAudio();
1039
1040 // Retry the insert (should always work).
1041 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1042 RTC_DCHECK(result);
1043 }
peah764e3642016-10-22 05:04:30 -07001044}
1045
1046void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001047 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001048 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001049
ivoc9f4a4a02016-10-28 05:39:16 -07001050 const size_t new_red_render_queue_element_max_size =
1051 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1052
peaha0624602016-10-25 04:45:24 -07001053 // Reallocate the queues if the queue item sizes are too small to fit the
1054 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001055
1056 if (agc_render_queue_element_max_size_ <
1057 new_agc_render_queue_element_max_size) {
1058 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1059
1060 std::vector<int16_t> template_queue_element(
1061 agc_render_queue_element_max_size_);
1062
1063 agc_render_signal_queue_.reset(
1064 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1065 kMaxNumFramesToBuffer, template_queue_element,
1066 RenderQueueItemVerifier<int16_t>(
1067 agc_render_queue_element_max_size_)));
1068
1069 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1070 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1071 } else {
1072 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001073 }
ivoc9f4a4a02016-10-28 05:39:16 -07001074
1075 if (red_render_queue_element_max_size_ <
1076 new_red_render_queue_element_max_size) {
1077 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1078
1079 std::vector<float> template_queue_element(
1080 red_render_queue_element_max_size_);
1081
1082 red_render_signal_queue_.reset(
1083 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1084 kMaxNumFramesToBuffer, template_queue_element,
1085 RenderQueueItemVerifier<float>(
1086 red_render_queue_element_max_size_)));
1087
1088 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1089 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1090 } else {
1091 red_render_signal_queue_->Clear();
1092 }
peah764e3642016-10-22 05:04:30 -07001093}
1094
1095void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1096 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001097 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001098 RTC_DCHECK(aecm_render_signal_queue_);
1099 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001100 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001101 aecm_capture_queue_buffer_);
1102 }
peah701d6282016-10-25 05:42:20 -07001103 }
1104
1105 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001106 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001107 }
ivoc9f4a4a02016-10-28 05:39:16 -07001108
1109 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001110 RTC_DCHECK(submodules_.echo_detector);
1111 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001112 }
peah764e3642016-10-22 05:04:30 -07001113}
1114
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001115int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001116 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peah192164e2015-11-17 02:16:45 -08001117
peahdf3efa82015-11-28 12:35:15 -08001118 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001119 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001120 {
Sam Zackrisson308bc642019-12-23 10:22:08 +01001121 // Acquire the capture lock in order to:
1122 // - Safely call the function that retrieves the render side data. This
1123 // function accesses APM getters that need the capture lock held when
1124 // being called.
1125 // - Access api_format. The lock is released immediately due to the
1126 // conditional reinitialization.
peahdf3efa82015-11-28 12:35:15 -08001127 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson308bc642019-12-23 10:22:08 +01001128 EmptyQueuedRenderAudio();
1129
1130 if (!frame) {
1131 return kNullPointerError;
1132 }
1133 // Must be a native rate.
1134 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1135 frame->sample_rate_hz_ != kSampleRate16kHz &&
1136 frame->sample_rate_hz_ != kSampleRate32kHz &&
1137 frame->sample_rate_hz_ != kSampleRate48kHz) {
1138 return kBadSampleRateError;
1139 }
1140
peahdf3efa82015-11-28 12:35:15 -08001141 // TODO(ajm): The input and output rates and channels are currently
1142 // constrained to be identical in the int16 interface.
1143 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001144
1145 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001146 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001147
Oskar Sundbom4b276482019-05-23 14:28:00 +02001148 reinitialization_required =
1149 reinitialization_required ||
1150 processing_config.input_stream().sample_rate_hz() !=
1151 frame->sample_rate_hz_ ||
1152 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1153 processing_config.output_stream().sample_rate_hz() !=
1154 frame->sample_rate_hz_ ||
1155 processing_config.output_stream().num_channels() != frame->num_channels_;
1156
1157 if (reinitialization_required) {
1158 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1159 processing_config.input_stream().set_num_channels(frame->num_channels_);
1160 processing_config.output_stream().set_sample_rate_hz(
1161 frame->sample_rate_hz_);
1162 processing_config.output_stream().set_num_channels(frame->num_channels_);
1163
1164 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001165 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001166 rtc::CritScope cs_capture(&crit_capture_);
1167 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001168 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001169
peahdf3efa82015-11-28 12:35:15 -08001170 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001171 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001172 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001173 return kBadDataLengthError;
1174 }
1175
aleloi868f32f2017-05-23 07:20:05 -07001176 if (aec_dump_) {
1177 RecordUnprocessedCaptureStream(*frame);
1178 }
1179
Per Åhgrend47941e2019-08-22 11:51:13 +02001180 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001181 if (capture_.capture_fullband_audio) {
1182 capture_.capture_fullband_audio->CopyFrom(frame);
1183 }
peahde65ddc2016-09-16 15:02:15 -07001184 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001185 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001186 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001187 if (capture_.capture_fullband_audio) {
1188 capture_.capture_fullband_audio->CopyTo(frame);
1189 } else {
1190 capture_.capture_audio->CopyTo(frame);
1191 }
Per Åhgrena1351272019-08-15 12:15:46 +02001192 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001193 if (capture_.stats.voice_detected) {
1194 frame->vad_activity_ = *capture_.stats.voice_detected
1195 ? AudioFrame::kVadActive
1196 : AudioFrame::kVadPassive;
1197 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001198
aleloi868f32f2017-05-23 07:20:05 -07001199 if (aec_dump_) {
1200 RecordProcessedCaptureStream(*frame);
1201 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001202
1203 return kNoError;
1204}
1205
peahde65ddc2016-09-16 15:02:15 -07001206int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001207 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001208
peahb58a1582016-03-15 09:34:24 -07001209 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001210 // TODO(peah): Simplify once the public API Enable functions for these
1211 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001212 RTC_DCHECK_LE(
1213 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001214
peahde65ddc2016-09-16 15:02:15 -07001215 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001216 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001217
Per Åhgrenc0424252019-12-10 13:04:15 +01001218 if (submodules_.high_pass_filter &&
1219 config_.high_pass_filter.apply_in_full_band &&
1220 !constants_.enforce_split_band_hpf) {
1221 submodules_.high_pass_filter->Process(capture_buffer,
1222 /*use_split_band_data=*/false);
1223 }
1224
saza1d600522019-10-18 13:29:43 +02001225 if (submodules_.pre_amplifier) {
1226 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001227 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001228 capture_buffer->num_frames()));
1229 }
1230
Per Åhgren928146f2019-08-20 09:19:21 +02001231 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001232 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001233 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001234 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1235 if (log_rms) {
1236 capture_rms_interval_counter_ = 0;
1237 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001238 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1239 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1240 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1241 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001242 }
1243
saza1d600522019-10-18 13:29:43 +02001244 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001245 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001246 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001247 capture_.echo_path_gain_change =
1248 capture_.prev_analog_mic_level != analog_mic_level &&
1249 capture_.prev_analog_mic_level != -1;
1250 capture_.prev_analog_mic_level = analog_mic_level;
1251
Per Åhgrend2650d12018-10-02 17:00:59 +02001252 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001253 if (submodules_.pre_amplifier) {
1254 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001255 capture_.echo_path_gain_change =
1256 capture_.echo_path_gain_change ||
1257 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001258 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001259 capture_.prev_pre_amp_gain = pre_amp_gain;
1260 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001261
1262 // Detect volume change.
1263 capture_.echo_path_gain_change =
1264 capture_.echo_path_gain_change ||
1265 (capture_.prev_playout_volume != capture_.playout_volume &&
1266 capture_.prev_playout_volume >= 0);
1267 capture_.prev_playout_volume = capture_.playout_volume;
1268
saza1d600522019-10-18 13:29:43 +02001269 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001270 }
1271
Per Åhgren3daedb62019-11-22 12:11:40 +01001272 if (constants_.use_experimental_agc &&
1273 submodules_.gain_control->is_enabled()) {
1274 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001275 }
1276
peah2ace3f92016-09-10 04:42:27 -07001277 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1278 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001279 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1280 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001281 }
1282
Per Åhgrene14cb992019-11-27 09:34:22 +01001283 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1284 constants_.multi_channel_capture_support;
1285 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001286 // Force down-mixing of the number of channels after the detection of
1287 // capture signal saturation.
1288 // TODO(peah): Look into ensuring that this kind of tampering with the
1289 // AudioBuffer functionality should not be needed.
1290 capture_buffer->set_num_channels(1);
1291 }
1292
Per Åhgrenc0424252019-12-10 13:04:15 +01001293 if (submodules_.high_pass_filter &&
1294 (!config_.high_pass_filter.apply_in_full_band ||
1295 constants_.enforce_split_band_hpf)) {
1296 submodules_.high_pass_filter->Process(capture_buffer,
1297 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001298 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001299
Per Åhgrene35b32c2019-11-22 18:22:04 +01001300 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001301 RTC_DCHECK(
1302 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001303
1304 if (!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1305 !linear_aec_buffer || submodules_.echo_control_mobile) {
1306 if (submodules_.noise_suppressor) {
1307 submodules_.noise_suppressor->Analyze(*capture_buffer);
1308 } else if (submodules_.legacy_noise_suppressor) {
1309 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
1310 }
saza0bad15f2019-10-16 11:46:11 +02001311 }
peahb58a1582016-03-15 09:34:24 -07001312
saza1d600522019-10-18 13:29:43 +02001313 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001314 // Ensure that the stream delay was set before the call to the
1315 // AECM ProcessCaptureAudio function.
1316 if (!was_stream_delay_set()) {
1317 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001318 }
1319
saza1d600522019-10-18 13:29:43 +02001320 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001321 submodules_.noise_suppressor->Process(capture_buffer);
1322 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001323 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001324 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001325 }
peahe0eae3c2016-12-14 01:16:23 -08001326
saza1d600522019-10-18 13:29:43 +02001327 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001328 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001329 } else {
saza1d600522019-10-18 13:29:43 +02001330 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001331 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1332
1333 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001334 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001335 }
1336
saza1d600522019-10-18 13:29:43 +02001337 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001338 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001339 }
1340
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001341 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
1342 linear_aec_buffer) {
1343 if (submodules_.noise_suppressor) {
1344 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
1345 } else if (submodules_.legacy_noise_suppressor) {
1346 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(
1347 linear_aec_buffer);
1348 }
1349 }
1350
saza1d600522019-10-18 13:29:43 +02001351 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001352 submodules_.noise_suppressor->Process(capture_buffer);
1353 } else if (submodules_.legacy_noise_suppressor) {
1354 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001355 }
Per Åhgren46537a32017-06-07 10:08:10 +02001356 }
ivoc9f4a4a02016-10-28 05:39:16 -07001357
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001358 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001359 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001360 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001361 } else {
1362 capture_.stats.voice_detected = absl::nullopt;
1363 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001364
Per Åhgren3daedb62019-11-22 12:11:40 +01001365 if (constants_.use_experimental_agc &&
1366 submodules_.gain_control->is_enabled()) {
1367 submodules_.agc_manager->Process(capture_buffer);
1368
1369 absl::optional<int> new_digital_gain =
1370 submodules_.agc_manager->GetDigitalComressionGain();
1371 if (new_digital_gain) {
1372 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1373 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001374 }
Per Åhgren200feba2019-03-06 04:16:46 +01001375 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001376 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001377 capture_buffer, /*stream_has_echo*/ false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001378
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001379 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001380 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001381 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1382 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001383 }
1384
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001385 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001386 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001387 bool ec_active = ec ? ec->ActiveProcessing() : false;
1388 // Only update the fullband buffer if the multiband processing has changed
1389 // the signal. Keep the original signal otherwise.
1390 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1391 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1392 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001393 capture_buffer = capture_.capture_fullband_audio.get();
1394 }
1395
peah9e6a2902017-05-15 07:19:21 -07001396 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001397 RTC_DCHECK(submodules_.echo_detector);
1398 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1399 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001400 }
1401
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001402 // TODO(aluebs): Investigate if the transient suppression placement should be
1403 // before or after the AGC.
Per Åhgrenc0734712020-01-02 15:15:36 +01001404 if (submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001405 float voice_probability = submodules_.agc_manager.get()
1406 ? submodules_.agc_manager->voice_probability()
1407 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001408
saza1d600522019-10-18 13:29:43 +02001409 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001410 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001411 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001412 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001413 capture_buffer->num_frames_per_band(),
1414 capture_.keyboard_info.keyboard_data,
1415 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001416 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001417 }
1418
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001419 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001420 if (submodules_.capture_analyzer) {
1421 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001422 }
1423
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001424 if (submodules_.gain_controller2) {
saza1d600522019-10-18 13:29:43 +02001425 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001426 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001427 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001428 }
1429
saza1d600522019-10-18 13:29:43 +02001430 if (submodules_.capture_post_processor) {
1431 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001432 }
1433
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001434 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001435 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001436 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1437 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001438 } else {
1439 capture_.stats.output_rms_dbfs = absl::nullopt;
1440 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001441
Per Åhgren928146f2019-08-20 09:19:21 +02001442 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001443 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001444 capture_nonlocked_.capture_processing_format.num_frames()));
1445 if (log_rms) {
1446 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1447 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1448 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1449 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1450 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1451 }
1452
Per Åhgren0e3198e2019-11-18 08:52:22 +01001453 if (submodules_.agc_manager) {
1454 int level = recommended_stream_analog_level();
1455 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1456 &level);
1457 }
1458
Per Åhgrencf4c8722019-12-30 14:32:14 +01001459 // Compute echo-related stats.
1460 if (submodules_.echo_controller) {
1461 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1462 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1463 capture_.stats.echo_return_loss_enhancement =
1464 ec_metrics.echo_return_loss_enhancement;
1465 capture_.stats.delay_ms = ec_metrics.delay_ms;
1466 }
1467 if (config_.residual_echo_detector.enabled) {
1468 RTC_DCHECK(submodules_.echo_detector);
1469 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1470 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1471 capture_.stats.residual_echo_likelihood_recent_max =
1472 ed_metrics.echo_likelihood_recent_max;
1473 }
1474
1475 // Pass stats for reporting.
1476 stats_reporter_.UpdateStatistics(capture_.stats);
1477
peahdf3efa82015-11-28 12:35:15 -08001478 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001479 return kNoError;
1480}
1481
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001482int AudioProcessingImpl::AnalyzeReverseStream(
1483 const float* const* data,
1484 const StreamConfig& reverse_config) {
1485 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1486 rtc::CritScope cs(&crit_render_);
1487 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1488}
1489
peahde65ddc2016-09-16 15:02:15 -07001490int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1491 const StreamConfig& input_config,
1492 const StreamConfig& output_config,
1493 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001494 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001495 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001496 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001497 if (submodule_states_.RenderMultiBandProcessingActive() ||
1498 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001499 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1500 dest);
peah2ace3f92016-09-10 04:42:27 -07001501 } else if (formats_.api_format.reverse_input_stream() !=
1502 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001503 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1504 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001505 } else {
peahde65ddc2016-09-16 15:02:15 -07001506 CopyAudioIfNeeded(src, input_config.num_frames(),
1507 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001508 }
1509
1510 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001511}
1512
peahdf3efa82015-11-28 12:35:15 -08001513int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001514 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001515 const StreamConfig& input_config,
1516 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001517 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001518 return kNullPointerError;
1519 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001520
peahde65ddc2016-09-16 15:02:15 -07001521 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001522 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001523 }
1524
peahdf3efa82015-11-28 12:35:15 -08001525 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001526 processing_config.reverse_input_stream() = input_config;
1527 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001528
peahdf3efa82015-11-28 12:35:15 -08001529 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001530 RTC_DCHECK_EQ(input_config.num_frames(),
1531 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001532
aleloi868f32f2017-05-23 07:20:05 -07001533 if (aec_dump_) {
1534 const size_t channel_size =
1535 formats_.api_format.reverse_input_stream().num_frames();
1536 const size_t num_channels =
1537 formats_.api_format.reverse_input_stream().num_channels();
1538 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001539 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001540 }
peahdf3efa82015-11-28 12:35:15 -08001541 render_.render_audio->CopyFrom(src,
1542 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001543 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001544}
1545
1546int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001547 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001548 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001549 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001550 return kNullPointerError;
1551 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001552 // Must be a native rate.
1553 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1554 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001555 frame->sample_rate_hz_ != kSampleRate32kHz &&
1556 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001557 return kBadSampleRateError;
1558 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001559
Michael Graczyk86c6d332015-07-23 11:41:39 -07001560 if (frame->num_channels_ <= 0) {
1561 return kBadNumberChannelsError;
1562 }
1563
peahdf3efa82015-11-28 12:35:15 -08001564 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001565 processing_config.reverse_input_stream().set_sample_rate_hz(
1566 frame->sample_rate_hz_);
1567 processing_config.reverse_input_stream().set_num_channels(
1568 frame->num_channels_);
1569 processing_config.reverse_output_stream().set_sample_rate_hz(
1570 frame->sample_rate_hz_);
1571 processing_config.reverse_output_stream().set_num_channels(
1572 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001573
peahdf3efa82015-11-28 12:35:15 -08001574 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001575 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001576 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001577 return kBadDataLengthError;
1578 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001579
aleloi868f32f2017-05-23 07:20:05 -07001580 if (aec_dump_) {
1581 aec_dump_->WriteRenderStreamMessage(*frame);
1582 }
1583
Per Åhgrend47941e2019-08-22 11:51:13 +02001584 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001585 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001586 if (submodule_states_.RenderMultiBandProcessingActive() ||
1587 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001588 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001589 }
aluebsb0319552016-03-17 20:39:53 -07001590 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001591}
niklase@google.com470e71d2011-07-07 08:21:25 +00001592
peahde65ddc2016-09-16 15:02:15 -07001593int AudioProcessingImpl::ProcessRenderStreamLocked() {
1594 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001595
Alex Loiko73ec0192018-05-15 10:52:28 +02001596 HandleRenderRuntimeSettings();
1597
saza1d600522019-10-18 13:29:43 +02001598 if (submodules_.render_pre_processor) {
1599 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001600 }
1601
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001602 QueueNonbandedRenderAudio(render_buffer);
1603
peah2ace3f92016-09-10 04:42:27 -07001604 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001605 SampleRateSupportsMultiBand(
1606 formats_.render_processing_format.sample_rate_hz())) {
1607 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001608 }
1609
peahce4d9152017-05-19 01:28:05 -07001610 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1611 QueueBandedRenderAudio(render_buffer);
1612 }
1613
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001614 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001615 if (submodules_.echo_controller) {
1616 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001617 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001618
peah2ace3f92016-09-10 04:42:27 -07001619 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001620 SampleRateSupportsMultiBand(
1621 formats_.render_processing_format.sample_rate_hz())) {
1622 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001623 }
1624
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001625 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001626}
1627
1628int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001629 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001630 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001631 capture_.was_stream_delay_set = true;
1632 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001633
niklase@google.com470e71d2011-07-07 08:21:25 +00001634 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001635 delay = 0;
1636 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001637 }
1638
1639 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1640 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001641 delay = 500;
1642 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001643 }
1644
peahdf3efa82015-11-28 12:35:15 -08001645 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001646 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001647}
1648
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001649bool AudioProcessingImpl::GetLinearAecOutput(
1650 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1651 rtc::CritScope cs(&crit_capture_);
1652 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1653
1654 RTC_DCHECK(linear_aec_buffer);
1655 if (linear_aec_buffer) {
1656 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1657 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1658
1659 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1660 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1661 rtc::ArrayView<const float> channel_view =
1662 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1663 linear_aec_buffer->num_frames());
1664 std::copy(channel_view.begin(), channel_view.end(),
1665 linear_output[ch].begin());
1666 }
1667 return true;
1668 }
1669 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1670 RTC_NOTREACHED();
1671 return false;
1672}
1673
niklase@google.com470e71d2011-07-07 08:21:25 +00001674int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001675 // Used as callback from submodules, hence locking is not allowed.
1676 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001677}
1678
1679bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001680 // Used as callback from submodules, hence locking is not allowed.
1681 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001682}
1683
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001684void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001685 rtc::CritScope cs(&crit_capture_);
1686 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001687}
1688
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001689void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001690 rtc::CritScope cs(&crit_capture_);
1691 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001692}
1693
1694int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001695 rtc::CritScope cs(&crit_capture_);
1696 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001697}
1698
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001699void AudioProcessingImpl::set_stream_analog_level(int level) {
1700 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001701
1702 if (submodules_.agc_manager) {
1703 submodules_.agc_manager->set_stream_analog_level(level);
1704 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1705 1, &level);
1706 } else {
1707 int error = submodules_.gain_control->set_stream_analog_level(level);
1708 RTC_DCHECK_EQ(kNoError, error);
1709 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001710}
1711
1712int AudioProcessingImpl::recommended_stream_analog_level() const {
1713 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001714 if (submodules_.agc_manager) {
1715 return submodules_.agc_manager->stream_analog_level();
1716 }
1717 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001718}
1719
aleloi868f32f2017-05-23 07:20:05 -07001720void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1721 RTC_DCHECK(aec_dump);
1722 rtc::CritScope cs_render(&crit_render_);
1723 rtc::CritScope cs_capture(&crit_capture_);
1724
1725 // The previously attached AecDump will be destroyed with the
1726 // 'aec_dump' parameter, which is after locks are released.
1727 aec_dump_.swap(aec_dump);
1728 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001729 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001730}
1731
1732void AudioProcessingImpl::DetachAecDump() {
1733 // The d-tor of a task-queue based AecDump blocks until all pending
1734 // tasks are done. This construction avoids blocking while holding
1735 // the render and capture locks.
1736 std::unique_ptr<AecDump> aec_dump = nullptr;
1737 {
1738 rtc::CritScope cs_render(&crit_render_);
1739 rtc::CritScope cs_capture(&crit_capture_);
1740 aec_dump = std::move(aec_dump_);
1741 }
1742}
1743
Sam Zackrisson4d364492018-03-02 16:03:21 +01001744void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1745 std::unique_ptr<AudioGenerator> audio_generator) {
1746 // TODO(bugs.webrtc.org/8882) Stub.
1747 // Reset internal audio generator with audio_generator.
1748}
1749
1750void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1751 // TODO(bugs.webrtc.org/8882) Stub.
1752 // Delete audio generator, if one is attached.
1753}
1754
peah8271d042016-11-22 07:24:52 -08001755void AudioProcessingImpl::MutateConfig(
1756 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1757 rtc::CritScope cs_render(&crit_render_);
1758 rtc::CritScope cs_capture(&crit_capture_);
1759 mutator(&config_);
1760 ApplyConfig(config_);
1761}
1762
1763AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1764 rtc::CritScope cs_render(&crit_render_);
1765 rtc::CritScope cs_capture(&crit_capture_);
1766 return config_;
1767}
1768
peah2ace3f92016-09-10 04:42:27 -07001769bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1770 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001771 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
1772 config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001773 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001774 submodules_.gain_control->is_enabled(), !!submodules_.gain_controller2,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001775 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
Per Åhgrenc0734712020-01-02 15:15:36 +01001776 config_.voice_detection.enabled, !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001777}
1778
Per Åhgrenc0734712020-01-02 15:15:36 +01001779void AudioProcessingImpl::InitializeTransientSuppressor() {
1780 if (config_.transient_suppression.enabled) {
1781 if (!submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001782 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001783 }
saza1d600522019-10-18 13:29:43 +02001784 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1785 capture_nonlocked_.split_rate,
1786 num_proc_channels());
Per Åhgrenc0734712020-01-02 15:15:36 +01001787 } else {
1788 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001789 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001790}
1791
Per Åhgren0f14db22020-01-03 14:27:14 +01001792void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01001793 bool high_pass_filter_needed_by_aec =
1794 config_.echo_canceller.enabled &&
1795 config_.echo_canceller.enforce_high_pass_filtering &&
1796 !config_.echo_canceller.mobile_mode;
1797 if (submodule_states_.HighPassFilteringRequired() ||
1798 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001799 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1800 !constants_.enforce_split_band_hpf;
1801 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1802 : proc_split_sample_rate_hz();
1803 size_t num_channels =
1804 use_full_band ? num_output_channels() : num_proc_channels();
1805
Per Åhgren0f14db22020-01-03 14:27:14 +01001806 if (!submodules_.high_pass_filter ||
1807 rate != submodules_.high_pass_filter->sample_rate_hz() ||
1808 forced_reset ||
1809 num_channels != submodules_.high_pass_filter->num_channels()) {
1810 submodules_.high_pass_filter.reset(
1811 new HighPassFilter(rate, num_channels));
1812 }
peah8271d042016-11-22 07:24:52 -08001813 } else {
saza1d600522019-10-18 13:29:43 +02001814 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001815 }
1816}
alessiob3ec96df2017-05-22 06:57:06 -07001817
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001818void AudioProcessingImpl::InitializeVoiceDetector() {
1819 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001820 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001821 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1822 } else {
saza1d600522019-10-18 13:29:43 +02001823 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001824 }
1825}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001826void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001827 bool use_echo_controller =
1828 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001829 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001830
1831 if (use_echo_controller) {
1832 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001833 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001834 submodules_.echo_controller = echo_control_factory_->Create(
1835 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001836 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001837 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001838 EchoCanceller3Config config =
1839 use_setup_specific_default_aec3_config_
1840 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1841 num_proc_channels())
1842 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001843 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001844 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001845 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001846 }
1847
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001848 // Setup the storage for returning the linear AEC output.
1849 if (config_.echo_canceller.export_linear_aec_output) {
1850 constexpr int kLinearOutputRateHz = 16000;
1851 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1852 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1853 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1854 } else {
1855 capture_.linear_aec_output.reset();
1856 }
1857
Per Åhgren200feba2019-03-06 04:16:46 +01001858 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001859
saza1d600522019-10-18 13:29:43 +02001860 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001861 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001862 return;
peahe0eae3c2016-12-14 01:16:23 -08001863 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001864
saza1d600522019-10-18 13:29:43 +02001865 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001866 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001867 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001868
1869 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001870 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001871 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001872 return;
1873 }
1874
1875 if (config_.echo_canceller.mobile_mode) {
1876 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001877 size_t max_element_size =
1878 std::max(static_cast<size_t>(1),
1879 kMaxAllowedValuesOfSamplesPerBand *
1880 EchoControlMobileImpl::NumCancellersRequired(
1881 num_output_channels(), num_reverse_channels()));
1882
1883 std::vector<int16_t> template_queue_element(max_element_size);
1884
1885 aecm_render_signal_queue_.reset(
1886 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1887 kMaxNumFramesToBuffer, template_queue_element,
1888 RenderQueueItemVerifier<int16_t>(max_element_size)));
1889
1890 aecm_render_queue_buffer_.resize(max_element_size);
1891 aecm_capture_queue_buffer_.resize(max_element_size);
1892
saza1d600522019-10-18 13:29:43 +02001893 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001894
saza1d600522019-10-18 13:29:43 +02001895 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1896 num_reverse_channels(),
1897 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001898 return;
1899 }
1900
saza1d600522019-10-18 13:29:43 +02001901 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001902 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001903}
peah8271d042016-11-22 07:24:52 -08001904
alessiob3ec96df2017-05-22 06:57:06 -07001905void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001906 if (config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001907 if (!submodules_.gain_controller2) {
1908 // TODO(alessiob): Move the injected gain controller once injection is
1909 // implemented.
1910 submodules_.gain_controller2.reset(new GainController2());
1911 }
1912
saza1d600522019-10-18 13:29:43 +02001913 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001914 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
1915 } else {
1916 submodules_.gain_controller2.reset();
alessiob3ec96df2017-05-22 06:57:06 -07001917 }
1918}
1919
saza0bad15f2019-10-16 11:46:11 +02001920void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001921 submodules_.legacy_noise_suppressor.reset();
1922 submodules_.noise_suppressor.reset();
1923
saza0bad15f2019-10-16 11:46:11 +02001924 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001925 const bool use_legacy_ns =
1926 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1927
1928 if (!use_legacy_ns) {
1929 auto map_level =
1930 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1931 using NoiseSuppresionConfig =
1932 AudioProcessing::Config::NoiseSuppression;
1933 switch (level) {
1934 case NoiseSuppresionConfig::kLow:
1935 return NsConfig::SuppressionLevel::k6dB;
1936 case NoiseSuppresionConfig::kModerate:
1937 return NsConfig::SuppressionLevel::k12dB;
1938 case NoiseSuppresionConfig::kHigh:
1939 return NsConfig::SuppressionLevel::k18dB;
1940 case NoiseSuppresionConfig::kVeryHigh:
1941 return NsConfig::SuppressionLevel::k21dB;
1942 default:
1943 RTC_NOTREACHED();
1944 }
1945 };
1946
1947 NsConfig cfg;
1948 cfg.target_level = map_level(config_.noise_suppression.level);
1949 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1950 cfg, proc_sample_rate_hz(), num_proc_channels());
1951 } else {
1952 auto ns_level =
1953 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1954 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1955 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1956 }
saza0bad15f2019-10-16 11:46:11 +02001957 }
1958}
1959
Alex Loikob5c9a792018-04-16 16:31:22 +02001960void AudioProcessingImpl::InitializePreAmplifier() {
1961 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001962 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001963 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1964 } else {
saza1d600522019-10-18 13:29:43 +02001965 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001966 }
1967}
1968
ivoc9f4a4a02016-10-28 05:39:16 -07001969void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001970 RTC_DCHECK(submodules_.echo_detector);
1971 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001972 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001973 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001974}
1975
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001976void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001977 if (submodules_.capture_analyzer) {
1978 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1979 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001980 }
1981}
1982
Sam Zackrisson0beac582017-09-25 12:04:02 +02001983void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001984 if (submodules_.capture_post_processor) {
1985 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001986 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001987 }
1988}
1989
Alex Loiko5825aa62017-12-18 16:02:40 +01001990void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001991 if (submodules_.render_pre_processor) {
1992 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001993 formats_.render_processing_format.sample_rate_hz(),
1994 formats_.render_processing_format.num_channels());
1995 }
1996}
1997
Per Åhgrenea4c5df2019-05-03 09:00:08 +02001998void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001999
aleloi868f32f2017-05-23 07:20:05 -07002000void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2001 if (!aec_dump_) {
2002 return;
2003 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002004
2005 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002006 // TODO(peah): Add semicolon-separated concatenations of experiment
2007 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002008 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2009 experiments_description += "AgcClippingLevelExperiment;";
2010 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002011 if (capture_nonlocked_.echo_controller_enabled) {
2012 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002013 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002014 if (config_.gain_controller2.enabled) {
2015 experiments_description += "GainController2;";
2016 }
aleloi868f32f2017-05-23 07:20:05 -07002017
2018 InternalAPMConfig apm_config;
2019
Per Åhgren200feba2019-03-06 04:16:46 +01002020 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002021 apm_config.aec_delay_agnostic_enabled = false;
2022 apm_config.aec_extended_filter_enabled = false;
2023 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002024
saza1d600522019-10-18 13:29:43 +02002025 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002026 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002027 submodules_.echo_control_mobile &&
2028 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002029 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002030 submodules_.echo_control_mobile
2031 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002032 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002033
saza1d600522019-10-18 13:29:43 +02002034 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
2035 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07002036 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02002037 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01002038 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002039
2040 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2041
saza0bad15f2019-10-16 11:46:11 +02002042 apm_config.ns_enabled = config_.noise_suppression.enabled;
2043 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002044
2045 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002046 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002047 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002048 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2049 apm_config.pre_amplifier_fixed_gain_factor =
2050 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002051
2052 if (!forced && apm_config == apm_config_for_aec_dump_) {
2053 return;
2054 }
2055 aec_dump_->WriteConfig(apm_config);
2056 apm_config_for_aec_dump_ = apm_config;
2057}
2058
2059void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2060 const float* const* src) {
2061 RTC_DCHECK(aec_dump_);
2062 WriteAecDumpConfigMessage(false);
2063
2064 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2065 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2066 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002067 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002068 RecordAudioProcessingState();
2069}
2070
2071void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2072 const AudioFrame& capture_frame) {
2073 RTC_DCHECK(aec_dump_);
2074 WriteAecDumpConfigMessage(false);
2075
2076 aec_dump_->AddCaptureStreamInput(capture_frame);
2077 RecordAudioProcessingState();
2078}
2079
2080void AudioProcessingImpl::RecordProcessedCaptureStream(
2081 const float* const* processed_capture_stream) {
2082 RTC_DCHECK(aec_dump_);
2083
2084 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2085 const size_t num_channels =
2086 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002087 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2088 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002089 aec_dump_->WriteCaptureStreamMessage();
2090}
2091
2092void AudioProcessingImpl::RecordProcessedCaptureStream(
2093 const AudioFrame& processed_capture_frame) {
2094 RTC_DCHECK(aec_dump_);
2095
2096 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2097 aec_dump_->WriteCaptureStreamMessage();
2098}
2099
2100void AudioProcessingImpl::RecordAudioProcessingState() {
2101 RTC_DCHECK(aec_dump_);
2102 AecDump::AudioProcessingState audio_proc_state;
2103 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002104 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002105 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002106 audio_proc_state.keypress = capture_.key_pressed;
2107 aec_dump_->AddAudioProcessingState(audio_proc_state);
2108}
2109
Per Åhgrenc0734712020-01-02 15:15:36 +01002110AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002111 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002112 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002113 output_will_be_muted(false),
2114 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002115 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002116 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002117 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002118 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002119 prev_pre_amp_gain(-1.f),
2120 playout_volume(-1),
2121 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002122
2123AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2124
Per Åhgrena1351272019-08-15 12:15:46 +02002125void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2126 const float* const* data,
2127 const StreamConfig& stream_config) {
2128 if (stream_config.has_keyboard()) {
2129 keyboard_data = data[stream_config.num_channels()];
2130 } else {
2131 keyboard_data = NULL;
2132 }
2133 num_keyboard_frames = stream_config.num_frames();
2134}
2135
kwiberg83ffe452016-08-29 14:46:07 -07002136AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2137
2138AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2139
Per Åhgrencf4c8722019-12-30 14:32:14 +01002140AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2141 : stats_message_queue_(1) {}
2142
2143AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2144
2145AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
2146 rtc::CritScope cs_stats(&crit_stats_);
2147 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2148 // If the message queue is full, return the cached stats.
2149 static_cast<void>(new_stats_available);
2150
2151 return cached_stats_;
2152}
2153
2154void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2155 const AudioProcessingStats& new_stats) {
2156 AudioProcessingStats stats_to_queue = new_stats;
2157 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2158 // If the message queue is full, discard the new stats.
2159 static_cast<void>(stats_message_passed);
2160}
2161
niklase@google.com470e71d2011-07-07 08:21:25 +00002162} // namespace webrtc