blob: d544304070d0d4a4b16ae4bfd42c4695e94d75b3 [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 Åhgrenb2b58d82019-12-02 14:59:40 +010078// Checks whether AEC3 should be allowed to decide what the default
79// configuration should be based on the render and capture channel configuration
80// at hand.
81bool UseSetupSpecificDefaultAec3Congfig() {
82 return !field_trial::IsEnabled(
83 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
84}
85
Per Åhgrenc8626b62019-08-23 15:49:51 +020086// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020087int SuitableProcessRate(int minimum_rate,
88 int max_splitting_rate,
89 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020090 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020091 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020092 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070093 if (rate >= uppermost_native_rate) {
94 return uppermost_native_rate;
95 }
96 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070097 return rate;
98 }
99 }
peah2ace3f92016-09-10 04:42:27 -0700100 RTC_NOTREACHED();
101 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700102}
103
Sam Zackrisson23513132019-01-11 15:10:32 +0100104NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
105 AudioProcessing::Config::NoiseSuppression::Level level) {
106 using NsConfig = AudioProcessing::Config::NoiseSuppression;
107 switch (level) {
108 case NsConfig::kLow:
saza0bad15f2019-10-16 11:46:11 +0200109 return NoiseSuppression::Level::kLow;
Sam Zackrisson23513132019-01-11 15:10:32 +0100110 case NsConfig::kModerate:
saza0bad15f2019-10-16 11:46:11 +0200111 return NoiseSuppression::Level::kModerate;
Sam Zackrisson23513132019-01-11 15:10:32 +0100112 case NsConfig::kHigh:
saza0bad15f2019-10-16 11:46:11 +0200113 return NoiseSuppression::Level::kHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100114 case NsConfig::kVeryHigh:
saza0bad15f2019-10-16 11:46:11 +0200115 return NoiseSuppression::Level::kVeryHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100116 default:
117 RTC_NOTREACHED();
118 }
119}
120
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100121GainControl::Mode Agc1ConfigModeToInterfaceMode(
122 AudioProcessing::Config::GainController1::Mode mode) {
123 using Agc1Config = AudioProcessing::Config::GainController1;
124 switch (mode) {
125 case Agc1Config::kAdaptiveAnalog:
126 return GainControl::kAdaptiveAnalog;
127 case Agc1Config::kAdaptiveDigital:
128 return GainControl::kAdaptiveDigital;
129 case Agc1Config::kFixedDigital:
130 return GainControl::kFixedDigital;
131 }
132}
133
peah9e6a2902017-05-15 07:19:21 -0700134// Maximum lengths that frame of samples being passed from the render side to
135// the capture side can have (does not apply to AEC3).
136static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
137static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
138
peah764e3642016-10-22 05:04:30 -0700139// Maximum number of frames to buffer in the render queue.
140// TODO(peah): Decrease this once we properly handle hugely unbalanced
141// reverse and forward call numbers.
142static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700143} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000144
145// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000146static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000147
saza1d600522019-10-18 13:29:43 +0200148AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100149 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200150 bool render_pre_processor_enabled,
151 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100152 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200153 render_pre_processor_enabled_(render_pre_processor_enabled),
154 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700155
saza1d600522019-10-18 13:29:43 +0200156bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200157 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700158 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700159 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700160 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700161 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700162 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200163 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200164 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200165 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool transient_suppressor_enabled) {
167 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200168 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700169 changed |=
170 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700171 changed |=
172 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700173 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
174 changed |=
peah2ace3f92016-09-10 04:42:27 -0700175 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200176 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200177 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200178 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200179 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700180 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
181 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200182 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700183 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700184 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700185 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700186 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700187 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200188 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200189 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200190 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700191 transient_suppressor_enabled_ = transient_suppressor_enabled;
192 }
193
194 changed |= first_update_;
195 first_update_ = false;
196 return changed;
197}
198
saza1d600522019-10-18 13:29:43 +0200199bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700200 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200201 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700202}
203
saza1d600522019-10-18 13:29:43 +0200204bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
205 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200206 // If echo controller is present, assume it performs active processing.
207 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
208}
209
saza1d600522019-10-18 13:29:43 +0200210bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200211 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100212 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
213 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200214 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700215}
216
saza1d600522019-10-18 13:29:43 +0200217bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700218 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200219 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
220 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700221}
222
saza1d600522019-10-18 13:29:43 +0200223bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200224 return capture_analyzer_enabled_;
225}
226
saza1d600522019-10-18 13:29:43 +0200227bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700228 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100229 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
230 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700231}
232
saza1d600522019-10-18 13:29:43 +0200233bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100234 const {
235 return render_pre_processor_enabled_;
236}
237
saza1d600522019-10-18 13:29:43 +0200238bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700239 const {
peah2ace3f92016-09-10 04:42:27 -0700240 return false;
peah2ace3f92016-09-10 04:42:27 -0700241}
242
saza1d600522019-10-18 13:29:43 +0200243bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100244 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
245 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200246}
247
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100248AudioProcessingBuilder::AudioProcessingBuilder() = default;
249AudioProcessingBuilder::~AudioProcessingBuilder() = default;
250
251AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
252 std::unique_ptr<CustomProcessing> capture_post_processing) {
253 capture_post_processing_ = std::move(capture_post_processing);
254 return *this;
255}
256
257AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
258 std::unique_ptr<CustomProcessing> render_pre_processing) {
259 render_pre_processing_ = std::move(render_pre_processing);
260 return *this;
261}
262
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200263AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
264 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
265 capture_analyzer_ = std::move(capture_analyzer);
266 return *this;
267}
268
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100269AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
270 std::unique_ptr<EchoControlFactory> echo_control_factory) {
271 echo_control_factory_ = std::move(echo_control_factory);
272 return *this;
273}
274
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100275AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200276 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100277 echo_detector_ = std::move(echo_detector);
278 return *this;
279}
280
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100281AudioProcessing* AudioProcessingBuilder::Create() {
282 webrtc::Config config;
283 return Create(config);
284}
285
286AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100287 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
288 config, std::move(capture_post_processing_),
289 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200290 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100291 if (apm->Initialize() != AudioProcessing::kNoError) {
292 delete apm;
293 apm = nullptr;
294 }
295 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100296}
297
peah88ac8532016-09-12 16:47:25 -0700298AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200299 : AudioProcessingImpl(config,
300 /*capture_post_processor=*/nullptr,
301 /*render_pre_processor=*/nullptr,
302 /*echo_control_factory=*/nullptr,
303 /*echo_detector=*/nullptr,
304 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000305
Per Åhgren13735822018-02-12 21:42:56 +0100306int AudioProcessingImpl::instance_count_ = 0;
307
Sam Zackrisson0beac582017-09-25 12:04:02 +0200308AudioProcessingImpl::AudioProcessingImpl(
309 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100310 std::unique_ptr<CustomProcessing> capture_post_processor,
311 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200312 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200313 rtc::scoped_refptr<EchoDetector> echo_detector,
314 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100315 : data_dumper_(
316 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgren0cbb58e2019-10-29 22:59:44 +0100317 enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100318 use_setup_specific_default_aec3_config_(
319 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200320 capture_runtime_settings_(kRuntimeSettingQueueSize),
321 render_runtime_settings_(kRuntimeSettingQueueSize),
322 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
323 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200324 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200325 submodule_states_(!!capture_post_processor,
326 !!render_pre_processor,
327 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200328 submodules_(std::move(capture_post_processor),
329 std::move(render_pre_processor),
330 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100331 std::move(capture_analyzer)),
332 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
333 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000334#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Per Åhgren3daedb62019-11-22 12:11:40 +0100335 /* enabled= */ false,
336 /* enabled_agc2_level_estimator= */ false,
337 /* digital_adaptive_disabled= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000338#else
Per Åhgren3daedb62019-11-22 12:11:40 +0100339 config.Get<ExperimentalAgc>().enabled,
340 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
341 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000342#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200343 !field_trial::IsEnabled(
344 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
345 !field_trial::IsEnabled(
346 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700347#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200348 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700349#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200350 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700351#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200352 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200353 RTC_LOG(LS_INFO) << "Injected APM submodules:"
354 << "\nEcho control factory: " << !!echo_control_factory_
355 << "\nEcho detector: " << !!submodules_.echo_detector
356 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
357 << "\nCapture post processor: "
358 << !!submodules_.capture_post_processor
359 << "\nRender pre processor: "
360 << !!submodules_.render_pre_processor;
361
Sam Zackrisson421c8592019-02-11 13:39:46 +0100362 // Mark Echo Controller enabled if a factory is injected.
363 capture_nonlocked_.echo_controller_enabled =
364 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000365
saza1d600522019-10-18 13:29:43 +0200366 submodules_.gain_control.reset(new GainControlImpl());
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200367
Sam Zackrisson421c8592019-02-11 13:39:46 +0100368 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200369 if (!submodules_.echo_detector) {
370 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100371 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800372 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000373
Sam Zackrisson421c8592019-02-11 13:39:46 +0100374 // TODO(alessiob): Move the injected gain controller once injection is
375 // implemented.
saza1d600522019-10-18 13:29:43 +0200376 submodules_.gain_controller2.reset(new GainController2());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100377
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000378 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000379}
380
Per Åhgren0e3198e2019-11-18 08:52:22 +0100381AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000382
niklase@google.com470e71d2011-07-07 08:21:25 +0000383int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800384 // Run in a single-threaded manner during initialization.
385 rtc::CritScope cs_render(&crit_render_);
386 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000387 return InitializeLocked();
388}
389
peahde65ddc2016-09-16 15:02:15 -0700390int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
391 int capture_output_sample_rate_hz,
392 int render_input_sample_rate_hz,
393 ChannelLayout capture_input_layout,
394 ChannelLayout capture_output_layout,
395 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700396 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700397 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
398 LayoutHasKeyboard(capture_input_layout)},
399 {capture_output_sample_rate_hz,
400 ChannelsFromLayout(capture_output_layout),
401 LayoutHasKeyboard(capture_output_layout)},
402 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
403 LayoutHasKeyboard(render_input_layout)},
404 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
405 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700406
407 return Initialize(processing_config);
408}
409
410int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800411 // Run in a single-threaded manner during initialization.
412 rtc::CritScope cs_render(&crit_render_);
413 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700414 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000415}
416
peahdf3efa82015-11-28 12:35:15 -0800417int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800418 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800419 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200420 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800421 return kNoError;
422 }
peahdf3efa82015-11-28 12:35:15 -0800423
424 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800425 return InitializeLocked(processing_config);
426}
427
niklase@google.com470e71d2011-07-07 08:21:25 +0000428int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200429 UpdateActiveSubmoduleStates();
430
Per Åhgrend47941e2019-08-22 11:51:13 +0200431 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800432 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200433 ? formats_.render_processing_format.sample_rate_hz()
434 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800435 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
436 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200437 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800438 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200439 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700440 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200441 render_audiobuffer_sample_rate_hz,
442 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700443 if (formats_.api_format.reverse_input_stream() !=
444 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800445 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800446 formats_.api_format.reverse_input_stream().num_channels(),
447 formats_.api_format.reverse_input_stream().num_frames(),
448 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800449 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700450 } else {
peahdf3efa82015-11-28 12:35:15 -0800451 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700452 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700453 } else {
peahdf3efa82015-11-28 12:35:15 -0800454 render_.render_audio.reset(nullptr);
455 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700456 }
peahce4d9152017-05-19 01:28:05 -0700457
Per Åhgrend47941e2019-08-22 11:51:13 +0200458 capture_.capture_audio.reset(new AudioBuffer(
459 formats_.api_format.input_stream().sample_rate_hz(),
460 formats_.api_format.input_stream().num_channels(),
461 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
462 formats_.api_format.output_stream().num_channels(),
463 formats_.api_format.output_stream().sample_rate_hz(),
464 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000465
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200466 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
467 formats_.api_format.output_stream().sample_rate_hz() &&
468 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
469 capture_.capture_fullband_audio.reset(
470 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
471 formats_.api_format.input_stream().num_channels(),
472 formats_.api_format.output_stream().sample_rate_hz(),
473 formats_.api_format.output_stream().num_channels(),
474 formats_.api_format.output_stream().sample_rate_hz(),
475 formats_.api_format.output_stream().num_channels()));
476 } else {
477 capture_.capture_fullband_audio.reset();
478 }
479
peah764e3642016-10-22 05:04:30 -0700480 AllocateRenderQueue();
481
saza1d600522019-10-18 13:29:43 +0200482 submodules_.gain_control->Initialize(num_proc_channels(),
483 proc_sample_rate_hz());
Per Åhgren3daedb62019-11-22 12:11:40 +0100484 if (constants_.use_experimental_agc) {
485 if (!submodules_.agc_manager.get() ||
486 submodules_.agc_manager->num_channels() !=
487 static_cast<int>(num_proc_channels()) ||
488 submodules_.agc_manager->sample_rate_hz() !=
489 capture_nonlocked_.split_rate) {
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100490 int stream_analog_level = -1;
491 const bool re_creation = !!submodules_.agc_manager;
492 if (re_creation) {
493 stream_analog_level = submodules_.agc_manager->stream_analog_level();
494 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100495 submodules_.agc_manager.reset(new AgcManagerDirect(
496 num_proc_channels(), constants_.agc_startup_min_volume,
497 constants_.agc_clipped_level_min,
498 constants_.use_experimental_agc_agc2_level_estimation,
499 constants_.use_experimental_agc_agc2_digital_adaptive,
500 capture_nonlocked_.split_rate));
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100501 if (re_creation) {
502 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
503 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100504 }
saza1d600522019-10-18 13:29:43 +0200505 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 12:11:40 +0100506 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 08:52:22 +0100507 submodules_.gain_control.get());
saza1d600522019-10-18 13:29:43 +0200508 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 15:02:15 -0700509 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200510 InitializeTransient();
Per Åhgren4011de02019-12-03 11:48:48 +0000511 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200512 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700513 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200514 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700515 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200516 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200517 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200518 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100519 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800520
aleloi868f32f2017-05-23 07:20:05 -0700521 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200522 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700523 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000524 return kNoError;
525}
526
Michael Graczyk86c6d332015-07-23 11:41:39 -0700527int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200528 UpdateActiveSubmoduleStates();
529
Michael Graczyk86c6d332015-07-23 11:41:39 -0700530 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700531 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
532 return kBadSampleRateError;
533 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000534 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700535
Peter Kasting69558702016-01-12 16:26:35 -0800536 const size_t num_in_channels = config.input_stream().num_channels();
537 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700538
539 // Need at least one input channel.
540 // Need either one output channel or as many outputs as there are inputs.
541 if (num_in_channels == 0 ||
542 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700543 return kBadNumberChannelsError;
544 }
545
peahdf3efa82015-11-28 12:35:15 -0800546 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000547
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200548 // Choose maximum rate to use for the split filtering.
549 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
550 config_.pipeline.maximum_internal_processing_rate == 32000);
551 int max_splitting_rate = 48000;
552 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
553 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
554 }
555
Per Åhgrenc8626b62019-08-23 15:49:51 +0200556 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700557 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700558 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200559 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700560 submodule_states_.CaptureMultiBandSubModulesActive() ||
561 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200562 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000563
peahde65ddc2016-09-16 15:02:15 -0700564 capture_nonlocked_.capture_processing_format =
565 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700566
peah2ce640f2017-04-07 03:57:48 -0700567 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200568 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200569 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700570 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
571 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200572 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700573 submodule_states_.CaptureMultiBandSubModulesActive() ||
574 submodule_states_.RenderMultiBandSubModulesActive());
575 } else {
576 render_processing_rate = capture_processing_rate;
577 }
578
peahde65ddc2016-09-16 15:02:15 -0700579 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700580 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700581 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
582 kSampleRate8kHz) {
583 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000584 } else {
peahde65ddc2016-09-16 15:02:15 -0700585 render_processing_rate =
586 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000587 }
588
Per Åhgrenc8626b62019-08-23 15:49:51 +0200589 RTC_DCHECK_NE(8000, render_processing_rate);
590
peahce4d9152017-05-19 01:28:05 -0700591 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200592 // By default, downmix the render stream to mono for analysis. This has been
593 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100594 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
595 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200596 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100597 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200598 ? formats_.api_format.reverse_input_stream().num_channels()
599 : 1;
600 formats_.render_processing_format =
601 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700602 } else {
603 formats_.render_processing_format = StreamConfig(
604 formats_.api_format.reverse_input_stream().sample_rate_hz(),
605 formats_.api_format.reverse_input_stream().num_channels());
606 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000607
peahde65ddc2016-09-16 15:02:15 -0700608 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
609 kSampleRate32kHz ||
610 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
611 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800612 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000613 } else {
peahdf3efa82015-11-28 12:35:15 -0800614 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700615 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000616 }
617
618 return InitializeLocked();
619}
620
peah88ac8532016-09-12 16:47:25 -0700621void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200622 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
623
peah88ac8532016-09-12 16:47:25 -0700624 // Run in a single-threaded manner when applying the settings.
625 rtc::CritScope cs_render(&crit_render_);
626 rtc::CritScope cs_capture(&crit_capture_);
627
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200628 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100629 config_.pipeline.multi_channel_render !=
630 config.pipeline.multi_channel_render ||
631 config_.pipeline.multi_channel_capture !=
632 config.pipeline.multi_channel_capture;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200633
Per Åhgren200feba2019-03-06 04:16:46 +0100634 const bool aec_config_changed =
635 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100636 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100637
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100638 const bool agc1_config_changed =
639 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
640 config_.gain_controller1.mode != config.gain_controller1.mode ||
641 config_.gain_controller1.target_level_dbfs !=
642 config.gain_controller1.target_level_dbfs ||
643 config_.gain_controller1.compression_gain_db !=
644 config.gain_controller1.compression_gain_db ||
645 config_.gain_controller1.enable_limiter !=
646 config.gain_controller1.enable_limiter ||
647 config_.gain_controller1.analog_level_minimum !=
648 config.gain_controller1.analog_level_minimum ||
649 config_.gain_controller1.analog_level_maximum !=
650 config.gain_controller1.analog_level_maximum;
651
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200652 const bool voice_detection_config_changed =
653 config_.voice_detection.enabled != config.voice_detection.enabled;
654
saza0bad15f2019-10-16 11:46:11 +0200655 const bool ns_config_changed =
656 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
657 config_.noise_suppression.level != config.noise_suppression.level;
658
Yves Gerey499bc6c2018-10-10 18:29:07 +0200659 config_ = config;
660
Per Åhgren200feba2019-03-06 04:16:46 +0100661 if (aec_config_changed) {
662 InitializeEchoController();
663 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200664
saza0bad15f2019-10-16 11:46:11 +0200665 if (ns_config_changed) {
666 InitializeNoiseSuppressor();
667 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100668
Per Åhgren4011de02019-12-03 11:48:48 +0000669 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800670
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100671 if (agc1_config_changed) {
672 ApplyAgc1Config(config_.gain_controller1);
673 }
674
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100675 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700676 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100677 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
678 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100679 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100680 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700681 config_.gain_controller2 = AudioProcessing::Config::GainController2();
682 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200683 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200684 InitializePreAmplifier();
saza1d600522019-10-18 13:29:43 +0200685 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100686
saza1d600522019-10-18 13:29:43 +0200687 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
688 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100689 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100690
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200691 if (voice_detection_config_changed) {
692 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100693 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200694
695 // Reinitialization must happen after all submodule configuration to avoid
696 // additional reinitializations on the next capture / render processing call.
697 if (pipeline_config_changed) {
698 InitializeLocked(formats_.api_format);
699 }
peah88ac8532016-09-12 16:47:25 -0700700}
701
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100702void AudioProcessingImpl::ApplyAgc1Config(
703 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100704 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100705 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100706
Per Åhgren0e3198e2019-11-18 08:52:22 +0100707 if (!submodules_.agc_manager) {
708 error = submodules_.gain_control->set_mode(
709 Agc1ConfigModeToInterfaceMode(config.mode));
710 RTC_DCHECK_EQ(kNoError, error);
711 error = submodules_.gain_control->set_target_level_dbfs(
712 config.target_level_dbfs);
713 RTC_DCHECK_EQ(kNoError, error);
714 error = submodules_.gain_control->set_compression_gain_db(
715 config.compression_gain_db);
716 RTC_DCHECK_EQ(kNoError, error);
717 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
718 RTC_DCHECK_EQ(kNoError, error);
719 error = submodules_.gain_control->set_analog_level_limits(
720 config.analog_level_minimum, config.analog_level_maximum);
721 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100722 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100723}
724
peah88ac8532016-09-12 16:47:25 -0700725void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800726 // Run in a single-threaded manner when setting the extra options.
727 rtc::CritScope cs_render(&crit_render_);
728 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000729
peahdf3efa82015-11-28 12:35:15 -0800730 if (capture_.transient_suppressor_enabled !=
731 config.Get<ExperimentalNs>().enabled) {
732 capture_.transient_suppressor_enabled =
733 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000734 InitializeTransient();
735 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000736}
737
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000738int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800739 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700740 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000741}
742
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200743int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
744 return capture_.capture_fullband_audio
745 ? capture_.capture_fullband_audio->num_frames() * 100
746 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
747}
748
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000749int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800750 // Used as callback from submodules, hence locking is not allowed.
751 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000752}
753
Peter Kasting69558702016-01-12 16:26:35 -0800754size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800755 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700756 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000757}
758
Peter Kasting69558702016-01-12 16:26:35 -0800759size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800760 // Used as callback from submodules, hence locking is not allowed.
761 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000762}
763
Peter Kasting69558702016-01-12 16:26:35 -0800764size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800765 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100766 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
767 constants_.multi_channel_capture_support;
768 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200769 return 1;
770 }
771 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800772}
773
Peter Kasting69558702016-01-12 16:26:35 -0800774size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800775 // Used as callback from submodules, hence locking is not allowed.
776 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000777}
778
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000779void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800780 rtc::CritScope cs(&crit_capture_);
781 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200782 if (submodules_.agc_manager.get()) {
783 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000784 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000785}
786
Alessio Bazzicac054e782018-04-16 12:10:09 +0200787void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200788 switch (setting.type()) {
789 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100790 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200791 render_runtime_settings_enqueuer_.Enqueue(setting);
792 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200793 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100794 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200795 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100796 capture_runtime_settings_enqueuer_.Enqueue(setting);
797 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200798 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200799 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100800 render_runtime_settings_enqueuer_.Enqueue(setting);
801 return;
802 case RuntimeSetting::Type::kNotSpecified:
803 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200804 return;
805 }
806 // The language allows the enum to have a non-enumerator
807 // value. Check that this doesn't happen.
808 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200809}
810
811AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
812 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200813 : runtime_settings_(*runtime_settings) {
814 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200815}
816
817AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
818 default;
819
820void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
821 RuntimeSetting setting) {
822 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200823 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200824 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200825 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200826 RTC_LOG(LS_ERROR)
827 << "The runtime settings queue is full. Oldest setting discarded.";
828 }
829 if (remaining_attempts == 0)
830 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
831}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000832
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000833int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700834 const StreamConfig& input_config,
835 const StreamConfig& output_config,
836 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800837 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800838 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700839 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800840 {
841 // Acquire the capture lock in order to safely call the function
842 // that retrieves the render side data. This function accesses apm
843 // getters that need the capture lock held when being called.
844 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700845 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800846
847 if (!src || !dest) {
848 return kNullPointerError;
849 }
850
851 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700852 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000853 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000854
Oskar Sundbom4b276482019-05-23 14:28:00 +0200855 if (processing_config.input_stream() != input_config) {
856 processing_config.input_stream() = input_config;
857 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800858 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200859
860 if (processing_config.output_stream() != output_config) {
861 processing_config.output_stream() = output_config;
862 reinitialization_required = true;
863 }
864
865 if (reinitialization_required) {
866 // Reinitialize.
867 rtc::CritScope cs_render(&crit_render_);
868 rtc::CritScope cs_capture(&crit_capture_);
869 RETURN_ON_ERR(InitializeLocked(processing_config));
870 }
871
peahdf3efa82015-11-28 12:35:15 -0800872 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700873 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
874 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000875
aleloi868f32f2017-05-23 07:20:05 -0700876 if (aec_dump_) {
877 RecordUnprocessedCaptureStream(src);
878 }
879
Per Åhgrena1351272019-08-15 12:15:46 +0200880 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800881 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200882 if (capture_.capture_fullband_audio) {
883 capture_.capture_fullband_audio->CopyFrom(
884 src, formats_.api_format.input_stream());
885 }
peahde65ddc2016-09-16 15:02:15 -0700886 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200887 if (capture_.capture_fullband_audio) {
888 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
889 dest);
890 } else {
891 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
892 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000893
aleloi868f32f2017-05-23 07:20:05 -0700894 if (aec_dump_) {
895 RecordProcessedCaptureStream(dest);
896 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000897 return kNoError;
898}
899
Alex Loiko73ec0192018-05-15 10:52:28 +0200900void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200901 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200902 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200903 if (aec_dump_) {
904 aec_dump_->WriteRuntimeSetting(setting);
905 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200906 switch (setting.type()) {
907 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200908 if (config_.pre_amplifier.enabled) {
909 float value;
910 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200911 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200912 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200913 }
914 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200915 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100916 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100917 if (!submodules_.agc_manager) {
918 float value;
919 setting.GetFloat(&value);
920 int int_value = static_cast<int>(value + .5f);
921 config_.gain_controller1.compression_gain_db = int_value;
922 int error =
923 submodules_.gain_control->set_compression_gain_db(int_value);
924 RTC_DCHECK_EQ(kNoError, error);
925 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100926 break;
927 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200928 case RuntimeSetting::Type::kCaptureFixedPostGain: {
929 if (config_.gain_controller2.enabled) {
930 float value;
931 setting.GetFloat(&value);
932 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200933 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200934 }
935 break;
936 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200937 case RuntimeSetting::Type::kPlayoutVolumeChange: {
938 int value;
939 setting.GetInt(&value);
940 capture_.playout_volume = value;
941 break;
942 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100943 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
944 RTC_NOTREACHED();
945 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200946 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
947 RTC_NOTREACHED();
948 break;
949 case RuntimeSetting::Type::kNotSpecified:
950 RTC_NOTREACHED();
951 break;
952 }
953 }
954}
955
956void AudioProcessingImpl::HandleRenderRuntimeSettings() {
957 RuntimeSetting setting;
958 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200959 if (aec_dump_) {
960 aec_dump_->WriteRuntimeSetting(setting);
961 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200962 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100963 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100964 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200965 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200966 if (submodules_.render_pre_processor) {
967 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200968 }
969 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100970 case RuntimeSetting::Type::kCapturePreGain: // fall-through
971 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200972 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200973 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200974 RTC_NOTREACHED();
975 break;
976 }
977 }
978}
979
peah9e6a2902017-05-15 07:19:21 -0700980void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800981 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700982
saza1d600522019-10-18 13:29:43 +0200983 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200984 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
985 num_reverse_channels(),
986 &aecm_render_queue_buffer_);
987 RTC_DCHECK(aecm_render_signal_queue_);
988 // Insert the samples into the queue.
989 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
990 // The data queue is full and needs to be emptied.
991 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -0700992
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200993 // Retry the insert (should always work).
994 bool result =
995 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
996 RTC_DCHECK(result);
997 }
peah764e3642016-10-22 05:04:30 -0700998 }
peah701d6282016-10-25 05:42:20 -0700999
Per Åhgren0e3198e2019-11-18 08:52:22 +01001000 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001001 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001002 // Insert the samples into the queue.
1003 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1004 // The data queue is full and needs to be emptied.
1005 EmptyQueuedRenderAudio();
1006
1007 // Retry the insert (should always work).
1008 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1009 RTC_DCHECK(result);
1010 }
1011 }
peah9e6a2902017-05-15 07:19:21 -07001012}
ivoc9f4a4a02016-10-28 05:39:16 -07001013
peah9e6a2902017-05-15 07:19:21 -07001014void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001015 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1016
1017 // Insert the samples into the queue.
1018 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1019 // The data queue is full and needs to be emptied.
1020 EmptyQueuedRenderAudio();
1021
1022 // Retry the insert (should always work).
1023 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1024 RTC_DCHECK(result);
1025 }
peah764e3642016-10-22 05:04:30 -07001026}
1027
1028void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001029 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001030 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001031
ivoc9f4a4a02016-10-28 05:39:16 -07001032 const size_t new_red_render_queue_element_max_size =
1033 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1034
peaha0624602016-10-25 04:45:24 -07001035 // Reallocate the queues if the queue item sizes are too small to fit the
1036 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001037
1038 if (agc_render_queue_element_max_size_ <
1039 new_agc_render_queue_element_max_size) {
1040 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1041
1042 std::vector<int16_t> template_queue_element(
1043 agc_render_queue_element_max_size_);
1044
1045 agc_render_signal_queue_.reset(
1046 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1047 kMaxNumFramesToBuffer, template_queue_element,
1048 RenderQueueItemVerifier<int16_t>(
1049 agc_render_queue_element_max_size_)));
1050
1051 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1052 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1053 } else {
1054 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001055 }
ivoc9f4a4a02016-10-28 05:39:16 -07001056
1057 if (red_render_queue_element_max_size_ <
1058 new_red_render_queue_element_max_size) {
1059 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1060
1061 std::vector<float> template_queue_element(
1062 red_render_queue_element_max_size_);
1063
1064 red_render_signal_queue_.reset(
1065 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1066 kMaxNumFramesToBuffer, template_queue_element,
1067 RenderQueueItemVerifier<float>(
1068 red_render_queue_element_max_size_)));
1069
1070 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1071 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1072 } else {
1073 red_render_signal_queue_->Clear();
1074 }
peah764e3642016-10-22 05:04:30 -07001075}
1076
1077void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1078 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001079 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001080 RTC_DCHECK(aecm_render_signal_queue_);
1081 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001082 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001083 aecm_capture_queue_buffer_);
1084 }
peah701d6282016-10-25 05:42:20 -07001085 }
1086
1087 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001088 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001089 }
ivoc9f4a4a02016-10-28 05:39:16 -07001090
1091 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001092 RTC_DCHECK(submodules_.echo_detector);
1093 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001094 }
peah764e3642016-10-22 05:04:30 -07001095}
1096
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001097int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001098 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001099 {
1100 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001101 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001102 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001103 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001104 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001105 }
peahfa6228e2015-11-16 16:27:42 -08001106
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001107 if (!frame) {
1108 return kNullPointerError;
1109 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001110 // Must be a native rate.
1111 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1112 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001113 frame->sample_rate_hz_ != kSampleRate32kHz &&
1114 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001115 return kBadSampleRateError;
1116 }
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 {
1121 // Aquire lock for the access of api_format.
1122 // The lock is released immediately due to the conditional
1123 // reinitialization.
1124 rtc::CritScope cs_capture(&crit_capture_);
1125 // TODO(ajm): The input and output rates and channels are currently
1126 // constrained to be identical in the int16 interface.
1127 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001128
1129 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001130 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001131
Oskar Sundbom4b276482019-05-23 14:28:00 +02001132 reinitialization_required =
1133 reinitialization_required ||
1134 processing_config.input_stream().sample_rate_hz() !=
1135 frame->sample_rate_hz_ ||
1136 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1137 processing_config.output_stream().sample_rate_hz() !=
1138 frame->sample_rate_hz_ ||
1139 processing_config.output_stream().num_channels() != frame->num_channels_;
1140
1141 if (reinitialization_required) {
1142 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1143 processing_config.input_stream().set_num_channels(frame->num_channels_);
1144 processing_config.output_stream().set_sample_rate_hz(
1145 frame->sample_rate_hz_);
1146 processing_config.output_stream().set_num_channels(frame->num_channels_);
1147
1148 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001149 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001150 rtc::CritScope cs_capture(&crit_capture_);
1151 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001152 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001153
peahdf3efa82015-11-28 12:35:15 -08001154 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001155 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001156 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001157 return kBadDataLengthError;
1158 }
1159
aleloi868f32f2017-05-23 07:20:05 -07001160 if (aec_dump_) {
1161 RecordUnprocessedCaptureStream(*frame);
1162 }
1163
Per Åhgrend47941e2019-08-22 11:51:13 +02001164 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001165 if (capture_.capture_fullband_audio) {
1166 capture_.capture_fullband_audio->CopyFrom(frame);
1167 }
peahde65ddc2016-09-16 15:02:15 -07001168 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001169 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001170 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001171 if (capture_.capture_fullband_audio) {
1172 capture_.capture_fullband_audio->CopyTo(frame);
1173 } else {
1174 capture_.capture_audio->CopyTo(frame);
1175 }
Per Åhgrena1351272019-08-15 12:15:46 +02001176 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001177 if (capture_.stats.voice_detected) {
1178 frame->vad_activity_ = *capture_.stats.voice_detected
1179 ? AudioFrame::kVadActive
1180 : AudioFrame::kVadPassive;
1181 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001182
aleloi868f32f2017-05-23 07:20:05 -07001183 if (aec_dump_) {
1184 RecordProcessedCaptureStream(*frame);
1185 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001186
1187 return kNoError;
1188}
1189
peahde65ddc2016-09-16 15:02:15 -07001190int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001191 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001192
peahb58a1582016-03-15 09:34:24 -07001193 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001194 // TODO(peah): Simplify once the public API Enable functions for these
1195 // are moved to APM.
saza1d600522019-10-18 13:29:43 +02001196 RTC_DCHECK_LE(!!submodules_.echo_controller +
saza1d600522019-10-18 13:29:43 +02001197 !!submodules_.echo_control_mobile,
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001198 1);
peahb58a1582016-03-15 09:34:24 -07001199
peahde65ddc2016-09-16 15:02:15 -07001200 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001201
saza1d600522019-10-18 13:29:43 +02001202 if (submodules_.pre_amplifier) {
1203 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001204 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001205 capture_buffer->num_frames()));
1206 }
1207
Per Åhgren928146f2019-08-20 09:19:21 +02001208 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001209 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001210 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001211 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1212 if (log_rms) {
1213 capture_rms_interval_counter_ = 0;
1214 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001215 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1216 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1217 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1218 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001219 }
1220
saza1d600522019-10-18 13:29:43 +02001221 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001222 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001223 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001224 capture_.echo_path_gain_change =
1225 capture_.prev_analog_mic_level != analog_mic_level &&
1226 capture_.prev_analog_mic_level != -1;
1227 capture_.prev_analog_mic_level = analog_mic_level;
1228
Per Åhgrend2650d12018-10-02 17:00:59 +02001229 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001230 if (submodules_.pre_amplifier) {
1231 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001232 capture_.echo_path_gain_change =
1233 capture_.echo_path_gain_change ||
1234 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001235 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001236 capture_.prev_pre_amp_gain = pre_amp_gain;
1237 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001238
1239 // Detect volume change.
1240 capture_.echo_path_gain_change =
1241 capture_.echo_path_gain_change ||
1242 (capture_.prev_playout_volume != capture_.playout_volume &&
1243 capture_.prev_playout_volume >= 0);
1244 capture_.prev_playout_volume = capture_.playout_volume;
1245
saza1d600522019-10-18 13:29:43 +02001246 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001247 }
1248
Per Åhgren3daedb62019-11-22 12:11:40 +01001249 if (constants_.use_experimental_agc &&
1250 submodules_.gain_control->is_enabled()) {
1251 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001252 }
1253
peah2ace3f92016-09-10 04:42:27 -07001254 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1255 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001256 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1257 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001258 }
1259
Per Åhgrene14cb992019-11-27 09:34:22 +01001260 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1261 constants_.multi_channel_capture_support;
1262 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001263 // Force down-mixing of the number of channels after the detection of
1264 // capture signal saturation.
1265 // TODO(peah): Look into ensuring that this kind of tampering with the
1266 // AudioBuffer functionality should not be needed.
1267 capture_buffer->set_num_channels(1);
1268 }
1269
saza1d600522019-10-18 13:29:43 +02001270 if (submodules_.high_pass_filter) {
1271 submodules_.high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001272 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001273
Per Åhgrene35b32c2019-11-22 18:22:04 +01001274 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001275 RTC_DCHECK(
1276 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
saza1d600522019-10-18 13:29:43 +02001277 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001278 submodules_.noise_suppressor->Analyze(*capture_buffer);
1279 } else if (submodules_.legacy_noise_suppressor) {
1280 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001281 }
peahb58a1582016-03-15 09:34:24 -07001282
saza1d600522019-10-18 13:29:43 +02001283 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001284 // Ensure that the stream delay was set before the call to the
1285 // AECM ProcessCaptureAudio function.
1286 if (!was_stream_delay_set()) {
1287 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001288 }
1289
saza1d600522019-10-18 13:29:43 +02001290 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001291 submodules_.noise_suppressor->Process(capture_buffer);
1292 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001293 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001294 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001295 }
peahe0eae3c2016-12-14 01:16:23 -08001296
saza1d600522019-10-18 13:29:43 +02001297 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001298 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001299 } else {
saza1d600522019-10-18 13:29:43 +02001300 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001301 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1302
1303 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001304 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001305 }
1306
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001307 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
saza1d600522019-10-18 13:29:43 +02001308 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001309 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001310 }
1311
saza1d600522019-10-18 13:29:43 +02001312 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001313 submodules_.noise_suppressor->Process(capture_buffer);
1314 } else if (submodules_.legacy_noise_suppressor) {
1315 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001316 }
Per Åhgren46537a32017-06-07 10:08:10 +02001317 }
ivoc9f4a4a02016-10-28 05:39:16 -07001318
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001319 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001320 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001321 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001322 } else {
1323 capture_.stats.voice_detected = absl::nullopt;
1324 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001325
Per Åhgren3daedb62019-11-22 12:11:40 +01001326 if (constants_.use_experimental_agc &&
1327 submodules_.gain_control->is_enabled()) {
1328 submodules_.agc_manager->Process(capture_buffer);
1329
1330 absl::optional<int> new_digital_gain =
1331 submodules_.agc_manager->GetDigitalComressionGain();
1332 if (new_digital_gain) {
1333 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1334 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001335 }
Per Åhgren200feba2019-03-06 04:16:46 +01001336 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001337 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001338 capture_buffer, /*stream_has_echo*/ false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001339
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001340 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001341 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001342 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1343 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001344 }
1345
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001346 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001347 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001348 bool ec_active = ec ? ec->ActiveProcessing() : false;
1349 // Only update the fullband buffer if the multiband processing has changed
1350 // the signal. Keep the original signal otherwise.
1351 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1352 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1353 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001354 capture_buffer = capture_.capture_fullband_audio.get();
1355 }
1356
peah9e6a2902017-05-15 07:19:21 -07001357 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001358 RTC_DCHECK(submodules_.echo_detector);
1359 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1360 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001361 }
1362
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001363 // TODO(aluebs): Investigate if the transient suppression placement should be
1364 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001365 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001366 float voice_probability = submodules_.agc_manager.get()
1367 ? submodules_.agc_manager->voice_probability()
1368 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001369
saza1d600522019-10-18 13:29:43 +02001370 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001371 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001372 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001373 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001374 capture_buffer->num_frames_per_band(),
1375 capture_.keyboard_info.keyboard_data,
1376 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001377 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001378 }
1379
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001380 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001381 if (submodules_.capture_analyzer) {
1382 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001383 }
1384
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001385 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001386 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001387 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001388 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001389 }
1390
saza1d600522019-10-18 13:29:43 +02001391 if (submodules_.capture_post_processor) {
1392 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001393 }
1394
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001395 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001396 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001397 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1398 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001399 } else {
1400 capture_.stats.output_rms_dbfs = absl::nullopt;
1401 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001402
Per Åhgren928146f2019-08-20 09:19:21 +02001403 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001404 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001405 capture_nonlocked_.capture_processing_format.num_frames()));
1406 if (log_rms) {
1407 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1408 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1409 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1410 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1411 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1412 }
1413
Per Åhgren0e3198e2019-11-18 08:52:22 +01001414 if (submodules_.agc_manager) {
1415 int level = recommended_stream_analog_level();
1416 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1417 &level);
1418 }
1419
peahdf3efa82015-11-28 12:35:15 -08001420 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001421 return kNoError;
1422}
1423
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001424int AudioProcessingImpl::AnalyzeReverseStream(
1425 const float* const* data,
1426 const StreamConfig& reverse_config) {
1427 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1428 rtc::CritScope cs(&crit_render_);
1429 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1430}
1431
peahde65ddc2016-09-16 15:02:15 -07001432int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1433 const StreamConfig& input_config,
1434 const StreamConfig& output_config,
1435 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001436 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001437 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001438 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001439 if (submodule_states_.RenderMultiBandProcessingActive() ||
1440 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001441 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1442 dest);
peah2ace3f92016-09-10 04:42:27 -07001443 } else if (formats_.api_format.reverse_input_stream() !=
1444 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001445 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1446 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001447 } else {
peahde65ddc2016-09-16 15:02:15 -07001448 CopyAudioIfNeeded(src, input_config.num_frames(),
1449 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001450 }
1451
1452 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001453}
1454
peahdf3efa82015-11-28 12:35:15 -08001455int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001456 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001457 const StreamConfig& input_config,
1458 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001459 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001460 return kNullPointerError;
1461 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001462
peahde65ddc2016-09-16 15:02:15 -07001463 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001464 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001465 }
1466
peahdf3efa82015-11-28 12:35:15 -08001467 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001468 processing_config.reverse_input_stream() = input_config;
1469 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001470
peahdf3efa82015-11-28 12:35:15 -08001471 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001472 RTC_DCHECK_EQ(input_config.num_frames(),
1473 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001474
aleloi868f32f2017-05-23 07:20:05 -07001475 if (aec_dump_) {
1476 const size_t channel_size =
1477 formats_.api_format.reverse_input_stream().num_frames();
1478 const size_t num_channels =
1479 formats_.api_format.reverse_input_stream().num_channels();
1480 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001481 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001482 }
peahdf3efa82015-11-28 12:35:15 -08001483 render_.render_audio->CopyFrom(src,
1484 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001485 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001486}
1487
1488int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001489 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001490 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001491 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001492 return kNullPointerError;
1493 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001494 // Must be a native rate.
1495 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1496 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001497 frame->sample_rate_hz_ != kSampleRate32kHz &&
1498 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001499 return kBadSampleRateError;
1500 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001501
Michael Graczyk86c6d332015-07-23 11:41:39 -07001502 if (frame->num_channels_ <= 0) {
1503 return kBadNumberChannelsError;
1504 }
1505
peahdf3efa82015-11-28 12:35:15 -08001506 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001507 processing_config.reverse_input_stream().set_sample_rate_hz(
1508 frame->sample_rate_hz_);
1509 processing_config.reverse_input_stream().set_num_channels(
1510 frame->num_channels_);
1511 processing_config.reverse_output_stream().set_sample_rate_hz(
1512 frame->sample_rate_hz_);
1513 processing_config.reverse_output_stream().set_num_channels(
1514 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001515
peahdf3efa82015-11-28 12:35:15 -08001516 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001517 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001518 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001519 return kBadDataLengthError;
1520 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001521
aleloi868f32f2017-05-23 07:20:05 -07001522 if (aec_dump_) {
1523 aec_dump_->WriteRenderStreamMessage(*frame);
1524 }
1525
Per Åhgrend47941e2019-08-22 11:51:13 +02001526 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001527 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001528 if (submodule_states_.RenderMultiBandProcessingActive() ||
1529 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001530 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001531 }
aluebsb0319552016-03-17 20:39:53 -07001532 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001533}
niklase@google.com470e71d2011-07-07 08:21:25 +00001534
peahde65ddc2016-09-16 15:02:15 -07001535int AudioProcessingImpl::ProcessRenderStreamLocked() {
1536 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001537
Alex Loiko73ec0192018-05-15 10:52:28 +02001538 HandleRenderRuntimeSettings();
1539
saza1d600522019-10-18 13:29:43 +02001540 if (submodules_.render_pre_processor) {
1541 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001542 }
1543
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001544 QueueNonbandedRenderAudio(render_buffer);
1545
peah2ace3f92016-09-10 04:42:27 -07001546 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001547 SampleRateSupportsMultiBand(
1548 formats_.render_processing_format.sample_rate_hz())) {
1549 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001550 }
1551
peahce4d9152017-05-19 01:28:05 -07001552 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1553 QueueBandedRenderAudio(render_buffer);
1554 }
1555
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001556 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001557 if (submodules_.echo_controller) {
1558 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001559 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001560
peah2ace3f92016-09-10 04:42:27 -07001561 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001562 SampleRateSupportsMultiBand(
1563 formats_.render_processing_format.sample_rate_hz())) {
1564 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001565 }
1566
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001567 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001568}
1569
1570int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001571 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001572 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001573 capture_.was_stream_delay_set = true;
1574 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001575
niklase@google.com470e71d2011-07-07 08:21:25 +00001576 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001577 delay = 0;
1578 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001579 }
1580
1581 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1582 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001583 delay = 500;
1584 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001585 }
1586
peahdf3efa82015-11-28 12:35:15 -08001587 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001588 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001589}
1590
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001591bool AudioProcessingImpl::GetLinearAecOutput(
1592 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1593 rtc::CritScope cs(&crit_capture_);
1594 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1595
1596 RTC_DCHECK(linear_aec_buffer);
1597 if (linear_aec_buffer) {
1598 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1599 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1600
1601 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1602 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1603 rtc::ArrayView<const float> channel_view =
1604 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1605 linear_aec_buffer->num_frames());
1606 std::copy(channel_view.begin(), channel_view.end(),
1607 linear_output[ch].begin());
1608 }
1609 return true;
1610 }
1611 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1612 RTC_NOTREACHED();
1613 return false;
1614}
1615
niklase@google.com470e71d2011-07-07 08:21:25 +00001616int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001617 // Used as callback from submodules, hence locking is not allowed.
1618 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001619}
1620
1621bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001622 // Used as callback from submodules, hence locking is not allowed.
1623 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001624}
1625
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001626void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001627 rtc::CritScope cs(&crit_capture_);
1628 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001629}
1630
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001631void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001632 rtc::CritScope cs(&crit_capture_);
1633 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001634}
1635
1636int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001637 rtc::CritScope cs(&crit_capture_);
1638 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001639}
1640
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001641void AudioProcessingImpl::set_stream_analog_level(int level) {
1642 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001643
1644 if (submodules_.agc_manager) {
1645 submodules_.agc_manager->set_stream_analog_level(level);
1646 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1647 1, &level);
1648 } else {
1649 int error = submodules_.gain_control->set_stream_analog_level(level);
1650 RTC_DCHECK_EQ(kNoError, error);
1651 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001652}
1653
1654int AudioProcessingImpl::recommended_stream_analog_level() const {
1655 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001656 if (submodules_.agc_manager) {
1657 return submodules_.agc_manager->stream_analog_level();
1658 }
1659 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001660}
1661
aleloi868f32f2017-05-23 07:20:05 -07001662void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1663 RTC_DCHECK(aec_dump);
1664 rtc::CritScope cs_render(&crit_render_);
1665 rtc::CritScope cs_capture(&crit_capture_);
1666
1667 // The previously attached AecDump will be destroyed with the
1668 // 'aec_dump' parameter, which is after locks are released.
1669 aec_dump_.swap(aec_dump);
1670 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001671 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001672}
1673
1674void AudioProcessingImpl::DetachAecDump() {
1675 // The d-tor of a task-queue based AecDump blocks until all pending
1676 // tasks are done. This construction avoids blocking while holding
1677 // the render and capture locks.
1678 std::unique_ptr<AecDump> aec_dump = nullptr;
1679 {
1680 rtc::CritScope cs_render(&crit_render_);
1681 rtc::CritScope cs_capture(&crit_capture_);
1682 aec_dump = std::move(aec_dump_);
1683 }
1684}
1685
Sam Zackrisson4d364492018-03-02 16:03:21 +01001686void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1687 std::unique_ptr<AudioGenerator> audio_generator) {
1688 // TODO(bugs.webrtc.org/8882) Stub.
1689 // Reset internal audio generator with audio_generator.
1690}
1691
1692void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1693 // TODO(bugs.webrtc.org/8882) Stub.
1694 // Delete audio generator, if one is attached.
1695}
1696
Ivo Creusen56d46092017-11-24 17:29:59 +01001697AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001698 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001699 rtc::CritScope cs_capture(&crit_capture_);
1700 if (!has_remote_tracks) {
1701 return capture_.stats;
1702 }
1703 AudioProcessingStats stats = capture_.stats;
saza1d600522019-10-18 13:29:43 +02001704 if (submodules_.echo_controller) {
1705 auto ec_metrics = submodules_.echo_controller->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001706 stats.echo_return_loss = ec_metrics.echo_return_loss;
1707 stats.echo_return_loss_enhancement =
1708 ec_metrics.echo_return_loss_enhancement;
1709 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001710 }
1711 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001712 RTC_DCHECK(submodules_.echo_detector);
1713 auto ed_metrics = submodules_.echo_detector->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001714 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1715 stats.residual_echo_likelihood_recent_max =
1716 ed_metrics.echo_likelihood_recent_max;
1717 }
Ivo Creusenae026092017-11-20 13:07:16 +01001718 return stats;
1719}
1720
peah8271d042016-11-22 07:24:52 -08001721void AudioProcessingImpl::MutateConfig(
1722 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1723 rtc::CritScope cs_render(&crit_render_);
1724 rtc::CritScope cs_capture(&crit_capture_);
1725 mutator(&config_);
1726 ApplyConfig(config_);
1727}
1728
1729AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1730 rtc::CritScope cs_render(&crit_render_);
1731 rtc::CritScope cs_capture(&crit_capture_);
1732 return config_;
1733}
1734
peah2ace3f92016-09-10 04:42:27 -07001735bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1736 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001737 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
1738 config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001739 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
1740 submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled,
1741 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 11:46:11 +02001742 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001743}
1744
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001745void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001746 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001747 if (!submodules_.transient_suppressor.get()) {
1748 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001749 }
saza1d600522019-10-18 13:29:43 +02001750 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1751 capture_nonlocked_.split_rate,
1752 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001753 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001754}
1755
Per Åhgren4011de02019-12-03 11:48:48 +00001756void AudioProcessingImpl::InitializeHighPassFilter() {
Per Åhgrenb8106462019-12-04 08:34:12 +01001757 bool high_pass_filter_needed_by_aec =
1758 config_.echo_canceller.enabled &&
1759 config_.echo_canceller.enforce_high_pass_filtering &&
1760 !config_.echo_canceller.mobile_mode;
1761 if (submodule_states_.HighPassFilteringRequired() ||
1762 high_pass_filter_needed_by_aec) {
saza1d600522019-10-18 13:29:43 +02001763 submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001764 } else {
saza1d600522019-10-18 13:29:43 +02001765 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001766 }
1767}
alessiob3ec96df2017-05-22 06:57:06 -07001768
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001769void AudioProcessingImpl::InitializeVoiceDetector() {
1770 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001771 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001772 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1773 } else {
saza1d600522019-10-18 13:29:43 +02001774 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001775 }
1776}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001777void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001778 bool use_echo_controller =
1779 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001780 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001781
1782 if (use_echo_controller) {
1783 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001784 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001785 submodules_.echo_controller = echo_control_factory_->Create(
1786 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001787 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001788 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001789 EchoCanceller3Config config =
1790 use_setup_specific_default_aec3_config_
1791 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1792 num_proc_channels())
1793 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001794 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001795 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001796 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001797 }
1798
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001799 // Setup the storage for returning the linear AEC output.
1800 if (config_.echo_canceller.export_linear_aec_output) {
1801 constexpr int kLinearOutputRateHz = 16000;
1802 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1803 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1804 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1805 } else {
1806 capture_.linear_aec_output.reset();
1807 }
1808
Per Åhgren200feba2019-03-06 04:16:46 +01001809 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001810
saza1d600522019-10-18 13:29:43 +02001811 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001812 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001813 return;
peahe0eae3c2016-12-14 01:16:23 -08001814 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001815
saza1d600522019-10-18 13:29:43 +02001816 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001817 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001818 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001819
1820 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001821 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001822 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001823 return;
1824 }
1825
1826 if (config_.echo_canceller.mobile_mode) {
1827 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001828 size_t max_element_size =
1829 std::max(static_cast<size_t>(1),
1830 kMaxAllowedValuesOfSamplesPerBand *
1831 EchoControlMobileImpl::NumCancellersRequired(
1832 num_output_channels(), num_reverse_channels()));
1833
1834 std::vector<int16_t> template_queue_element(max_element_size);
1835
1836 aecm_render_signal_queue_.reset(
1837 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1838 kMaxNumFramesToBuffer, template_queue_element,
1839 RenderQueueItemVerifier<int16_t>(max_element_size)));
1840
1841 aecm_render_queue_buffer_.resize(max_element_size);
1842 aecm_capture_queue_buffer_.resize(max_element_size);
1843
saza1d600522019-10-18 13:29:43 +02001844 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001845
saza1d600522019-10-18 13:29:43 +02001846 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1847 num_reverse_channels(),
1848 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001849 return;
1850 }
1851
saza1d600522019-10-18 13:29:43 +02001852 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001853 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001854}
peah8271d042016-11-22 07:24:52 -08001855
alessiob3ec96df2017-05-22 06:57:06 -07001856void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001857 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001858 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001859 }
1860}
1861
saza0bad15f2019-10-16 11:46:11 +02001862void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001863 submodules_.legacy_noise_suppressor.reset();
1864 submodules_.noise_suppressor.reset();
1865
saza0bad15f2019-10-16 11:46:11 +02001866 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001867 const bool use_legacy_ns =
1868 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1869
1870 if (!use_legacy_ns) {
1871 auto map_level =
1872 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1873 using NoiseSuppresionConfig =
1874 AudioProcessing::Config::NoiseSuppression;
1875 switch (level) {
1876 case NoiseSuppresionConfig::kLow:
1877 return NsConfig::SuppressionLevel::k6dB;
1878 case NoiseSuppresionConfig::kModerate:
1879 return NsConfig::SuppressionLevel::k12dB;
1880 case NoiseSuppresionConfig::kHigh:
1881 return NsConfig::SuppressionLevel::k18dB;
1882 case NoiseSuppresionConfig::kVeryHigh:
1883 return NsConfig::SuppressionLevel::k21dB;
1884 default:
1885 RTC_NOTREACHED();
1886 }
1887 };
1888
1889 NsConfig cfg;
1890 cfg.target_level = map_level(config_.noise_suppression.level);
1891 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1892 cfg, proc_sample_rate_hz(), num_proc_channels());
1893 } else {
1894 auto ns_level =
1895 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1896 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1897 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1898 }
saza0bad15f2019-10-16 11:46:11 +02001899 }
1900}
1901
Alex Loikob5c9a792018-04-16 16:31:22 +02001902void AudioProcessingImpl::InitializePreAmplifier() {
1903 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001904 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001905 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1906 } else {
saza1d600522019-10-18 13:29:43 +02001907 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001908 }
1909}
1910
ivoc9f4a4a02016-10-28 05:39:16 -07001911void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001912 RTC_DCHECK(submodules_.echo_detector);
1913 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001914 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001915 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001916}
1917
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001918void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001919 if (submodules_.capture_analyzer) {
1920 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1921 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001922 }
1923}
1924
Sam Zackrisson0beac582017-09-25 12:04:02 +02001925void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001926 if (submodules_.capture_post_processor) {
1927 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001928 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001929 }
1930}
1931
Alex Loiko5825aa62017-12-18 16:02:40 +01001932void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001933 if (submodules_.render_pre_processor) {
1934 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001935 formats_.render_processing_format.sample_rate_hz(),
1936 formats_.render_processing_format.num_channels());
1937 }
1938}
1939
Per Åhgrenea4c5df2019-05-03 09:00:08 +02001940void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001941
aleloi868f32f2017-05-23 07:20:05 -07001942void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1943 if (!aec_dump_) {
1944 return;
1945 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001946
1947 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07001948 // TODO(peah): Add semicolon-separated concatenations of experiment
1949 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001950 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1951 experiments_description += "AgcClippingLevelExperiment;";
1952 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001953 if (capture_nonlocked_.echo_controller_enabled) {
1954 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001955 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001956 if (config_.gain_controller2.enabled) {
1957 experiments_description += "GainController2;";
1958 }
aleloi868f32f2017-05-23 07:20:05 -07001959
1960 InternalAPMConfig apm_config;
1961
Per Åhgren200feba2019-03-06 04:16:46 +01001962 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001963 apm_config.aec_delay_agnostic_enabled = false;
1964 apm_config.aec_extended_filter_enabled = false;
1965 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07001966
saza1d600522019-10-18 13:29:43 +02001967 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07001968 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02001969 submodules_.echo_control_mobile &&
1970 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001971 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02001972 submodules_.echo_control_mobile
1973 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001974 : 0;
aleloi868f32f2017-05-23 07:20:05 -07001975
saza1d600522019-10-18 13:29:43 +02001976 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
1977 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07001978 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02001979 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01001980 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07001981
1982 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1983
saza0bad15f2019-10-16 11:46:11 +02001984 apm_config.ns_enabled = config_.noise_suppression.enabled;
1985 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07001986
1987 apm_config.transient_suppression_enabled =
1988 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001989 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001990 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1991 apm_config.pre_amplifier_fixed_gain_factor =
1992 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001993
1994 if (!forced && apm_config == apm_config_for_aec_dump_) {
1995 return;
1996 }
1997 aec_dump_->WriteConfig(apm_config);
1998 apm_config_for_aec_dump_ = apm_config;
1999}
2000
2001void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2002 const float* const* src) {
2003 RTC_DCHECK(aec_dump_);
2004 WriteAecDumpConfigMessage(false);
2005
2006 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2007 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2008 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002009 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002010 RecordAudioProcessingState();
2011}
2012
2013void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2014 const AudioFrame& capture_frame) {
2015 RTC_DCHECK(aec_dump_);
2016 WriteAecDumpConfigMessage(false);
2017
2018 aec_dump_->AddCaptureStreamInput(capture_frame);
2019 RecordAudioProcessingState();
2020}
2021
2022void AudioProcessingImpl::RecordProcessedCaptureStream(
2023 const float* const* processed_capture_stream) {
2024 RTC_DCHECK(aec_dump_);
2025
2026 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2027 const size_t num_channels =
2028 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002029 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2030 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002031 aec_dump_->WriteCaptureStreamMessage();
2032}
2033
2034void AudioProcessingImpl::RecordProcessedCaptureStream(
2035 const AudioFrame& processed_capture_frame) {
2036 RTC_DCHECK(aec_dump_);
2037
2038 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2039 aec_dump_->WriteCaptureStreamMessage();
2040}
2041
2042void AudioProcessingImpl::RecordAudioProcessingState() {
2043 RTC_DCHECK(aec_dump_);
2044 AecDump::AudioProcessingState audio_proc_state;
2045 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002046 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002047 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002048 audio_proc_state.keypress = capture_.key_pressed;
2049 aec_dump_->AddAudioProcessingState(audio_proc_state);
2050}
2051
kwiberg83ffe452016-08-29 14:46:07 -07002052AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002053 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002054 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002055 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002056 output_will_be_muted(false),
2057 key_pressed(false),
2058 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002059 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002060 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002061 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002062 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002063 prev_pre_amp_gain(-1.f),
2064 playout_volume(-1),
2065 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002066
2067AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2068
Per Åhgrena1351272019-08-15 12:15:46 +02002069void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2070 const float* const* data,
2071 const StreamConfig& stream_config) {
2072 if (stream_config.has_keyboard()) {
2073 keyboard_data = data[stream_config.num_channels()];
2074 } else {
2075 keyboard_data = NULL;
2076 }
2077 num_keyboard_frames = stream_config.num_frames();
2078}
2079
kwiberg83ffe452016-08-29 14:46:07 -07002080AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2081
2082AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2083
niklase@google.com470e71d2011-07-07 08:21:25 +00002084} // namespace webrtc