blob: 6abebd26128e77c5a5babfee9bf687f87ffa7406 [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"
Per Åhgren645f24c2020-03-16 12:06:02 +010022#include "api/audio/audio_frame.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "common_audio/include/audio_util.h"
Per Åhgren09e9a832020-05-11 11:03:47 +020025#include "modules/audio_processing/aec_dump/aec_dump_factory.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020026#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/common.h"
Yves Gerey988cc082018-10-23 12:03:01 +020029#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 21:42:56 +010030#include "modules/audio_processing/logging/apm_data_dumper.h"
Sam Zackrissonb37e59d2020-04-27 08:39:33 +020031#include "modules/audio_processing/optionally_built_submodule_creators.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/ref_counted_object.h"
37#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020039#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000041
Michael Graczyk86c6d332015-07-23 11:41:39 -070042#define RETURN_ON_ERR(expr) \
43 do { \
44 int err = (expr); \
45 if (err != kNoError) { \
46 return err; \
47 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000048 } while (0)
49
niklase@google.com470e71d2011-07-07 08:21:25 +000050namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070051
Alex Loiko73ec0192018-05-15 10:52:28 +020052constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070053
Michael Graczyk86c6d332015-07-23 11:41:39 -070054namespace {
55
56static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
57 switch (layout) {
58 case AudioProcessing::kMono:
59 case AudioProcessing::kStereo:
60 return false;
61 case AudioProcessing::kMonoAndKeyboard:
62 case AudioProcessing::kStereoAndKeyboard:
63 return true;
64 }
65
kwiberg9e2be5f2016-09-14 05:23:22 -070066 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070067 return false;
68}
aluebsdf6416a2016-03-16 18:26:35 -070069
peah2ace3f92016-09-10 04:42:27 -070070bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070071 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
72 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
73}
74
Per Åhgrenc0424252019-12-10 13:04:15 +010075// Checks whether the high-pass filter should be done in the full-band.
76bool EnforceSplitBandHpf() {
77 return field_trial::IsEnabled("WebRTC-FullBandHpfKillSwitch");
78}
79
Per Åhgrenb2b58d82019-12-02 14:59:40 +010080// Checks whether AEC3 should be allowed to decide what the default
81// configuration should be based on the render and capture channel configuration
82// at hand.
83bool UseSetupSpecificDefaultAec3Congfig() {
84 return !field_trial::IsEnabled(
85 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
86}
87
Per Åhgrenc8626b62019-08-23 15:49:51 +020088// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020089int SuitableProcessRate(int minimum_rate,
90 int max_splitting_rate,
91 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020092 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020093 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020094 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070095 if (rate >= uppermost_native_rate) {
96 return uppermost_native_rate;
97 }
98 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070099 return rate;
100 }
101 }
peah2ace3f92016-09-10 04:42:27 -0700102 RTC_NOTREACHED();
103 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700104}
105
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100106GainControl::Mode Agc1ConfigModeToInterfaceMode(
107 AudioProcessing::Config::GainController1::Mode mode) {
108 using Agc1Config = AudioProcessing::Config::GainController1;
109 switch (mode) {
110 case Agc1Config::kAdaptiveAnalog:
111 return GainControl::kAdaptiveAnalog;
112 case Agc1Config::kAdaptiveDigital:
113 return GainControl::kAdaptiveDigital;
114 case Agc1Config::kFixedDigital:
115 return GainControl::kFixedDigital;
116 }
117}
118
peah9e6a2902017-05-15 07:19:21 -0700119// Maximum lengths that frame of samples being passed from the render side to
120// the capture side can have (does not apply to AEC3).
121static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
122static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum number of frames to buffer in the render queue.
125// TODO(peah): Decrease this once we properly handle hugely unbalanced
126// reverse and forward call numbers.
127static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700128} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000129
130// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000131static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000132
saza1d600522019-10-18 13:29:43 +0200133AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100134 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200135 bool render_pre_processor_enabled,
136 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100137 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200138 render_pre_processor_enabled_(render_pre_processor_enabled),
139 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700140
saza1d600522019-10-18 13:29:43 +0200141bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200142 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700143 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700144 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700145 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700146 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700147 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200148 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200149 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200150 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700151 bool transient_suppressor_enabled) {
152 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200153 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700154 changed |=
155 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700156 changed |=
157 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700158 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
159 changed |=
peah2ace3f92016-09-10 04:42:27 -0700160 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200161 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200162 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200163 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200164 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700165 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
166 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200167 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700168 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700169 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700170 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700171 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700172 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200173 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200174 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200175 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700176 transient_suppressor_enabled_ = transient_suppressor_enabled;
177 }
178
179 changed |= first_update_;
180 first_update_ = false;
181 return changed;
182}
183
saza1d600522019-10-18 13:29:43 +0200184bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700185 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200186 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700187}
188
saza1d600522019-10-18 13:29:43 +0200189bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
190 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200191 // If echo controller is present, assume it performs active processing.
192 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
193}
194
saza1d600522019-10-18 13:29:43 +0200195bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200196 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100197 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
198 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200199 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700200}
201
saza1d600522019-10-18 13:29:43 +0200202bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700203 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200204 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
205 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700206}
207
saza1d600522019-10-18 13:29:43 +0200208bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200209 return capture_analyzer_enabled_;
210}
211
saza1d600522019-10-18 13:29:43 +0200212bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700213 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100214 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
215 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700216}
217
saza1d600522019-10-18 13:29:43 +0200218bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100219 const {
220 return render_pre_processor_enabled_;
221}
222
saza1d600522019-10-18 13:29:43 +0200223bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700224 const {
peah2ace3f92016-09-10 04:42:27 -0700225 return false;
peah2ace3f92016-09-10 04:42:27 -0700226}
227
saza1d600522019-10-18 13:29:43 +0200228bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100229 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
230 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200231}
232
peah88ac8532016-09-12 16:47:25 -0700233AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200234 : AudioProcessingImpl(config,
235 /*capture_post_processor=*/nullptr,
236 /*render_pre_processor=*/nullptr,
237 /*echo_control_factory=*/nullptr,
238 /*echo_detector=*/nullptr,
239 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000240
Per Åhgren13735822018-02-12 21:42:56 +0100241int AudioProcessingImpl::instance_count_ = 0;
242
Sam Zackrisson0beac582017-09-25 12:04:02 +0200243AudioProcessingImpl::AudioProcessingImpl(
244 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100245 std::unique_ptr<CustomProcessing> capture_post_processor,
246 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200247 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200248 rtc::scoped_refptr<EchoDetector> echo_detector,
249 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100250 : data_dumper_(
251 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100252 use_setup_specific_default_aec3_config_(
253 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200254 capture_runtime_settings_(kRuntimeSettingQueueSize),
255 render_runtime_settings_(kRuntimeSettingQueueSize),
256 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
257 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200258 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200259 submodule_states_(!!capture_post_processor,
260 !!render_pre_processor,
261 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200262 submodules_(std::move(capture_post_processor),
263 std::move(render_pre_processor),
264 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100265 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100266 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200267 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
268 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100269 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
270 EnforceSplitBandHpf()),
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200271 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200272 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100273 "\nEcho control factory: "
274 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200275 << "\nEcho detector: " << !!submodules_.echo_detector
276 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
277 << "\nCapture post processor: "
278 << !!submodules_.capture_post_processor
279 << "\nRender pre processor: "
280 << !!submodules_.render_pre_processor;
281
Sam Zackrisson421c8592019-02-11 13:39:46 +0100282 // Mark Echo Controller enabled if a factory is injected.
283 capture_nonlocked_.echo_controller_enabled =
284 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000285
Sam Zackrisson421c8592019-02-11 13:39:46 +0100286 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200287 if (!submodules_.echo_detector) {
288 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100289 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800290 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000291
Per Åhgren0695df12020-01-13 14:43:13 +0100292#if !(defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS))
Per Åhgrenc0734712020-01-02 15:15:36 +0100293 // TODO(webrtc:5298): Remove once the use of ExperimentalNs has been
294 // deprecated.
Per Åhgrenc0734712020-01-02 15:15:36 +0100295 config_.transient_suppression.enabled = config.Get<ExperimentalNs>().enabled;
Per Åhgren0695df12020-01-13 14:43:13 +0100296
297 // TODO(webrtc:5298): Remove once the use of ExperimentalAgc has been
298 // deprecated.
299 config_.gain_controller1.analog_gain_controller.enabled =
300 config.Get<ExperimentalAgc>().enabled;
301 config_.gain_controller1.analog_gain_controller.startup_min_volume =
302 config.Get<ExperimentalAgc>().startup_min_volume;
303 config_.gain_controller1.analog_gain_controller.clipped_level_min =
304 config.Get<ExperimentalAgc>().clipped_level_min;
305 config_.gain_controller1.analog_gain_controller.enable_agc2_level_estimator =
306 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator;
307 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive =
308 !config.Get<ExperimentalAgc>().digital_adaptive_disabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100309#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000310}
311
Per Åhgren0e3198e2019-11-18 08:52:22 +0100312AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000313
niklase@google.com470e71d2011-07-07 08:21:25 +0000314int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800315 // Run in a single-threaded manner during initialization.
316 rtc::CritScope cs_render(&crit_render_);
317 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000318 return InitializeLocked();
319}
320
peahde65ddc2016-09-16 15:02:15 -0700321int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
322 int capture_output_sample_rate_hz,
323 int render_input_sample_rate_hz,
324 ChannelLayout capture_input_layout,
325 ChannelLayout capture_output_layout,
326 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700327 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700328 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
329 LayoutHasKeyboard(capture_input_layout)},
330 {capture_output_sample_rate_hz,
331 ChannelsFromLayout(capture_output_layout),
332 LayoutHasKeyboard(capture_output_layout)},
333 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
334 LayoutHasKeyboard(render_input_layout)},
335 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
336 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700337
338 return Initialize(processing_config);
339}
340
341int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800342 // Run in a single-threaded manner during initialization.
343 rtc::CritScope cs_render(&crit_render_);
344 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700345 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000346}
347
peahdf3efa82015-11-28 12:35:15 -0800348int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800349 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800350 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200351 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800352 return kNoError;
353 }
peahdf3efa82015-11-28 12:35:15 -0800354
355 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800356 return InitializeLocked(processing_config);
357}
358
niklase@google.com470e71d2011-07-07 08:21:25 +0000359int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200360 UpdateActiveSubmoduleStates();
361
Per Åhgrend47941e2019-08-22 11:51:13 +0200362 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800363 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200364 ? formats_.render_processing_format.sample_rate_hz()
365 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800366 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
367 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200368 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800369 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200370 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700371 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200372 render_audiobuffer_sample_rate_hz,
373 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700374 if (formats_.api_format.reverse_input_stream() !=
375 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800376 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800377 formats_.api_format.reverse_input_stream().num_channels(),
378 formats_.api_format.reverse_input_stream().num_frames(),
379 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800380 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700381 } else {
peahdf3efa82015-11-28 12:35:15 -0800382 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700383 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700384 } else {
peahdf3efa82015-11-28 12:35:15 -0800385 render_.render_audio.reset(nullptr);
386 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700387 }
peahce4d9152017-05-19 01:28:05 -0700388
Per Åhgrend47941e2019-08-22 11:51:13 +0200389 capture_.capture_audio.reset(new AudioBuffer(
390 formats_.api_format.input_stream().sample_rate_hz(),
391 formats_.api_format.input_stream().num_channels(),
392 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
393 formats_.api_format.output_stream().num_channels(),
394 formats_.api_format.output_stream().sample_rate_hz(),
395 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000396
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200397 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
398 formats_.api_format.output_stream().sample_rate_hz() &&
399 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
400 capture_.capture_fullband_audio.reset(
401 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
402 formats_.api_format.input_stream().num_channels(),
403 formats_.api_format.output_stream().sample_rate_hz(),
404 formats_.api_format.output_stream().num_channels(),
405 formats_.api_format.output_stream().sample_rate_hz(),
406 formats_.api_format.output_stream().num_channels()));
407 } else {
408 capture_.capture_fullband_audio.reset();
409 }
410
peah764e3642016-10-22 05:04:30 -0700411 AllocateRenderQueue();
412
Per Åhgren0695df12020-01-13 14:43:13 +0100413 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100414 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100415 InitializeHighPassFilter(true);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200416 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700417 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200418 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700419 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200420 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200421 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200422 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100423 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800424
aleloi868f32f2017-05-23 07:20:05 -0700425 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200426 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700427 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000428 return kNoError;
429}
430
Michael Graczyk86c6d332015-07-23 11:41:39 -0700431int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200432 UpdateActiveSubmoduleStates();
433
Michael Graczyk86c6d332015-07-23 11:41:39 -0700434 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700435 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
436 return kBadSampleRateError;
437 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000438 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700439
Peter Kasting69558702016-01-12 16:26:35 -0800440 const size_t num_in_channels = config.input_stream().num_channels();
441 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700442
443 // Need at least one input channel.
444 // Need either one output channel or as many outputs as there are inputs.
445 if (num_in_channels == 0 ||
446 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700447 return kBadNumberChannelsError;
448 }
449
peahdf3efa82015-11-28 12:35:15 -0800450 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000451
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200452 // Choose maximum rate to use for the split filtering.
453 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
454 config_.pipeline.maximum_internal_processing_rate == 32000);
455 int max_splitting_rate = 48000;
456 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
457 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
458 }
459
Per Åhgrenc8626b62019-08-23 15:49:51 +0200460 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700461 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700462 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200463 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700464 submodule_states_.CaptureMultiBandSubModulesActive() ||
465 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200466 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000467
peahde65ddc2016-09-16 15:02:15 -0700468 capture_nonlocked_.capture_processing_format =
469 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700470
peah2ce640f2017-04-07 03:57:48 -0700471 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200472 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200473 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700474 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
475 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200476 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700477 submodule_states_.CaptureMultiBandSubModulesActive() ||
478 submodule_states_.RenderMultiBandSubModulesActive());
479 } else {
480 render_processing_rate = capture_processing_rate;
481 }
482
peahde65ddc2016-09-16 15:02:15 -0700483 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700484 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700485 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
486 kSampleRate8kHz) {
487 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000488 } else {
peahde65ddc2016-09-16 15:02:15 -0700489 render_processing_rate =
490 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000491 }
492
Per Åhgrenc8626b62019-08-23 15:49:51 +0200493 RTC_DCHECK_NE(8000, render_processing_rate);
494
peahce4d9152017-05-19 01:28:05 -0700495 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200496 // By default, downmix the render stream to mono for analysis. This has been
497 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100498 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
499 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200500 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100501 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200502 ? formats_.api_format.reverse_input_stream().num_channels()
503 : 1;
504 formats_.render_processing_format =
505 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700506 } else {
507 formats_.render_processing_format = StreamConfig(
508 formats_.api_format.reverse_input_stream().sample_rate_hz(),
509 formats_.api_format.reverse_input_stream().num_channels());
510 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000511
peahde65ddc2016-09-16 15:02:15 -0700512 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
513 kSampleRate32kHz ||
514 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
515 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800516 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000517 } else {
peahdf3efa82015-11-28 12:35:15 -0800518 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700519 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000520 }
521
522 return InitializeLocked();
523}
524
peah88ac8532016-09-12 16:47:25 -0700525void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200526 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
527
peah88ac8532016-09-12 16:47:25 -0700528 // Run in a single-threaded manner when applying the settings.
529 rtc::CritScope cs_render(&crit_render_);
530 rtc::CritScope cs_capture(&crit_capture_);
531
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200532 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100533 config_.pipeline.multi_channel_render !=
534 config.pipeline.multi_channel_render ||
535 config_.pipeline.multi_channel_capture !=
Per Åhgrenc0424252019-12-10 13:04:15 +0100536 config.pipeline.multi_channel_capture ||
537 config_.pipeline.maximum_internal_processing_rate !=
538 config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200539
Per Åhgren200feba2019-03-06 04:16:46 +0100540 const bool aec_config_changed =
541 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100542 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100543
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100544 const bool agc1_config_changed =
545 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
546 config_.gain_controller1.mode != config.gain_controller1.mode ||
547 config_.gain_controller1.target_level_dbfs !=
548 config.gain_controller1.target_level_dbfs ||
549 config_.gain_controller1.compression_gain_db !=
550 config.gain_controller1.compression_gain_db ||
551 config_.gain_controller1.enable_limiter !=
552 config.gain_controller1.enable_limiter ||
553 config_.gain_controller1.analog_level_minimum !=
554 config.gain_controller1.analog_level_minimum ||
555 config_.gain_controller1.analog_level_maximum !=
Per Åhgren0695df12020-01-13 14:43:13 +0100556 config.gain_controller1.analog_level_maximum ||
557 config_.gain_controller1.analog_gain_controller.enabled !=
558 config.gain_controller1.analog_gain_controller.enabled ||
559 config_.gain_controller1.analog_gain_controller.startup_min_volume !=
560 config.gain_controller1.analog_gain_controller.startup_min_volume ||
561 config_.gain_controller1.analog_gain_controller.clipped_level_min !=
562 config.gain_controller1.analog_gain_controller.clipped_level_min ||
563 config_.gain_controller1.analog_gain_controller
564 .enable_agc2_level_estimator !=
565 config.gain_controller1.analog_gain_controller
566 .enable_agc2_level_estimator ||
567 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive !=
568 config.gain_controller1.analog_gain_controller
569 .enable_digital_adaptive;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100570
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100571 const bool agc2_config_changed =
572 config_.gain_controller2.enabled != config.gain_controller2.enabled;
573
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200574 const bool voice_detection_config_changed =
575 config_.voice_detection.enabled != config.voice_detection.enabled;
576
saza0bad15f2019-10-16 11:46:11 +0200577 const bool ns_config_changed =
578 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
579 config_.noise_suppression.level != config.noise_suppression.level;
580
Per Åhgrenc0734712020-01-02 15:15:36 +0100581 const bool ts_config_changed = config_.transient_suppression.enabled !=
582 config.transient_suppression.enabled;
583
Per Åhgren0f14db22020-01-03 14:27:14 +0100584 const bool pre_amplifier_config_changed =
585 config_.pre_amplifier.enabled != config.pre_amplifier.enabled ||
586 config_.pre_amplifier.fixed_gain_factor !=
587 config.pre_amplifier.fixed_gain_factor;
588
Yves Gerey499bc6c2018-10-10 18:29:07 +0200589 config_ = config;
590
Per Åhgren200feba2019-03-06 04:16:46 +0100591 if (aec_config_changed) {
592 InitializeEchoController();
593 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200594
saza0bad15f2019-10-16 11:46:11 +0200595 if (ns_config_changed) {
596 InitializeNoiseSuppressor();
597 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100598
Per Åhgrenc0734712020-01-02 15:15:36 +0100599 if (ts_config_changed) {
600 InitializeTransientSuppressor();
601 }
602
Per Åhgren0f14db22020-01-03 14:27:14 +0100603 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800604
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100605 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100606 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100607 }
608
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100609 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700610 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100611 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
612 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100613 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100614 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700615 config_.gain_controller2 = AudioProcessing::Config::GainController2();
616 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100617
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100618 if (agc2_config_changed) {
619 InitializeGainController2();
620 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100621
622 if (pre_amplifier_config_changed) {
623 InitializePreAmplifier();
624 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100625
saza1d600522019-10-18 13:29:43 +0200626 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
627 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100628 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100629
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200630 if (voice_detection_config_changed) {
631 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100632 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200633
634 // Reinitialization must happen after all submodule configuration to avoid
635 // additional reinitializations on the next capture / render processing call.
636 if (pipeline_config_changed) {
637 InitializeLocked(formats_.api_format);
638 }
peah88ac8532016-09-12 16:47:25 -0700639}
640
Per Åhgrenc0734712020-01-02 15:15:36 +0100641// TODO(webrtc:5298): Remove.
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100642void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {}
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000643
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200644void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
645 const ApmSubmoduleCreationOverrides& overrides) {
646 rtc::CritScope cs(&crit_capture_);
647 submodule_creation_overrides_ = overrides;
648}
649
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000650int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800651 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700652 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000653}
654
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200655int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
656 return capture_.capture_fullband_audio
657 ? capture_.capture_fullband_audio->num_frames() * 100
658 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
659}
660
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000661int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800662 // Used as callback from submodules, hence locking is not allowed.
663 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000664}
665
Peter Kasting69558702016-01-12 16:26:35 -0800666size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800667 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700668 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000669}
670
Peter Kasting69558702016-01-12 16:26:35 -0800671size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800672 // Used as callback from submodules, hence locking is not allowed.
673 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000674}
675
Peter Kasting69558702016-01-12 16:26:35 -0800676size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800677 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100678 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
679 constants_.multi_channel_capture_support;
680 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200681 return 1;
682 }
683 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800684}
685
Peter Kasting69558702016-01-12 16:26:35 -0800686size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800687 // Used as callback from submodules, hence locking is not allowed.
688 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000689}
690
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000691void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800692 rtc::CritScope cs(&crit_capture_);
693 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200694 if (submodules_.agc_manager.get()) {
695 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000696 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000697}
698
Alessio Bazzicac054e782018-04-16 12:10:09 +0200699void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200700 switch (setting.type()) {
701 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100702 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200703 render_runtime_settings_enqueuer_.Enqueue(setting);
704 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200705 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100706 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200707 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100708 capture_runtime_settings_enqueuer_.Enqueue(setting);
709 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200710 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200711 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100712 render_runtime_settings_enqueuer_.Enqueue(setting);
713 return;
714 case RuntimeSetting::Type::kNotSpecified:
715 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200716 return;
717 }
718 // The language allows the enum to have a non-enumerator
719 // value. Check that this doesn't happen.
720 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200721}
722
723AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
724 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200725 : runtime_settings_(*runtime_settings) {
726 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200727}
728
729AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
730 default;
731
732void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
733 RuntimeSetting setting) {
734 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200735 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200736 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200737 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200738 RTC_LOG(LS_ERROR)
739 << "The runtime settings queue is full. Oldest setting discarded.";
740 }
741 if (remaining_attempts == 0)
742 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
743}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000744
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100745int AudioProcessingImpl::MaybeInitializeCapture(
746 const StreamConfig& input_config,
747 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -0800748 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700749 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800750 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100751 // Acquire the capture lock in order to access api_format. The lock is
752 // released immediately, as we may need to acquire the render lock as part
753 // of the conditional reinitialization.
peahdf3efa82015-11-28 12:35:15 -0800754 rtc::CritScope cs_capture(&crit_capture_);
peahdf3efa82015-11-28 12:35:15 -0800755 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700756 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000757 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000758
Oskar Sundbom4b276482019-05-23 14:28:00 +0200759 if (processing_config.input_stream() != input_config) {
760 processing_config.input_stream() = input_config;
761 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800762 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200763
764 if (processing_config.output_stream() != output_config) {
765 processing_config.output_stream() = output_config;
766 reinitialization_required = true;
767 }
768
769 if (reinitialization_required) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200770 rtc::CritScope cs_render(&crit_render_);
771 rtc::CritScope cs_capture(&crit_capture_);
772 RETURN_ON_ERR(InitializeLocked(processing_config));
773 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100774 return kNoError;
775}
776
777int AudioProcessingImpl::ProcessStream(const float* const* src,
778 const StreamConfig& input_config,
779 const StreamConfig& output_config,
780 float* const* dest) {
781 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
782 if (!src || !dest) {
783 return kNullPointerError;
784 }
785
786 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +0200787
peahdf3efa82015-11-28 12:35:15 -0800788 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000789
aleloi868f32f2017-05-23 07:20:05 -0700790 if (aec_dump_) {
791 RecordUnprocessedCaptureStream(src);
792 }
793
Per Åhgrena1351272019-08-15 12:15:46 +0200794 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800795 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200796 if (capture_.capture_fullband_audio) {
797 capture_.capture_fullband_audio->CopyFrom(
798 src, formats_.api_format.input_stream());
799 }
peahde65ddc2016-09-16 15:02:15 -0700800 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200801 if (capture_.capture_fullband_audio) {
802 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
803 dest);
804 } else {
805 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
806 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000807
aleloi868f32f2017-05-23 07:20:05 -0700808 if (aec_dump_) {
809 RecordProcessedCaptureStream(dest);
810 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000811 return kNoError;
812}
813
Alex Loiko73ec0192018-05-15 10:52:28 +0200814void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200815 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200816 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200817 if (aec_dump_) {
818 aec_dump_->WriteRuntimeSetting(setting);
819 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200820 switch (setting.type()) {
821 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200822 if (config_.pre_amplifier.enabled) {
823 float value;
824 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200825 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200826 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200827 }
828 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200829 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100830 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100831 if (!submodules_.agc_manager) {
832 float value;
833 setting.GetFloat(&value);
834 int int_value = static_cast<int>(value + .5f);
835 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +0100836 if (submodules_.gain_control) {
837 int error =
838 submodules_.gain_control->set_compression_gain_db(int_value);
839 RTC_DCHECK_EQ(kNoError, error);
840 }
Per Åhgren0e3198e2019-11-18 08:52:22 +0100841 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100842 break;
843 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200844 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100845 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200846 float value;
847 setting.GetFloat(&value);
848 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200849 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200850 }
851 break;
852 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200853 case RuntimeSetting::Type::kPlayoutVolumeChange: {
854 int value;
855 setting.GetInt(&value);
856 capture_.playout_volume = value;
857 break;
858 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100859 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
860 RTC_NOTREACHED();
861 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200862 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
863 RTC_NOTREACHED();
864 break;
865 case RuntimeSetting::Type::kNotSpecified:
866 RTC_NOTREACHED();
867 break;
868 }
869 }
870}
871
872void AudioProcessingImpl::HandleRenderRuntimeSettings() {
873 RuntimeSetting setting;
874 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200875 if (aec_dump_) {
876 aec_dump_->WriteRuntimeSetting(setting);
877 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200878 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100879 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100880 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200881 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200882 if (submodules_.render_pre_processor) {
883 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200884 }
885 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100886 case RuntimeSetting::Type::kCapturePreGain: // fall-through
887 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200888 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200889 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200890 RTC_NOTREACHED();
891 break;
892 }
893 }
894}
895
peah9e6a2902017-05-15 07:19:21 -0700896void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800897 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700898
saza1d600522019-10-18 13:29:43 +0200899 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200900 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
901 num_reverse_channels(),
902 &aecm_render_queue_buffer_);
903 RTC_DCHECK(aecm_render_signal_queue_);
904 // Insert the samples into the queue.
905 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
906 // The data queue is full and needs to be emptied.
907 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -0700908
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200909 // Retry the insert (should always work).
910 bool result =
911 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
912 RTC_DCHECK(result);
913 }
peah764e3642016-10-22 05:04:30 -0700914 }
peah701d6282016-10-25 05:42:20 -0700915
Per Åhgren0695df12020-01-13 14:43:13 +0100916 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +0100917 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -0700918 // Insert the samples into the queue.
919 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
920 // The data queue is full and needs to be emptied.
921 EmptyQueuedRenderAudio();
922
923 // Retry the insert (should always work).
924 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
925 RTC_DCHECK(result);
926 }
927 }
peah9e6a2902017-05-15 07:19:21 -0700928}
ivoc9f4a4a02016-10-28 05:39:16 -0700929
peah9e6a2902017-05-15 07:19:21 -0700930void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700931 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
932
933 // Insert the samples into the queue.
934 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
935 // The data queue is full and needs to be emptied.
936 EmptyQueuedRenderAudio();
937
938 // Retry the insert (should always work).
939 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
940 RTC_DCHECK(result);
941 }
peah764e3642016-10-22 05:04:30 -0700942}
943
944void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700945 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700946 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700947
ivoc9f4a4a02016-10-28 05:39:16 -0700948 const size_t new_red_render_queue_element_max_size =
949 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
950
peaha0624602016-10-25 04:45:24 -0700951 // Reallocate the queues if the queue item sizes are too small to fit the
952 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700953
954 if (agc_render_queue_element_max_size_ <
955 new_agc_render_queue_element_max_size) {
956 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
957
958 std::vector<int16_t> template_queue_element(
959 agc_render_queue_element_max_size_);
960
961 agc_render_signal_queue_.reset(
962 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
963 kMaxNumFramesToBuffer, template_queue_element,
964 RenderQueueItemVerifier<int16_t>(
965 agc_render_queue_element_max_size_)));
966
967 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
968 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
969 } else {
970 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700971 }
ivoc9f4a4a02016-10-28 05:39:16 -0700972
973 if (red_render_queue_element_max_size_ <
974 new_red_render_queue_element_max_size) {
975 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
976
977 std::vector<float> template_queue_element(
978 red_render_queue_element_max_size_);
979
980 red_render_signal_queue_.reset(
981 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
982 kMaxNumFramesToBuffer, template_queue_element,
983 RenderQueueItemVerifier<float>(
984 red_render_queue_element_max_size_)));
985
986 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
987 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
988 } else {
989 red_render_signal_queue_->Clear();
990 }
peah764e3642016-10-22 05:04:30 -0700991}
992
993void AudioProcessingImpl::EmptyQueuedRenderAudio() {
994 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +0200995 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200996 RTC_DCHECK(aecm_render_signal_queue_);
997 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +0200998 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200999 aecm_capture_queue_buffer_);
1000 }
peah701d6282016-10-25 05:42:20 -07001001 }
1002
Per Åhgren0695df12020-01-13 14:43:13 +01001003 if (submodules_.gain_control) {
1004 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1005 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1006 }
peah764e3642016-10-22 05:04:30 -07001007 }
ivoc9f4a4a02016-10-28 05:39:16 -07001008
1009 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001010 RTC_DCHECK(submodules_.echo_detector);
1011 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001012 }
peah764e3642016-10-22 05:04:30 -07001013}
1014
Per Åhgren645f24c2020-03-16 12:06:02 +01001015int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1016 const StreamConfig& input_config,
1017 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001018 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001019 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001020 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +02001021
peahdf3efa82015-11-28 12:35:15 -08001022 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001023
aleloi868f32f2017-05-23 07:20:05 -07001024 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001025 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001026 }
1027
Per Åhgren645f24c2020-03-16 12:06:02 +01001028 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001029 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001030 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001031 }
peahde65ddc2016-09-16 15:02:15 -07001032 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001033 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001034 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001035 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001036 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001037 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001038 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001039 }
Per Åhgrena1351272019-08-15 12:15:46 +02001040 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001041
aleloi868f32f2017-05-23 07:20:05 -07001042 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001043 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001044 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001045
1046 return kNoError;
1047}
1048
peahde65ddc2016-09-16 15:02:15 -07001049int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001050 EmptyQueuedRenderAudio();
Alex Loiko73ec0192018-05-15 10:52:28 +02001051 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001052
peahb58a1582016-03-15 09:34:24 -07001053 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001054 // TODO(peah): Simplify once the public API Enable functions for these
1055 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001056 RTC_DCHECK_LE(
1057 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001058
peahde65ddc2016-09-16 15:02:15 -07001059 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001060 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001061
Per Åhgrenc0424252019-12-10 13:04:15 +01001062 if (submodules_.high_pass_filter &&
1063 config_.high_pass_filter.apply_in_full_band &&
1064 !constants_.enforce_split_band_hpf) {
1065 submodules_.high_pass_filter->Process(capture_buffer,
1066 /*use_split_band_data=*/false);
1067 }
1068
saza1d600522019-10-18 13:29:43 +02001069 if (submodules_.pre_amplifier) {
1070 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001071 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001072 capture_buffer->num_frames()));
1073 }
1074
Per Åhgren928146f2019-08-20 09:19:21 +02001075 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001076 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001077 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001078 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1079 if (log_rms) {
1080 capture_rms_interval_counter_ = 0;
1081 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001082 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1083 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1084 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1085 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001086 }
1087
saza1d600522019-10-18 13:29:43 +02001088 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001089 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001090 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001091 capture_.echo_path_gain_change =
1092 capture_.prev_analog_mic_level != analog_mic_level &&
1093 capture_.prev_analog_mic_level != -1;
1094 capture_.prev_analog_mic_level = analog_mic_level;
1095
Per Åhgrend2650d12018-10-02 17:00:59 +02001096 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001097 if (submodules_.pre_amplifier) {
1098 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001099 capture_.echo_path_gain_change =
1100 capture_.echo_path_gain_change ||
1101 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001102 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001103 capture_.prev_pre_amp_gain = pre_amp_gain;
1104 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001105
1106 // Detect volume change.
1107 capture_.echo_path_gain_change =
1108 capture_.echo_path_gain_change ||
1109 (capture_.prev_playout_volume != capture_.playout_volume &&
1110 capture_.prev_playout_volume >= 0);
1111 capture_.prev_playout_volume = capture_.playout_volume;
1112
saza1d600522019-10-18 13:29:43 +02001113 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001114 }
1115
Per Åhgren0695df12020-01-13 14:43:13 +01001116 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001117 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001118 }
1119
peah2ace3f92016-09-10 04:42:27 -07001120 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1121 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001122 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1123 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001124 }
1125
Per Åhgrene14cb992019-11-27 09:34:22 +01001126 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1127 constants_.multi_channel_capture_support;
1128 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001129 // Force down-mixing of the number of channels after the detection of
1130 // capture signal saturation.
1131 // TODO(peah): Look into ensuring that this kind of tampering with the
1132 // AudioBuffer functionality should not be needed.
1133 capture_buffer->set_num_channels(1);
1134 }
1135
Per Åhgrenc0424252019-12-10 13:04:15 +01001136 if (submodules_.high_pass_filter &&
1137 (!config_.high_pass_filter.apply_in_full_band ||
1138 constants_.enforce_split_band_hpf)) {
1139 submodules_.high_pass_filter->Process(capture_buffer,
1140 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001141 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001142
Per Åhgren0695df12020-01-13 14:43:13 +01001143 if (submodules_.gain_control) {
1144 RETURN_ON_ERR(
1145 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1146 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001147
Per Åhgren8ad9e742020-01-30 07:40:58 +01001148 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1149 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1150 submodules_.noise_suppressor) {
1151 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001152 }
peahb58a1582016-03-15 09:34:24 -07001153
saza1d600522019-10-18 13:29:43 +02001154 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001155 // Ensure that the stream delay was set before the call to the
1156 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001157 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001158 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001159 }
1160
saza1d600522019-10-18 13:29:43 +02001161 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001162 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001163 }
peahe0eae3c2016-12-14 01:16:23 -08001164
saza1d600522019-10-18 13:29:43 +02001165 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001166 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001167 } else {
saza1d600522019-10-18 13:29:43 +02001168 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001169 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1170
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001171 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001172 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001173 }
1174
saza1d600522019-10-18 13:29:43 +02001175 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001176 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001177 }
1178
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001179 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001180 linear_aec_buffer && submodules_.noise_suppressor) {
1181 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001182 }
1183
saza1d600522019-10-18 13:29:43 +02001184 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001185 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001186 }
Per Åhgren46537a32017-06-07 10:08:10 +02001187 }
ivoc9f4a4a02016-10-28 05:39:16 -07001188
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001189 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001190 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001191 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001192 } else {
1193 capture_.stats.voice_detected = absl::nullopt;
1194 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001195
Per Åhgren0695df12020-01-13 14:43:13 +01001196 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001197 submodules_.agc_manager->Process(capture_buffer);
1198
1199 absl::optional<int> new_digital_gain =
1200 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001201 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001202 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1203 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001204 }
Per Åhgren0695df12020-01-13 14:43:13 +01001205
1206 if (submodules_.gain_control) {
1207 // TODO(peah): Add reporting from AEC3 whether there is echo.
1208 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1209 capture_buffer, /*stream_has_echo*/ false));
1210 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001211
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001212 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001213 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001214 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1215 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001216 }
1217
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001218 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001219 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001220 bool ec_active = ec ? ec->ActiveProcessing() : false;
1221 // Only update the fullband buffer if the multiband processing has changed
1222 // the signal. Keep the original signal otherwise.
1223 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1224 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1225 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001226 capture_buffer = capture_.capture_fullband_audio.get();
1227 }
1228
peah9e6a2902017-05-15 07:19:21 -07001229 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001230 RTC_DCHECK(submodules_.echo_detector);
1231 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1232 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001233 }
1234
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001235 // TODO(aluebs): Investigate if the transient suppression placement should be
1236 // before or after the AGC.
Per Åhgrenc0734712020-01-02 15:15:36 +01001237 if (submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001238 float voice_probability = submodules_.agc_manager.get()
1239 ? submodules_.agc_manager->voice_probability()
1240 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001241
saza1d600522019-10-18 13:29:43 +02001242 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001243 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001244 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001245 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001246 capture_buffer->num_frames_per_band(),
1247 capture_.keyboard_info.keyboard_data,
1248 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001249 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001250 }
1251
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001252 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001253 if (submodules_.capture_analyzer) {
1254 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001255 }
1256
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001257 if (submodules_.gain_controller2) {
saza1d600522019-10-18 13:29:43 +02001258 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001259 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001260 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001261 }
1262
saza1d600522019-10-18 13:29:43 +02001263 if (submodules_.capture_post_processor) {
1264 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001265 }
1266
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001267 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001268 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001269 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1270 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001271 } else {
1272 capture_.stats.output_rms_dbfs = absl::nullopt;
1273 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001274
Per Åhgren928146f2019-08-20 09:19:21 +02001275 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001276 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001277 capture_nonlocked_.capture_processing_format.num_frames()));
1278 if (log_rms) {
1279 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1280 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1281 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1282 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1283 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1284 }
1285
Per Åhgren0e3198e2019-11-18 08:52:22 +01001286 if (submodules_.agc_manager) {
1287 int level = recommended_stream_analog_level();
1288 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1289 &level);
1290 }
1291
Per Åhgrencf4c8722019-12-30 14:32:14 +01001292 // Compute echo-related stats.
1293 if (submodules_.echo_controller) {
1294 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1295 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1296 capture_.stats.echo_return_loss_enhancement =
1297 ec_metrics.echo_return_loss_enhancement;
1298 capture_.stats.delay_ms = ec_metrics.delay_ms;
1299 }
1300 if (config_.residual_echo_detector.enabled) {
1301 RTC_DCHECK(submodules_.echo_detector);
1302 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1303 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1304 capture_.stats.residual_echo_likelihood_recent_max =
1305 ed_metrics.echo_likelihood_recent_max;
1306 }
1307
1308 // Pass stats for reporting.
1309 stats_reporter_.UpdateStatistics(capture_.stats);
1310
peahdf3efa82015-11-28 12:35:15 -08001311 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001312 return kNoError;
1313}
1314
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001315int AudioProcessingImpl::AnalyzeReverseStream(
1316 const float* const* data,
1317 const StreamConfig& reverse_config) {
1318 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1319 rtc::CritScope cs(&crit_render_);
1320 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1321}
1322
peahde65ddc2016-09-16 15:02:15 -07001323int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1324 const StreamConfig& input_config,
1325 const StreamConfig& output_config,
1326 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001327 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001328 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001329 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001330 if (submodule_states_.RenderMultiBandProcessingActive() ||
1331 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001332 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1333 dest);
peah2ace3f92016-09-10 04:42:27 -07001334 } else if (formats_.api_format.reverse_input_stream() !=
1335 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001336 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1337 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001338 } else {
peahde65ddc2016-09-16 15:02:15 -07001339 CopyAudioIfNeeded(src, input_config.num_frames(),
1340 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001341 }
1342
1343 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001344}
1345
peahdf3efa82015-11-28 12:35:15 -08001346int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001347 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001348 const StreamConfig& input_config,
1349 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001350 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001351 return kNullPointerError;
1352 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001353
peahde65ddc2016-09-16 15:02:15 -07001354 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001355 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001356 }
1357
peahdf3efa82015-11-28 12:35:15 -08001358 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001359 processing_config.reverse_input_stream() = input_config;
1360 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001361
peahdf3efa82015-11-28 12:35:15 -08001362 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001363 RTC_DCHECK_EQ(input_config.num_frames(),
1364 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001365
aleloi868f32f2017-05-23 07:20:05 -07001366 if (aec_dump_) {
1367 const size_t channel_size =
1368 formats_.api_format.reverse_input_stream().num_frames();
1369 const size_t num_channels =
1370 formats_.api_format.reverse_input_stream().num_channels();
1371 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001372 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001373 }
peahdf3efa82015-11-28 12:35:15 -08001374 render_.render_audio->CopyFrom(src,
1375 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001376 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001377}
1378
Per Åhgren645f24c2020-03-16 12:06:02 +01001379int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1380 const StreamConfig& input_config,
1381 const StreamConfig& output_config,
1382 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001383 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001384
1385 if (input_config.num_channels() <= 0) {
1386 return AudioProcessing::Error::kBadNumberChannelsError;
1387 }
1388
Per Åhgren645f24c2020-03-16 12:06:02 +01001389 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001390 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001391 processing_config.reverse_input_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001392 input_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001393 processing_config.reverse_input_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001394 input_config.num_channels());
ekmeyerson60d9b332015-08-14 10:35:55 -07001395 processing_config.reverse_output_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001396 output_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001397 processing_config.reverse_output_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001398 output_config.num_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001399
peahdf3efa82015-11-28 12:35:15 -08001400 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Per Åhgren645f24c2020-03-16 12:06:02 +01001401 if (input_config.num_frames() !=
peahdf3efa82015-11-28 12:35:15 -08001402 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001403 return kBadDataLengthError;
1404 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001405
aleloi868f32f2017-05-23 07:20:05 -07001406 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001407 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1408 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001409 }
1410
Per Åhgren645f24c2020-03-16 12:06:02 +01001411 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001412 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001413 if (submodule_states_.RenderMultiBandProcessingActive() ||
1414 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001415 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001416 }
aluebsb0319552016-03-17 20:39:53 -07001417 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001418}
niklase@google.com470e71d2011-07-07 08:21:25 +00001419
peahde65ddc2016-09-16 15:02:15 -07001420int AudioProcessingImpl::ProcessRenderStreamLocked() {
1421 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001422
Alex Loiko73ec0192018-05-15 10:52:28 +02001423 HandleRenderRuntimeSettings();
1424
saza1d600522019-10-18 13:29:43 +02001425 if (submodules_.render_pre_processor) {
1426 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001427 }
1428
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001429 QueueNonbandedRenderAudio(render_buffer);
1430
peah2ace3f92016-09-10 04:42:27 -07001431 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001432 SampleRateSupportsMultiBand(
1433 formats_.render_processing_format.sample_rate_hz())) {
1434 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001435 }
1436
peahce4d9152017-05-19 01:28:05 -07001437 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1438 QueueBandedRenderAudio(render_buffer);
1439 }
1440
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001441 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001442 if (submodules_.echo_controller) {
1443 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001444 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001445
peah2ace3f92016-09-10 04:42:27 -07001446 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001447 SampleRateSupportsMultiBand(
1448 formats_.render_processing_format.sample_rate_hz())) {
1449 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001450 }
1451
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001452 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001453}
1454
1455int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001456 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001457 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001458 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001459
niklase@google.com470e71d2011-07-07 08:21:25 +00001460 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001461 delay = 0;
1462 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001463 }
1464
1465 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1466 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001467 delay = 500;
1468 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001469 }
1470
peahdf3efa82015-11-28 12:35:15 -08001471 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001472 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001473}
1474
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001475bool AudioProcessingImpl::GetLinearAecOutput(
1476 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1477 rtc::CritScope cs(&crit_capture_);
1478 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1479
1480 RTC_DCHECK(linear_aec_buffer);
1481 if (linear_aec_buffer) {
1482 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1483 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1484
1485 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1486 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1487 rtc::ArrayView<const float> channel_view =
1488 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1489 linear_aec_buffer->num_frames());
1490 std::copy(channel_view.begin(), channel_view.end(),
1491 linear_output[ch].begin());
1492 }
1493 return true;
1494 }
1495 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1496 RTC_NOTREACHED();
1497 return false;
1498}
1499
niklase@google.com470e71d2011-07-07 08:21:25 +00001500int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001501 // Used as callback from submodules, hence locking is not allowed.
1502 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001503}
1504
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001505void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001506 rtc::CritScope cs(&crit_capture_);
1507 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001508}
1509
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001510void AudioProcessingImpl::set_stream_analog_level(int level) {
1511 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001512
1513 if (submodules_.agc_manager) {
1514 submodules_.agc_manager->set_stream_analog_level(level);
1515 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1516 1, &level);
Per Åhgren0695df12020-01-13 14:43:13 +01001517 } else if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001518 int error = submodules_.gain_control->set_stream_analog_level(level);
1519 RTC_DCHECK_EQ(kNoError, error);
Per Åhgren0695df12020-01-13 14:43:13 +01001520 } else {
1521 capture_.cached_stream_analog_level_ = level;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001522 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001523}
1524
1525int AudioProcessingImpl::recommended_stream_analog_level() const {
1526 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001527 if (submodules_.agc_manager) {
1528 return submodules_.agc_manager->stream_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01001529 } else if (submodules_.gain_control) {
1530 return submodules_.gain_control->stream_analog_level();
1531 } else {
1532 return capture_.cached_stream_analog_level_;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001533 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001534}
1535
Per Åhgren09e9a832020-05-11 11:03:47 +02001536bool AudioProcessingImpl::CreateAndAttachAecDump(const std::string& file_name,
1537 int64_t max_log_size_bytes,
1538 rtc::TaskQueue* worker_queue) {
1539 std::unique_ptr<AecDump> aec_dump =
1540 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
1541 if (!aec_dump) {
1542 return false;
1543 }
1544
1545 AttachAecDump(std::move(aec_dump));
1546 return true;
1547}
1548
1549bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
1550 int64_t max_log_size_bytes,
1551 rtc::TaskQueue* worker_queue) {
1552 std::unique_ptr<AecDump> aec_dump =
1553 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
1554 if (!aec_dump) {
1555 return false;
1556 }
1557
1558 AttachAecDump(std::move(aec_dump));
1559 return true;
1560}
1561
aleloi868f32f2017-05-23 07:20:05 -07001562void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1563 RTC_DCHECK(aec_dump);
1564 rtc::CritScope cs_render(&crit_render_);
1565 rtc::CritScope cs_capture(&crit_capture_);
1566
1567 // The previously attached AecDump will be destroyed with the
1568 // 'aec_dump' parameter, which is after locks are released.
1569 aec_dump_.swap(aec_dump);
1570 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001571 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001572}
1573
1574void AudioProcessingImpl::DetachAecDump() {
1575 // The d-tor of a task-queue based AecDump blocks until all pending
1576 // tasks are done. This construction avoids blocking while holding
1577 // the render and capture locks.
1578 std::unique_ptr<AecDump> aec_dump = nullptr;
1579 {
1580 rtc::CritScope cs_render(&crit_render_);
1581 rtc::CritScope cs_capture(&crit_capture_);
1582 aec_dump = std::move(aec_dump_);
1583 }
1584}
1585
peah8271d042016-11-22 07:24:52 -08001586void AudioProcessingImpl::MutateConfig(
1587 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1588 rtc::CritScope cs_render(&crit_render_);
1589 rtc::CritScope cs_capture(&crit_capture_);
1590 mutator(&config_);
1591 ApplyConfig(config_);
1592}
1593
1594AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1595 rtc::CritScope cs_render(&crit_render_);
1596 rtc::CritScope cs_capture(&crit_capture_);
1597 return config_;
1598}
1599
peah2ace3f92016-09-10 04:42:27 -07001600bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1601 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001602 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Per Åhgren8ad9e742020-01-30 07:40:58 +01001603 config_.residual_echo_detector.enabled, !!submodules_.noise_suppressor,
Per Åhgren0695df12020-01-13 14:43:13 +01001604 !!submodules_.gain_control, !!submodules_.gain_controller2,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001605 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
Per Åhgrenc0734712020-01-02 15:15:36 +01001606 config_.voice_detection.enabled, !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001607}
1608
Per Åhgrenc0734712020-01-02 15:15:36 +01001609void AudioProcessingImpl::InitializeTransientSuppressor() {
1610 if (config_.transient_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02001611 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01001612 if (!submodules_.transient_suppressor) {
Sam Zackrissonb37e59d2020-04-27 08:39:33 +02001613 submodules_.transient_suppressor =
1614 CreateTransientSuppressor(submodule_creation_overrides_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001615 }
sazaaa42ecd2020-04-01 15:24:40 +02001616 if (submodules_.transient_suppressor) {
1617 submodules_.transient_suppressor->Initialize(
1618 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1619 num_proc_channels());
1620 } else {
1621 RTC_LOG(LS_WARNING)
1622 << "No transient suppressor created (probably disabled)";
1623 }
Per Åhgrenc0734712020-01-02 15:15:36 +01001624 } else {
1625 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001626 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001627}
1628
Per Åhgren0f14db22020-01-03 14:27:14 +01001629void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01001630 bool high_pass_filter_needed_by_aec =
1631 config_.echo_canceller.enabled &&
1632 config_.echo_canceller.enforce_high_pass_filtering &&
1633 !config_.echo_canceller.mobile_mode;
1634 if (submodule_states_.HighPassFilteringRequired() ||
1635 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001636 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1637 !constants_.enforce_split_band_hpf;
1638 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1639 : proc_split_sample_rate_hz();
1640 size_t num_channels =
1641 use_full_band ? num_output_channels() : num_proc_channels();
1642
Per Åhgren0f14db22020-01-03 14:27:14 +01001643 if (!submodules_.high_pass_filter ||
1644 rate != submodules_.high_pass_filter->sample_rate_hz() ||
1645 forced_reset ||
1646 num_channels != submodules_.high_pass_filter->num_channels()) {
1647 submodules_.high_pass_filter.reset(
1648 new HighPassFilter(rate, num_channels));
1649 }
peah8271d042016-11-22 07:24:52 -08001650 } else {
saza1d600522019-10-18 13:29:43 +02001651 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001652 }
1653}
alessiob3ec96df2017-05-22 06:57:06 -07001654
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001655void AudioProcessingImpl::InitializeVoiceDetector() {
1656 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001657 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001658 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1659 } else {
saza1d600522019-10-18 13:29:43 +02001660 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001661 }
1662}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001663void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001664 bool use_echo_controller =
1665 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001666 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001667
1668 if (use_echo_controller) {
1669 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001670 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001671 submodules_.echo_controller = echo_control_factory_->Create(
1672 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001673 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001674 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001675 EchoCanceller3Config config =
1676 use_setup_specific_default_aec3_config_
1677 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1678 num_proc_channels())
1679 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001680 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001681 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001682 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001683 }
1684
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001685 // Setup the storage for returning the linear AEC output.
1686 if (config_.echo_canceller.export_linear_aec_output) {
1687 constexpr int kLinearOutputRateHz = 16000;
1688 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1689 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1690 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1691 } else {
1692 capture_.linear_aec_output.reset();
1693 }
1694
Per Åhgren200feba2019-03-06 04:16:46 +01001695 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001696
saza1d600522019-10-18 13:29:43 +02001697 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001698 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001699 return;
peahe0eae3c2016-12-14 01:16:23 -08001700 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001701
saza1d600522019-10-18 13:29:43 +02001702 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001703 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001704 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001705
1706 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001707 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001708 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001709 return;
1710 }
1711
1712 if (config_.echo_canceller.mobile_mode) {
1713 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001714 size_t max_element_size =
1715 std::max(static_cast<size_t>(1),
1716 kMaxAllowedValuesOfSamplesPerBand *
1717 EchoControlMobileImpl::NumCancellersRequired(
1718 num_output_channels(), num_reverse_channels()));
1719
1720 std::vector<int16_t> template_queue_element(max_element_size);
1721
1722 aecm_render_signal_queue_.reset(
1723 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1724 kMaxNumFramesToBuffer, template_queue_element,
1725 RenderQueueItemVerifier<int16_t>(max_element_size)));
1726
1727 aecm_render_queue_buffer_.resize(max_element_size);
1728 aecm_capture_queue_buffer_.resize(max_element_size);
1729
saza1d600522019-10-18 13:29:43 +02001730 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001731
saza1d600522019-10-18 13:29:43 +02001732 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1733 num_reverse_channels(),
1734 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001735 return;
1736 }
1737
saza1d600522019-10-18 13:29:43 +02001738 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001739 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001740}
peah8271d042016-11-22 07:24:52 -08001741
Per Åhgren0695df12020-01-13 14:43:13 +01001742void AudioProcessingImpl::InitializeGainController1() {
1743 if (!config_.gain_controller1.enabled) {
1744 submodules_.agc_manager.reset();
1745 submodules_.gain_control.reset();
1746 return;
1747 }
1748
1749 if (!submodules_.gain_control) {
1750 submodules_.gain_control.reset(new GainControlImpl());
1751 }
1752
1753 submodules_.gain_control->Initialize(num_proc_channels(),
1754 proc_sample_rate_hz());
1755
1756 if (!config_.gain_controller1.analog_gain_controller.enabled) {
1757 int error = submodules_.gain_control->set_mode(
1758 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
1759 RTC_DCHECK_EQ(kNoError, error);
1760 error = submodules_.gain_control->set_target_level_dbfs(
1761 config_.gain_controller1.target_level_dbfs);
1762 RTC_DCHECK_EQ(kNoError, error);
1763 error = submodules_.gain_control->set_compression_gain_db(
1764 config_.gain_controller1.compression_gain_db);
1765 RTC_DCHECK_EQ(kNoError, error);
1766 error = submodules_.gain_control->enable_limiter(
1767 config_.gain_controller1.enable_limiter);
1768 RTC_DCHECK_EQ(kNoError, error);
1769 error = submodules_.gain_control->set_analog_level_limits(
1770 config_.gain_controller1.analog_level_minimum,
1771 config_.gain_controller1.analog_level_maximum);
1772 RTC_DCHECK_EQ(kNoError, error);
1773
1774 submodules_.agc_manager.reset();
1775 return;
1776 }
1777
1778 if (!submodules_.agc_manager.get() ||
1779 submodules_.agc_manager->num_channels() !=
1780 static_cast<int>(num_proc_channels()) ||
1781 submodules_.agc_manager->sample_rate_hz() !=
1782 capture_nonlocked_.split_rate) {
1783 int stream_analog_level = -1;
1784 const bool re_creation = !!submodules_.agc_manager;
1785 if (re_creation) {
1786 stream_analog_level = submodules_.agc_manager->stream_analog_level();
1787 }
1788 submodules_.agc_manager.reset(new AgcManagerDirect(
1789 num_proc_channels(),
1790 config_.gain_controller1.analog_gain_controller.startup_min_volume,
1791 config_.gain_controller1.analog_gain_controller.clipped_level_min,
1792 config_.gain_controller1.analog_gain_controller
1793 .enable_agc2_level_estimator,
1794 !config_.gain_controller1.analog_gain_controller
1795 .enable_digital_adaptive,
1796 capture_nonlocked_.split_rate));
1797 if (re_creation) {
1798 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
1799 }
1800 }
1801 submodules_.agc_manager->Initialize();
1802 submodules_.agc_manager->SetupDigitalGainControl(
1803 submodules_.gain_control.get());
1804 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
1805}
1806
alessiob3ec96df2017-05-22 06:57:06 -07001807void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001808 if (config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001809 if (!submodules_.gain_controller2) {
1810 // TODO(alessiob): Move the injected gain controller once injection is
1811 // implemented.
1812 submodules_.gain_controller2.reset(new GainController2());
1813 }
1814
saza1d600522019-10-18 13:29:43 +02001815 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001816 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
1817 } else {
1818 submodules_.gain_controller2.reset();
alessiob3ec96df2017-05-22 06:57:06 -07001819 }
1820}
1821
saza0bad15f2019-10-16 11:46:11 +02001822void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001823 submodules_.noise_suppressor.reset();
1824
saza0bad15f2019-10-16 11:46:11 +02001825 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02001826 auto map_level =
1827 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1828 using NoiseSuppresionConfig =
1829 AudioProcessing::Config::NoiseSuppression;
1830 switch (level) {
1831 case NoiseSuppresionConfig::kLow:
1832 return NsConfig::SuppressionLevel::k6dB;
1833 case NoiseSuppresionConfig::kModerate:
1834 return NsConfig::SuppressionLevel::k12dB;
1835 case NoiseSuppresionConfig::kHigh:
1836 return NsConfig::SuppressionLevel::k18dB;
1837 case NoiseSuppresionConfig::kVeryHigh:
1838 return NsConfig::SuppressionLevel::k21dB;
1839 default:
1840 RTC_NOTREACHED();
1841 }
1842 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001843
sazaaa42ecd2020-04-01 15:24:40 +02001844 NsConfig cfg;
1845 cfg.target_level = map_level(config_.noise_suppression.level);
1846 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1847 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02001848 }
1849}
1850
Alex Loikob5c9a792018-04-16 16:31:22 +02001851void AudioProcessingImpl::InitializePreAmplifier() {
1852 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001853 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001854 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1855 } else {
saza1d600522019-10-18 13:29:43 +02001856 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001857 }
1858}
1859
ivoc9f4a4a02016-10-28 05:39:16 -07001860void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001861 RTC_DCHECK(submodules_.echo_detector);
1862 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001863 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001864 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001865}
1866
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001867void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001868 if (submodules_.capture_analyzer) {
1869 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1870 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001871 }
1872}
1873
Sam Zackrisson0beac582017-09-25 12:04:02 +02001874void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001875 if (submodules_.capture_post_processor) {
1876 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001877 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001878 }
1879}
1880
Alex Loiko5825aa62017-12-18 16:02:40 +01001881void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001882 if (submodules_.render_pre_processor) {
1883 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001884 formats_.render_processing_format.sample_rate_hz(),
1885 formats_.render_processing_format.num_channels());
1886 }
1887}
1888
aleloi868f32f2017-05-23 07:20:05 -07001889void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1890 if (!aec_dump_) {
1891 return;
1892 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001893
1894 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07001895 // TODO(peah): Add semicolon-separated concatenations of experiment
1896 // descriptions for other submodules.
Per Åhgren0695df12020-01-13 14:43:13 +01001897 if (config_.gain_controller1.analog_gain_controller.clipped_level_min !=
1898 kClippedLevelMin) {
aleloi868f32f2017-05-23 07:20:05 -07001899 experiments_description += "AgcClippingLevelExperiment;";
1900 }
Sam Zackrisson701bd172020-02-18 14:50:28 +01001901 if (!!submodules_.capture_post_processor) {
1902 experiments_description += "CapturePostProcessor;";
1903 }
1904 if (!!submodules_.render_pre_processor) {
1905 experiments_description += "RenderPreProcessor;";
1906 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001907 if (capture_nonlocked_.echo_controller_enabled) {
1908 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001909 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001910 if (config_.gain_controller2.enabled) {
1911 experiments_description += "GainController2;";
1912 }
aleloi868f32f2017-05-23 07:20:05 -07001913
1914 InternalAPMConfig apm_config;
1915
Per Åhgren200feba2019-03-06 04:16:46 +01001916 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001917 apm_config.aec_delay_agnostic_enabled = false;
1918 apm_config.aec_extended_filter_enabled = false;
1919 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07001920
saza1d600522019-10-18 13:29:43 +02001921 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07001922 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02001923 submodules_.echo_control_mobile &&
1924 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001925 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02001926 submodules_.echo_control_mobile
1927 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001928 : 0;
aleloi868f32f2017-05-23 07:20:05 -07001929
Per Åhgren0695df12020-01-13 14:43:13 +01001930 apm_config.agc_enabled = !!submodules_.gain_control;
1931
1932 apm_config.agc_mode = submodules_.gain_control
1933 ? static_cast<int>(submodules_.gain_control->mode())
1934 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07001935 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01001936 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
1937 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001938 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07001939
1940 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1941
saza0bad15f2019-10-16 11:46:11 +02001942 apm_config.ns_enabled = config_.noise_suppression.enabled;
1943 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07001944
1945 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01001946 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07001947 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001948 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1949 apm_config.pre_amplifier_fixed_gain_factor =
1950 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001951
1952 if (!forced && apm_config == apm_config_for_aec_dump_) {
1953 return;
1954 }
1955 aec_dump_->WriteConfig(apm_config);
1956 apm_config_for_aec_dump_ = apm_config;
1957}
1958
1959void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1960 const float* const* src) {
1961 RTC_DCHECK(aec_dump_);
1962 WriteAecDumpConfigMessage(false);
1963
1964 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1965 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1966 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001967 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001968 RecordAudioProcessingState();
1969}
1970
1971void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01001972 const int16_t* const data,
1973 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07001974 RTC_DCHECK(aec_dump_);
1975 WriteAecDumpConfigMessage(false);
1976
Per Åhgren645f24c2020-03-16 12:06:02 +01001977 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
1978 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07001979 RecordAudioProcessingState();
1980}
1981
1982void AudioProcessingImpl::RecordProcessedCaptureStream(
1983 const float* const* processed_capture_stream) {
1984 RTC_DCHECK(aec_dump_);
1985
1986 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1987 const size_t num_channels =
1988 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001989 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1990 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001991 aec_dump_->WriteCaptureStreamMessage();
1992}
1993
1994void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01001995 const int16_t* const data,
1996 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07001997 RTC_DCHECK(aec_dump_);
1998
Per Åhgren645f24c2020-03-16 12:06:02 +01001999 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002000 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002001 aec_dump_->WriteCaptureStreamMessage();
2002}
2003
2004void AudioProcessingImpl::RecordAudioProcessingState() {
2005 RTC_DCHECK(aec_dump_);
2006 AecDump::AudioProcessingState audio_proc_state;
2007 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002008 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002009 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002010 audio_proc_state.keypress = capture_.key_pressed;
2011 aec_dump_->AddAudioProcessingState(audio_proc_state);
2012}
2013
Per Åhgrenc0734712020-01-02 15:15:36 +01002014AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002015 : was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002016 output_will_be_muted(false),
2017 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002018 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002019 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002020 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002021 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002022 prev_pre_amp_gain(-1.f),
2023 playout_volume(-1),
2024 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002025
2026AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2027
Per Åhgrena1351272019-08-15 12:15:46 +02002028void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2029 const float* const* data,
2030 const StreamConfig& stream_config) {
2031 if (stream_config.has_keyboard()) {
2032 keyboard_data = data[stream_config.num_channels()];
2033 } else {
2034 keyboard_data = NULL;
2035 }
2036 num_keyboard_frames = stream_config.num_frames();
2037}
2038
kwiberg83ffe452016-08-29 14:46:07 -07002039AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2040
2041AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2042
Per Åhgrencf4c8722019-12-30 14:32:14 +01002043AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2044 : stats_message_queue_(1) {}
2045
2046AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2047
2048AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
2049 rtc::CritScope cs_stats(&crit_stats_);
2050 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2051 // If the message queue is full, return the cached stats.
2052 static_cast<void>(new_stats_available);
2053
2054 return cached_stats_;
2055}
2056
2057void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2058 const AudioProcessingStats& new_stats) {
2059 AudioProcessingStats stats_to_queue = new_stats;
2060 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2061 // If the message queue is full, discard the new stats.
2062 static_cast<void>(stats_message_passed);
2063}
2064
niklase@google.com470e71d2011-07-07 08:21:25 +00002065} // namespace webrtc