blob: e5e6ccef60f0930411089eed8d555730c7c99586 [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"
Alex Loikob5c9a792018-04-16 16:31:22 +020025#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/audio_processing/common.h"
Yves Gerey988cc082018-10-23 12:03:01 +020028#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 21:42:56 +010029#include "modules/audio_processing/logging/apm_data_dumper.h"
sazaaa42ecd2020-04-01 15:24:40 +020030#include "modules/audio_processing/transient/transient_suppressor_creator.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "rtc_base/ref_counted_object.h"
36#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020038#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000040
Michael Graczyk86c6d332015-07-23 11:41:39 -070041#define RETURN_ON_ERR(expr) \
42 do { \
43 int err = (expr); \
44 if (err != kNoError) { \
45 return err; \
46 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000047 } while (0)
48
niklase@google.com470e71d2011-07-07 08:21:25 +000049namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070050
Alex Loiko73ec0192018-05-15 10:52:28 +020051constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070052
Michael Graczyk86c6d332015-07-23 11:41:39 -070053namespace {
54
55static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
56 switch (layout) {
57 case AudioProcessing::kMono:
58 case AudioProcessing::kStereo:
59 return false;
60 case AudioProcessing::kMonoAndKeyboard:
61 case AudioProcessing::kStereoAndKeyboard:
62 return true;
63 }
64
kwiberg9e2be5f2016-09-14 05:23:22 -070065 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070066 return false;
67}
aluebsdf6416a2016-03-16 18:26:35 -070068
peah2ace3f92016-09-10 04:42:27 -070069bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070070 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
71 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
72}
73
Per Åhgrenc0424252019-12-10 13:04:15 +010074// Checks whether the high-pass filter should be done in the full-band.
75bool EnforceSplitBandHpf() {
76 return field_trial::IsEnabled("WebRTC-FullBandHpfKillSwitch");
77}
78
Per Åhgrenb2b58d82019-12-02 14:59:40 +010079// Checks whether AEC3 should be allowed to decide what the default
80// configuration should be based on the render and capture channel configuration
81// at hand.
82bool UseSetupSpecificDefaultAec3Congfig() {
83 return !field_trial::IsEnabled(
84 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
85}
86
Per Åhgrenc8626b62019-08-23 15:49:51 +020087// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020088int SuitableProcessRate(int minimum_rate,
89 int max_splitting_rate,
90 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020091 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020092 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020093 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070094 if (rate >= uppermost_native_rate) {
95 return uppermost_native_rate;
96 }
97 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070098 return rate;
99 }
100 }
peah2ace3f92016-09-10 04:42:27 -0700101 RTC_NOTREACHED();
102 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700103}
104
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100105GainControl::Mode Agc1ConfigModeToInterfaceMode(
106 AudioProcessing::Config::GainController1::Mode mode) {
107 using Agc1Config = AudioProcessing::Config::GainController1;
108 switch (mode) {
109 case Agc1Config::kAdaptiveAnalog:
110 return GainControl::kAdaptiveAnalog;
111 case Agc1Config::kAdaptiveDigital:
112 return GainControl::kAdaptiveDigital;
113 case Agc1Config::kFixedDigital:
114 return GainControl::kFixedDigital;
115 }
116}
117
peah9e6a2902017-05-15 07:19:21 -0700118// Maximum lengths that frame of samples being passed from the render side to
119// the capture side can have (does not apply to AEC3).
120static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
121static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
122
peah764e3642016-10-22 05:04:30 -0700123// Maximum number of frames to buffer in the render queue.
124// TODO(peah): Decrease this once we properly handle hugely unbalanced
125// reverse and forward call numbers.
126static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700127} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000128
129// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000130static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000131
saza1d600522019-10-18 13:29:43 +0200132AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100133 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200134 bool render_pre_processor_enabled,
135 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100136 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200137 render_pre_processor_enabled_(render_pre_processor_enabled),
138 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700139
saza1d600522019-10-18 13:29:43 +0200140bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200141 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700142 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700143 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700144 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700145 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700146 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200147 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200148 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200149 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700150 bool transient_suppressor_enabled) {
151 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200152 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700153 changed |=
154 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700155 changed |=
156 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700157 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
158 changed |=
peah2ace3f92016-09-10 04:42:27 -0700159 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200160 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200161 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200162 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200163 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700164 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
165 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200166 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700167 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700168 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700169 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700170 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700171 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200172 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200173 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200174 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700175 transient_suppressor_enabled_ = transient_suppressor_enabled;
176 }
177
178 changed |= first_update_;
179 first_update_ = false;
180 return changed;
181}
182
saza1d600522019-10-18 13:29:43 +0200183bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700184 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200185 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700186}
187
saza1d600522019-10-18 13:29:43 +0200188bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
189 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200190 // If echo controller is present, assume it performs active processing.
191 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
192}
193
saza1d600522019-10-18 13:29:43 +0200194bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200195 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100196 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
197 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200198 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700199}
200
saza1d600522019-10-18 13:29:43 +0200201bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700202 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200203 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
204 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700205}
206
saza1d600522019-10-18 13:29:43 +0200207bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200208 return capture_analyzer_enabled_;
209}
210
saza1d600522019-10-18 13:29:43 +0200211bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700212 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100213 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
214 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700215}
216
saza1d600522019-10-18 13:29:43 +0200217bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100218 const {
219 return render_pre_processor_enabled_;
220}
221
saza1d600522019-10-18 13:29:43 +0200222bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700223 const {
peah2ace3f92016-09-10 04:42:27 -0700224 return false;
peah2ace3f92016-09-10 04:42:27 -0700225}
226
saza1d600522019-10-18 13:29:43 +0200227bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100228 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
229 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200230}
231
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100232AudioProcessingBuilder::AudioProcessingBuilder() = default;
233AudioProcessingBuilder::~AudioProcessingBuilder() = default;
234
235AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
236 std::unique_ptr<CustomProcessing> capture_post_processing) {
237 capture_post_processing_ = std::move(capture_post_processing);
238 return *this;
239}
240
241AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
242 std::unique_ptr<CustomProcessing> render_pre_processing) {
243 render_pre_processing_ = std::move(render_pre_processing);
244 return *this;
245}
246
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200247AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
248 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
249 capture_analyzer_ = std::move(capture_analyzer);
250 return *this;
251}
252
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100253AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
254 std::unique_ptr<EchoControlFactory> echo_control_factory) {
255 echo_control_factory_ = std::move(echo_control_factory);
256 return *this;
257}
258
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100259AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200260 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100261 echo_detector_ = std::move(echo_detector);
262 return *this;
263}
264
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100265AudioProcessing* AudioProcessingBuilder::Create() {
266 webrtc::Config config;
267 return Create(config);
268}
269
270AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100271 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
272 config, std::move(capture_post_processing_),
273 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200274 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100275 if (apm->Initialize() != AudioProcessing::kNoError) {
276 delete apm;
277 apm = nullptr;
278 }
279 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100280}
281
peah88ac8532016-09-12 16:47:25 -0700282AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200283 : AudioProcessingImpl(config,
284 /*capture_post_processor=*/nullptr,
285 /*render_pre_processor=*/nullptr,
286 /*echo_control_factory=*/nullptr,
287 /*echo_detector=*/nullptr,
288 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000289
Per Åhgren13735822018-02-12 21:42:56 +0100290int AudioProcessingImpl::instance_count_ = 0;
291
Sam Zackrisson0beac582017-09-25 12:04:02 +0200292AudioProcessingImpl::AudioProcessingImpl(
293 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100294 std::unique_ptr<CustomProcessing> capture_post_processor,
295 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200296 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200297 rtc::scoped_refptr<EchoDetector> echo_detector,
298 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100299 : data_dumper_(
300 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100301 use_setup_specific_default_aec3_config_(
302 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200303 capture_runtime_settings_(kRuntimeSettingQueueSize),
304 render_runtime_settings_(kRuntimeSettingQueueSize),
305 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
306 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200307 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200308 submodule_states_(!!capture_post_processor,
309 !!render_pre_processor,
310 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200311 submodules_(std::move(capture_post_processor),
312 std::move(render_pre_processor),
313 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100314 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100315 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200316 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
317 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100318 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
319 EnforceSplitBandHpf()),
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200320 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200321 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100322 "\nEcho control factory: "
323 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200324 << "\nEcho detector: " << !!submodules_.echo_detector
325 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
326 << "\nCapture post processor: "
327 << !!submodules_.capture_post_processor
328 << "\nRender pre processor: "
329 << !!submodules_.render_pre_processor;
330
Sam Zackrisson421c8592019-02-11 13:39:46 +0100331 // Mark Echo Controller enabled if a factory is injected.
332 capture_nonlocked_.echo_controller_enabled =
333 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000334
Sam Zackrisson421c8592019-02-11 13:39:46 +0100335 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200336 if (!submodules_.echo_detector) {
337 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100338 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800339 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000340
Per Åhgren0695df12020-01-13 14:43:13 +0100341#if !(defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS))
Per Åhgrenc0734712020-01-02 15:15:36 +0100342 // TODO(webrtc:5298): Remove once the use of ExperimentalNs has been
343 // deprecated.
Per Åhgrenc0734712020-01-02 15:15:36 +0100344 config_.transient_suppression.enabled = config.Get<ExperimentalNs>().enabled;
Per Åhgren0695df12020-01-13 14:43:13 +0100345
346 // TODO(webrtc:5298): Remove once the use of ExperimentalAgc has been
347 // deprecated.
348 config_.gain_controller1.analog_gain_controller.enabled =
349 config.Get<ExperimentalAgc>().enabled;
350 config_.gain_controller1.analog_gain_controller.startup_min_volume =
351 config.Get<ExperimentalAgc>().startup_min_volume;
352 config_.gain_controller1.analog_gain_controller.clipped_level_min =
353 config.Get<ExperimentalAgc>().clipped_level_min;
354 config_.gain_controller1.analog_gain_controller.enable_agc2_level_estimator =
355 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator;
356 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive =
357 !config.Get<ExperimentalAgc>().digital_adaptive_disabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100358#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000359}
360
Per Åhgren0e3198e2019-11-18 08:52:22 +0100361AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000362
niklase@google.com470e71d2011-07-07 08:21:25 +0000363int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800364 // Run in a single-threaded manner during initialization.
365 rtc::CritScope cs_render(&crit_render_);
366 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000367 return InitializeLocked();
368}
369
peahde65ddc2016-09-16 15:02:15 -0700370int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
371 int capture_output_sample_rate_hz,
372 int render_input_sample_rate_hz,
373 ChannelLayout capture_input_layout,
374 ChannelLayout capture_output_layout,
375 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700376 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700377 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
378 LayoutHasKeyboard(capture_input_layout)},
379 {capture_output_sample_rate_hz,
380 ChannelsFromLayout(capture_output_layout),
381 LayoutHasKeyboard(capture_output_layout)},
382 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
383 LayoutHasKeyboard(render_input_layout)},
384 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
385 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700386
387 return Initialize(processing_config);
388}
389
390int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800391 // Run in a single-threaded manner during initialization.
392 rtc::CritScope cs_render(&crit_render_);
393 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700394 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000395}
396
peahdf3efa82015-11-28 12:35:15 -0800397int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800398 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800399 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200400 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800401 return kNoError;
402 }
peahdf3efa82015-11-28 12:35:15 -0800403
404 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800405 return InitializeLocked(processing_config);
406}
407
niklase@google.com470e71d2011-07-07 08:21:25 +0000408int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200409 UpdateActiveSubmoduleStates();
410
Per Åhgrend47941e2019-08-22 11:51:13 +0200411 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800412 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200413 ? formats_.render_processing_format.sample_rate_hz()
414 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800415 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
416 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200417 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800418 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200419 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700420 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200421 render_audiobuffer_sample_rate_hz,
422 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700423 if (formats_.api_format.reverse_input_stream() !=
424 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800425 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800426 formats_.api_format.reverse_input_stream().num_channels(),
427 formats_.api_format.reverse_input_stream().num_frames(),
428 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800429 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700430 } else {
peahdf3efa82015-11-28 12:35:15 -0800431 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700432 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700433 } else {
peahdf3efa82015-11-28 12:35:15 -0800434 render_.render_audio.reset(nullptr);
435 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700436 }
peahce4d9152017-05-19 01:28:05 -0700437
Per Åhgrend47941e2019-08-22 11:51:13 +0200438 capture_.capture_audio.reset(new AudioBuffer(
439 formats_.api_format.input_stream().sample_rate_hz(),
440 formats_.api_format.input_stream().num_channels(),
441 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
442 formats_.api_format.output_stream().num_channels(),
443 formats_.api_format.output_stream().sample_rate_hz(),
444 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000445
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200446 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
447 formats_.api_format.output_stream().sample_rate_hz() &&
448 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
449 capture_.capture_fullband_audio.reset(
450 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
451 formats_.api_format.input_stream().num_channels(),
452 formats_.api_format.output_stream().sample_rate_hz(),
453 formats_.api_format.output_stream().num_channels(),
454 formats_.api_format.output_stream().sample_rate_hz(),
455 formats_.api_format.output_stream().num_channels()));
456 } else {
457 capture_.capture_fullband_audio.reset();
458 }
459
peah764e3642016-10-22 05:04:30 -0700460 AllocateRenderQueue();
461
Per Åhgren0695df12020-01-13 14:43:13 +0100462 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100463 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100464 InitializeHighPassFilter(true);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200465 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700466 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200467 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700468 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200469 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200470 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200471 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100472 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800473
aleloi868f32f2017-05-23 07:20:05 -0700474 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200475 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700476 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000477 return kNoError;
478}
479
Michael Graczyk86c6d332015-07-23 11:41:39 -0700480int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200481 UpdateActiveSubmoduleStates();
482
Michael Graczyk86c6d332015-07-23 11:41:39 -0700483 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700484 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
485 return kBadSampleRateError;
486 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000487 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700488
Peter Kasting69558702016-01-12 16:26:35 -0800489 const size_t num_in_channels = config.input_stream().num_channels();
490 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700491
492 // Need at least one input channel.
493 // Need either one output channel or as many outputs as there are inputs.
494 if (num_in_channels == 0 ||
495 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700496 return kBadNumberChannelsError;
497 }
498
peahdf3efa82015-11-28 12:35:15 -0800499 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000500
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200501 // Choose maximum rate to use for the split filtering.
502 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
503 config_.pipeline.maximum_internal_processing_rate == 32000);
504 int max_splitting_rate = 48000;
505 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
506 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
507 }
508
Per Åhgrenc8626b62019-08-23 15:49:51 +0200509 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700510 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700511 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200512 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700513 submodule_states_.CaptureMultiBandSubModulesActive() ||
514 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200515 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000516
peahde65ddc2016-09-16 15:02:15 -0700517 capture_nonlocked_.capture_processing_format =
518 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700519
peah2ce640f2017-04-07 03:57:48 -0700520 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200521 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200522 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700523 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
524 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200525 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700526 submodule_states_.CaptureMultiBandSubModulesActive() ||
527 submodule_states_.RenderMultiBandSubModulesActive());
528 } else {
529 render_processing_rate = capture_processing_rate;
530 }
531
peahde65ddc2016-09-16 15:02:15 -0700532 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700533 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700534 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
535 kSampleRate8kHz) {
536 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000537 } else {
peahde65ddc2016-09-16 15:02:15 -0700538 render_processing_rate =
539 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000540 }
541
Per Åhgrenc8626b62019-08-23 15:49:51 +0200542 RTC_DCHECK_NE(8000, render_processing_rate);
543
peahce4d9152017-05-19 01:28:05 -0700544 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200545 // By default, downmix the render stream to mono for analysis. This has been
546 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100547 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
548 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200549 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100550 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200551 ? formats_.api_format.reverse_input_stream().num_channels()
552 : 1;
553 formats_.render_processing_format =
554 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700555 } else {
556 formats_.render_processing_format = StreamConfig(
557 formats_.api_format.reverse_input_stream().sample_rate_hz(),
558 formats_.api_format.reverse_input_stream().num_channels());
559 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000560
peahde65ddc2016-09-16 15:02:15 -0700561 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
562 kSampleRate32kHz ||
563 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
564 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800565 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000566 } else {
peahdf3efa82015-11-28 12:35:15 -0800567 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700568 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000569 }
570
571 return InitializeLocked();
572}
573
peah88ac8532016-09-12 16:47:25 -0700574void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200575 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
576
peah88ac8532016-09-12 16:47:25 -0700577 // Run in a single-threaded manner when applying the settings.
578 rtc::CritScope cs_render(&crit_render_);
579 rtc::CritScope cs_capture(&crit_capture_);
580
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200581 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100582 config_.pipeline.multi_channel_render !=
583 config.pipeline.multi_channel_render ||
584 config_.pipeline.multi_channel_capture !=
Per Åhgrenc0424252019-12-10 13:04:15 +0100585 config.pipeline.multi_channel_capture ||
586 config_.pipeline.maximum_internal_processing_rate !=
587 config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200588
Per Åhgren200feba2019-03-06 04:16:46 +0100589 const bool aec_config_changed =
590 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100591 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100592
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100593 const bool agc1_config_changed =
594 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
595 config_.gain_controller1.mode != config.gain_controller1.mode ||
596 config_.gain_controller1.target_level_dbfs !=
597 config.gain_controller1.target_level_dbfs ||
598 config_.gain_controller1.compression_gain_db !=
599 config.gain_controller1.compression_gain_db ||
600 config_.gain_controller1.enable_limiter !=
601 config.gain_controller1.enable_limiter ||
602 config_.gain_controller1.analog_level_minimum !=
603 config.gain_controller1.analog_level_minimum ||
604 config_.gain_controller1.analog_level_maximum !=
Per Åhgren0695df12020-01-13 14:43:13 +0100605 config.gain_controller1.analog_level_maximum ||
606 config_.gain_controller1.analog_gain_controller.enabled !=
607 config.gain_controller1.analog_gain_controller.enabled ||
608 config_.gain_controller1.analog_gain_controller.startup_min_volume !=
609 config.gain_controller1.analog_gain_controller.startup_min_volume ||
610 config_.gain_controller1.analog_gain_controller.clipped_level_min !=
611 config.gain_controller1.analog_gain_controller.clipped_level_min ||
612 config_.gain_controller1.analog_gain_controller
613 .enable_agc2_level_estimator !=
614 config.gain_controller1.analog_gain_controller
615 .enable_agc2_level_estimator ||
616 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive !=
617 config.gain_controller1.analog_gain_controller
618 .enable_digital_adaptive;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100619
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100620 const bool agc2_config_changed =
621 config_.gain_controller2.enabled != config.gain_controller2.enabled;
622
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200623 const bool voice_detection_config_changed =
624 config_.voice_detection.enabled != config.voice_detection.enabled;
625
saza0bad15f2019-10-16 11:46:11 +0200626 const bool ns_config_changed =
627 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
628 config_.noise_suppression.level != config.noise_suppression.level;
629
Per Åhgrenc0734712020-01-02 15:15:36 +0100630 const bool ts_config_changed = config_.transient_suppression.enabled !=
631 config.transient_suppression.enabled;
632
Per Åhgren0f14db22020-01-03 14:27:14 +0100633 const bool pre_amplifier_config_changed =
634 config_.pre_amplifier.enabled != config.pre_amplifier.enabled ||
635 config_.pre_amplifier.fixed_gain_factor !=
636 config.pre_amplifier.fixed_gain_factor;
637
Yves Gerey499bc6c2018-10-10 18:29:07 +0200638 config_ = config;
639
Per Åhgren200feba2019-03-06 04:16:46 +0100640 if (aec_config_changed) {
641 InitializeEchoController();
642 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200643
saza0bad15f2019-10-16 11:46:11 +0200644 if (ns_config_changed) {
645 InitializeNoiseSuppressor();
646 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100647
Per Åhgrenc0734712020-01-02 15:15:36 +0100648 if (ts_config_changed) {
649 InitializeTransientSuppressor();
650 }
651
Per Åhgren0f14db22020-01-03 14:27:14 +0100652 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800653
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100654 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100655 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100656 }
657
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100658 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700659 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100660 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
661 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100662 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100663 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700664 config_.gain_controller2 = AudioProcessing::Config::GainController2();
665 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100666
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100667 if (agc2_config_changed) {
668 InitializeGainController2();
669 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100670
671 if (pre_amplifier_config_changed) {
672 InitializePreAmplifier();
673 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100674
saza1d600522019-10-18 13:29:43 +0200675 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
676 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100677 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100678
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200679 if (voice_detection_config_changed) {
680 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100681 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200682
683 // Reinitialization must happen after all submodule configuration to avoid
684 // additional reinitializations on the next capture / render processing call.
685 if (pipeline_config_changed) {
686 InitializeLocked(formats_.api_format);
687 }
peah88ac8532016-09-12 16:47:25 -0700688}
689
Per Åhgrenc0734712020-01-02 15:15:36 +0100690// TODO(webrtc:5298): Remove.
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100691void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {}
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000692
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000693int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800694 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700695 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000696}
697
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200698int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
699 return capture_.capture_fullband_audio
700 ? capture_.capture_fullband_audio->num_frames() * 100
701 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
702}
703
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000704int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800705 // Used as callback from submodules, hence locking is not allowed.
706 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000707}
708
Peter Kasting69558702016-01-12 16:26:35 -0800709size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800710 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700711 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000712}
713
Peter Kasting69558702016-01-12 16:26:35 -0800714size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800715 // Used as callback from submodules, hence locking is not allowed.
716 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000717}
718
Peter Kasting69558702016-01-12 16:26:35 -0800719size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800720 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100721 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
722 constants_.multi_channel_capture_support;
723 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200724 return 1;
725 }
726 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800727}
728
Peter Kasting69558702016-01-12 16:26:35 -0800729size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800730 // Used as callback from submodules, hence locking is not allowed.
731 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000732}
733
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000734void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800735 rtc::CritScope cs(&crit_capture_);
736 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200737 if (submodules_.agc_manager.get()) {
738 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000739 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000740}
741
Alessio Bazzicac054e782018-04-16 12:10:09 +0200742void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200743 switch (setting.type()) {
744 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100745 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200746 render_runtime_settings_enqueuer_.Enqueue(setting);
747 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200748 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100749 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200750 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100751 capture_runtime_settings_enqueuer_.Enqueue(setting);
752 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200753 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200754 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100755 render_runtime_settings_enqueuer_.Enqueue(setting);
756 return;
757 case RuntimeSetting::Type::kNotSpecified:
758 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200759 return;
760 }
761 // The language allows the enum to have a non-enumerator
762 // value. Check that this doesn't happen.
763 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200764}
765
766AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
767 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200768 : runtime_settings_(*runtime_settings) {
769 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200770}
771
772AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
773 default;
774
775void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
776 RuntimeSetting setting) {
777 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200778 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200779 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200780 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200781 RTC_LOG(LS_ERROR)
782 << "The runtime settings queue is full. Oldest setting discarded.";
783 }
784 if (remaining_attempts == 0)
785 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
786}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000787
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100788int AudioProcessingImpl::MaybeInitializeCapture(
789 const StreamConfig& input_config,
790 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -0800791 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700792 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800793 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100794 // Acquire the capture lock in order to access api_format. The lock is
795 // released immediately, as we may need to acquire the render lock as part
796 // of the conditional reinitialization.
peahdf3efa82015-11-28 12:35:15 -0800797 rtc::CritScope cs_capture(&crit_capture_);
peahdf3efa82015-11-28 12:35:15 -0800798 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700799 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000800 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000801
Oskar Sundbom4b276482019-05-23 14:28:00 +0200802 if (processing_config.input_stream() != input_config) {
803 processing_config.input_stream() = input_config;
804 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800805 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200806
807 if (processing_config.output_stream() != output_config) {
808 processing_config.output_stream() = output_config;
809 reinitialization_required = true;
810 }
811
812 if (reinitialization_required) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200813 rtc::CritScope cs_render(&crit_render_);
814 rtc::CritScope cs_capture(&crit_capture_);
815 RETURN_ON_ERR(InitializeLocked(processing_config));
816 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100817 return kNoError;
818}
819
820int AudioProcessingImpl::ProcessStream(const float* const* src,
821 const StreamConfig& input_config,
822 const StreamConfig& output_config,
823 float* const* dest) {
824 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
825 if (!src || !dest) {
826 return kNullPointerError;
827 }
828
829 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +0200830
peahdf3efa82015-11-28 12:35:15 -0800831 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000832
aleloi868f32f2017-05-23 07:20:05 -0700833 if (aec_dump_) {
834 RecordUnprocessedCaptureStream(src);
835 }
836
Per Åhgrena1351272019-08-15 12:15:46 +0200837 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800838 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200839 if (capture_.capture_fullband_audio) {
840 capture_.capture_fullband_audio->CopyFrom(
841 src, formats_.api_format.input_stream());
842 }
peahde65ddc2016-09-16 15:02:15 -0700843 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200844 if (capture_.capture_fullband_audio) {
845 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
846 dest);
847 } else {
848 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
849 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000850
aleloi868f32f2017-05-23 07:20:05 -0700851 if (aec_dump_) {
852 RecordProcessedCaptureStream(dest);
853 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000854 return kNoError;
855}
856
Alex Loiko73ec0192018-05-15 10:52:28 +0200857void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200858 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200859 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200860 if (aec_dump_) {
861 aec_dump_->WriteRuntimeSetting(setting);
862 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200863 switch (setting.type()) {
864 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200865 if (config_.pre_amplifier.enabled) {
866 float value;
867 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200868 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200869 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200870 }
871 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200872 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100873 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100874 if (!submodules_.agc_manager) {
875 float value;
876 setting.GetFloat(&value);
877 int int_value = static_cast<int>(value + .5f);
878 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +0100879 if (submodules_.gain_control) {
880 int error =
881 submodules_.gain_control->set_compression_gain_db(int_value);
882 RTC_DCHECK_EQ(kNoError, error);
883 }
Per Åhgren0e3198e2019-11-18 08:52:22 +0100884 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100885 break;
886 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200887 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100888 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200889 float value;
890 setting.GetFloat(&value);
891 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200892 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200893 }
894 break;
895 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200896 case RuntimeSetting::Type::kPlayoutVolumeChange: {
897 int value;
898 setting.GetInt(&value);
899 capture_.playout_volume = value;
900 break;
901 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100902 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
903 RTC_NOTREACHED();
904 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200905 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
906 RTC_NOTREACHED();
907 break;
908 case RuntimeSetting::Type::kNotSpecified:
909 RTC_NOTREACHED();
910 break;
911 }
912 }
913}
914
915void AudioProcessingImpl::HandleRenderRuntimeSettings() {
916 RuntimeSetting setting;
917 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200918 if (aec_dump_) {
919 aec_dump_->WriteRuntimeSetting(setting);
920 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200921 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100922 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100923 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200924 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200925 if (submodules_.render_pre_processor) {
926 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200927 }
928 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100929 case RuntimeSetting::Type::kCapturePreGain: // fall-through
930 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200931 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200932 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200933 RTC_NOTREACHED();
934 break;
935 }
936 }
937}
938
peah9e6a2902017-05-15 07:19:21 -0700939void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800940 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700941
saza1d600522019-10-18 13:29:43 +0200942 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200943 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
944 num_reverse_channels(),
945 &aecm_render_queue_buffer_);
946 RTC_DCHECK(aecm_render_signal_queue_);
947 // Insert the samples into the queue.
948 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
949 // The data queue is full and needs to be emptied.
950 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -0700951
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200952 // Retry the insert (should always work).
953 bool result =
954 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
955 RTC_DCHECK(result);
956 }
peah764e3642016-10-22 05:04:30 -0700957 }
peah701d6282016-10-25 05:42:20 -0700958
Per Åhgren0695df12020-01-13 14:43:13 +0100959 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +0100960 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -0700961 // Insert the samples into the queue.
962 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
963 // The data queue is full and needs to be emptied.
964 EmptyQueuedRenderAudio();
965
966 // Retry the insert (should always work).
967 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
968 RTC_DCHECK(result);
969 }
970 }
peah9e6a2902017-05-15 07:19:21 -0700971}
ivoc9f4a4a02016-10-28 05:39:16 -0700972
peah9e6a2902017-05-15 07:19:21 -0700973void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700974 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
975
976 // Insert the samples into the queue.
977 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
978 // The data queue is full and needs to be emptied.
979 EmptyQueuedRenderAudio();
980
981 // Retry the insert (should always work).
982 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
983 RTC_DCHECK(result);
984 }
peah764e3642016-10-22 05:04:30 -0700985}
986
987void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700988 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700989 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700990
ivoc9f4a4a02016-10-28 05:39:16 -0700991 const size_t new_red_render_queue_element_max_size =
992 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
993
peaha0624602016-10-25 04:45:24 -0700994 // Reallocate the queues if the queue item sizes are too small to fit the
995 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700996
997 if (agc_render_queue_element_max_size_ <
998 new_agc_render_queue_element_max_size) {
999 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1000
1001 std::vector<int16_t> template_queue_element(
1002 agc_render_queue_element_max_size_);
1003
1004 agc_render_signal_queue_.reset(
1005 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1006 kMaxNumFramesToBuffer, template_queue_element,
1007 RenderQueueItemVerifier<int16_t>(
1008 agc_render_queue_element_max_size_)));
1009
1010 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1011 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1012 } else {
1013 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001014 }
ivoc9f4a4a02016-10-28 05:39:16 -07001015
1016 if (red_render_queue_element_max_size_ <
1017 new_red_render_queue_element_max_size) {
1018 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1019
1020 std::vector<float> template_queue_element(
1021 red_render_queue_element_max_size_);
1022
1023 red_render_signal_queue_.reset(
1024 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1025 kMaxNumFramesToBuffer, template_queue_element,
1026 RenderQueueItemVerifier<float>(
1027 red_render_queue_element_max_size_)));
1028
1029 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1030 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1031 } else {
1032 red_render_signal_queue_->Clear();
1033 }
peah764e3642016-10-22 05:04:30 -07001034}
1035
1036void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1037 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001038 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001039 RTC_DCHECK(aecm_render_signal_queue_);
1040 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001041 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001042 aecm_capture_queue_buffer_);
1043 }
peah701d6282016-10-25 05:42:20 -07001044 }
1045
Per Åhgren0695df12020-01-13 14:43:13 +01001046 if (submodules_.gain_control) {
1047 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1048 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1049 }
peah764e3642016-10-22 05:04:30 -07001050 }
ivoc9f4a4a02016-10-28 05:39:16 -07001051
1052 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001053 RTC_DCHECK(submodules_.echo_detector);
1054 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001055 }
peah764e3642016-10-22 05:04:30 -07001056}
1057
Per Åhgren645f24c2020-03-16 12:06:02 +01001058int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1059 const StreamConfig& input_config,
1060 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001061 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001062 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001063 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +02001064
peahdf3efa82015-11-28 12:35:15 -08001065 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001066
aleloi868f32f2017-05-23 07:20:05 -07001067 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001068 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001069 }
1070
Per Åhgren645f24c2020-03-16 12:06:02 +01001071 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001072 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001073 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001074 }
peahde65ddc2016-09-16 15:02:15 -07001075 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001076 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001077 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001078 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001079 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001080 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001081 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001082 }
Per Åhgrena1351272019-08-15 12:15:46 +02001083 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001084
aleloi868f32f2017-05-23 07:20:05 -07001085 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001086 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001087 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001088
1089 return kNoError;
1090}
1091
peahde65ddc2016-09-16 15:02:15 -07001092int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001093 EmptyQueuedRenderAudio();
Alex Loiko73ec0192018-05-15 10:52:28 +02001094 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001095
peahb58a1582016-03-15 09:34:24 -07001096 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001097 // TODO(peah): Simplify once the public API Enable functions for these
1098 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001099 RTC_DCHECK_LE(
1100 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001101
peahde65ddc2016-09-16 15:02:15 -07001102 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001103 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001104
Per Åhgrenc0424252019-12-10 13:04:15 +01001105 if (submodules_.high_pass_filter &&
1106 config_.high_pass_filter.apply_in_full_band &&
1107 !constants_.enforce_split_band_hpf) {
1108 submodules_.high_pass_filter->Process(capture_buffer,
1109 /*use_split_band_data=*/false);
1110 }
1111
saza1d600522019-10-18 13:29:43 +02001112 if (submodules_.pre_amplifier) {
1113 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001114 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001115 capture_buffer->num_frames()));
1116 }
1117
Per Åhgren928146f2019-08-20 09:19:21 +02001118 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001119 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001120 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001121 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1122 if (log_rms) {
1123 capture_rms_interval_counter_ = 0;
1124 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001125 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1126 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1127 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1128 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001129 }
1130
saza1d600522019-10-18 13:29:43 +02001131 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001132 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001133 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001134 capture_.echo_path_gain_change =
1135 capture_.prev_analog_mic_level != analog_mic_level &&
1136 capture_.prev_analog_mic_level != -1;
1137 capture_.prev_analog_mic_level = analog_mic_level;
1138
Per Åhgrend2650d12018-10-02 17:00:59 +02001139 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001140 if (submodules_.pre_amplifier) {
1141 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001142 capture_.echo_path_gain_change =
1143 capture_.echo_path_gain_change ||
1144 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001145 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001146 capture_.prev_pre_amp_gain = pre_amp_gain;
1147 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001148
1149 // Detect volume change.
1150 capture_.echo_path_gain_change =
1151 capture_.echo_path_gain_change ||
1152 (capture_.prev_playout_volume != capture_.playout_volume &&
1153 capture_.prev_playout_volume >= 0);
1154 capture_.prev_playout_volume = capture_.playout_volume;
1155
saza1d600522019-10-18 13:29:43 +02001156 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001157 }
1158
Per Åhgren0695df12020-01-13 14:43:13 +01001159 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001160 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001161 }
1162
peah2ace3f92016-09-10 04:42:27 -07001163 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1164 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001165 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1166 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001167 }
1168
Per Åhgrene14cb992019-11-27 09:34:22 +01001169 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1170 constants_.multi_channel_capture_support;
1171 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001172 // Force down-mixing of the number of channels after the detection of
1173 // capture signal saturation.
1174 // TODO(peah): Look into ensuring that this kind of tampering with the
1175 // AudioBuffer functionality should not be needed.
1176 capture_buffer->set_num_channels(1);
1177 }
1178
Per Åhgrenc0424252019-12-10 13:04:15 +01001179 if (submodules_.high_pass_filter &&
1180 (!config_.high_pass_filter.apply_in_full_band ||
1181 constants_.enforce_split_band_hpf)) {
1182 submodules_.high_pass_filter->Process(capture_buffer,
1183 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001184 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001185
Per Åhgren0695df12020-01-13 14:43:13 +01001186 if (submodules_.gain_control) {
1187 RETURN_ON_ERR(
1188 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1189 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001190
Per Åhgren8ad9e742020-01-30 07:40:58 +01001191 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1192 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1193 submodules_.noise_suppressor) {
1194 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001195 }
peahb58a1582016-03-15 09:34:24 -07001196
saza1d600522019-10-18 13:29:43 +02001197 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001198 // Ensure that the stream delay was set before the call to the
1199 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001200 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001201 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001202 }
1203
saza1d600522019-10-18 13:29:43 +02001204 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001205 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001206 }
peahe0eae3c2016-12-14 01:16:23 -08001207
saza1d600522019-10-18 13:29:43 +02001208 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001209 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001210 } else {
saza1d600522019-10-18 13:29:43 +02001211 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001212 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1213
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001214 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001215 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001216 }
1217
saza1d600522019-10-18 13:29:43 +02001218 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001219 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001220 }
1221
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001222 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001223 linear_aec_buffer && submodules_.noise_suppressor) {
1224 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001225 }
1226
saza1d600522019-10-18 13:29:43 +02001227 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001228 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001229 }
Per Åhgren46537a32017-06-07 10:08:10 +02001230 }
ivoc9f4a4a02016-10-28 05:39:16 -07001231
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001232 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001233 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001234 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001235 } else {
1236 capture_.stats.voice_detected = absl::nullopt;
1237 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001238
Per Åhgren0695df12020-01-13 14:43:13 +01001239 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001240 submodules_.agc_manager->Process(capture_buffer);
1241
1242 absl::optional<int> new_digital_gain =
1243 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001244 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001245 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1246 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001247 }
Per Åhgren0695df12020-01-13 14:43:13 +01001248
1249 if (submodules_.gain_control) {
1250 // TODO(peah): Add reporting from AEC3 whether there is echo.
1251 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1252 capture_buffer, /*stream_has_echo*/ false));
1253 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001254
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001255 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001256 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001257 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1258 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001259 }
1260
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001261 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001262 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001263 bool ec_active = ec ? ec->ActiveProcessing() : false;
1264 // Only update the fullband buffer if the multiband processing has changed
1265 // the signal. Keep the original signal otherwise.
1266 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1267 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1268 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001269 capture_buffer = capture_.capture_fullband_audio.get();
1270 }
1271
peah9e6a2902017-05-15 07:19:21 -07001272 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001273 RTC_DCHECK(submodules_.echo_detector);
1274 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1275 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001276 }
1277
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001278 // TODO(aluebs): Investigate if the transient suppression placement should be
1279 // before or after the AGC.
Per Åhgrenc0734712020-01-02 15:15:36 +01001280 if (submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001281 float voice_probability = submodules_.agc_manager.get()
1282 ? submodules_.agc_manager->voice_probability()
1283 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001284
saza1d600522019-10-18 13:29:43 +02001285 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001286 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001287 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001288 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001289 capture_buffer->num_frames_per_band(),
1290 capture_.keyboard_info.keyboard_data,
1291 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001292 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001293 }
1294
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001295 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001296 if (submodules_.capture_analyzer) {
1297 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001298 }
1299
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001300 if (submodules_.gain_controller2) {
saza1d600522019-10-18 13:29:43 +02001301 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001302 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001303 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001304 }
1305
saza1d600522019-10-18 13:29:43 +02001306 if (submodules_.capture_post_processor) {
1307 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001308 }
1309
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001310 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001311 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001312 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1313 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001314 } else {
1315 capture_.stats.output_rms_dbfs = absl::nullopt;
1316 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001317
Per Åhgren928146f2019-08-20 09:19:21 +02001318 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001319 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001320 capture_nonlocked_.capture_processing_format.num_frames()));
1321 if (log_rms) {
1322 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1323 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1324 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1325 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1326 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1327 }
1328
Per Åhgren0e3198e2019-11-18 08:52:22 +01001329 if (submodules_.agc_manager) {
1330 int level = recommended_stream_analog_level();
1331 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1332 &level);
1333 }
1334
Per Åhgrencf4c8722019-12-30 14:32:14 +01001335 // Compute echo-related stats.
1336 if (submodules_.echo_controller) {
1337 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1338 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1339 capture_.stats.echo_return_loss_enhancement =
1340 ec_metrics.echo_return_loss_enhancement;
1341 capture_.stats.delay_ms = ec_metrics.delay_ms;
1342 }
1343 if (config_.residual_echo_detector.enabled) {
1344 RTC_DCHECK(submodules_.echo_detector);
1345 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1346 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1347 capture_.stats.residual_echo_likelihood_recent_max =
1348 ed_metrics.echo_likelihood_recent_max;
1349 }
1350
1351 // Pass stats for reporting.
1352 stats_reporter_.UpdateStatistics(capture_.stats);
1353
peahdf3efa82015-11-28 12:35:15 -08001354 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001355 return kNoError;
1356}
1357
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001358int AudioProcessingImpl::AnalyzeReverseStream(
1359 const float* const* data,
1360 const StreamConfig& reverse_config) {
1361 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1362 rtc::CritScope cs(&crit_render_);
1363 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1364}
1365
peahde65ddc2016-09-16 15:02:15 -07001366int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1367 const StreamConfig& input_config,
1368 const StreamConfig& output_config,
1369 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001370 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001371 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001372 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001373 if (submodule_states_.RenderMultiBandProcessingActive() ||
1374 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001375 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1376 dest);
peah2ace3f92016-09-10 04:42:27 -07001377 } else if (formats_.api_format.reverse_input_stream() !=
1378 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001379 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1380 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001381 } else {
peahde65ddc2016-09-16 15:02:15 -07001382 CopyAudioIfNeeded(src, input_config.num_frames(),
1383 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001384 }
1385
1386 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001387}
1388
peahdf3efa82015-11-28 12:35:15 -08001389int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001390 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001391 const StreamConfig& input_config,
1392 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001393 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001394 return kNullPointerError;
1395 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001396
peahde65ddc2016-09-16 15:02:15 -07001397 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001398 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001399 }
1400
peahdf3efa82015-11-28 12:35:15 -08001401 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001402 processing_config.reverse_input_stream() = input_config;
1403 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001404
peahdf3efa82015-11-28 12:35:15 -08001405 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001406 RTC_DCHECK_EQ(input_config.num_frames(),
1407 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001408
aleloi868f32f2017-05-23 07:20:05 -07001409 if (aec_dump_) {
1410 const size_t channel_size =
1411 formats_.api_format.reverse_input_stream().num_frames();
1412 const size_t num_channels =
1413 formats_.api_format.reverse_input_stream().num_channels();
1414 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001415 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001416 }
peahdf3efa82015-11-28 12:35:15 -08001417 render_.render_audio->CopyFrom(src,
1418 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001419 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001420}
1421
Per Åhgren645f24c2020-03-16 12:06:02 +01001422int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1423 const StreamConfig& input_config,
1424 const StreamConfig& output_config,
1425 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001426 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001427
1428 if (input_config.num_channels() <= 0) {
1429 return AudioProcessing::Error::kBadNumberChannelsError;
1430 }
1431
Per Åhgren645f24c2020-03-16 12:06:02 +01001432 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001433 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001434 processing_config.reverse_input_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001435 input_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001436 processing_config.reverse_input_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001437 input_config.num_channels());
ekmeyerson60d9b332015-08-14 10:35:55 -07001438 processing_config.reverse_output_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001439 output_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001440 processing_config.reverse_output_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001441 output_config.num_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001442
peahdf3efa82015-11-28 12:35:15 -08001443 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Per Åhgren645f24c2020-03-16 12:06:02 +01001444 if (input_config.num_frames() !=
peahdf3efa82015-11-28 12:35:15 -08001445 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001446 return kBadDataLengthError;
1447 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001448
aleloi868f32f2017-05-23 07:20:05 -07001449 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001450 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1451 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001452 }
1453
Per Åhgren645f24c2020-03-16 12:06:02 +01001454 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001455 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001456 if (submodule_states_.RenderMultiBandProcessingActive() ||
1457 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001458 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001459 }
aluebsb0319552016-03-17 20:39:53 -07001460 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001461}
niklase@google.com470e71d2011-07-07 08:21:25 +00001462
peahde65ddc2016-09-16 15:02:15 -07001463int AudioProcessingImpl::ProcessRenderStreamLocked() {
1464 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001465
Alex Loiko73ec0192018-05-15 10:52:28 +02001466 HandleRenderRuntimeSettings();
1467
saza1d600522019-10-18 13:29:43 +02001468 if (submodules_.render_pre_processor) {
1469 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001470 }
1471
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001472 QueueNonbandedRenderAudio(render_buffer);
1473
peah2ace3f92016-09-10 04:42:27 -07001474 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001475 SampleRateSupportsMultiBand(
1476 formats_.render_processing_format.sample_rate_hz())) {
1477 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001478 }
1479
peahce4d9152017-05-19 01:28:05 -07001480 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1481 QueueBandedRenderAudio(render_buffer);
1482 }
1483
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001484 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001485 if (submodules_.echo_controller) {
1486 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001487 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001488
peah2ace3f92016-09-10 04:42:27 -07001489 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001490 SampleRateSupportsMultiBand(
1491 formats_.render_processing_format.sample_rate_hz())) {
1492 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001493 }
1494
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001495 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001496}
1497
1498int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001499 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001500 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001501 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001502
niklase@google.com470e71d2011-07-07 08:21:25 +00001503 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001504 delay = 0;
1505 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001506 }
1507
1508 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1509 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001510 delay = 500;
1511 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001512 }
1513
peahdf3efa82015-11-28 12:35:15 -08001514 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001515 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001516}
1517
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001518bool AudioProcessingImpl::GetLinearAecOutput(
1519 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1520 rtc::CritScope cs(&crit_capture_);
1521 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1522
1523 RTC_DCHECK(linear_aec_buffer);
1524 if (linear_aec_buffer) {
1525 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1526 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1527
1528 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1529 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1530 rtc::ArrayView<const float> channel_view =
1531 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1532 linear_aec_buffer->num_frames());
1533 std::copy(channel_view.begin(), channel_view.end(),
1534 linear_output[ch].begin());
1535 }
1536 return true;
1537 }
1538 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1539 RTC_NOTREACHED();
1540 return false;
1541}
1542
niklase@google.com470e71d2011-07-07 08:21:25 +00001543int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001544 // Used as callback from submodules, hence locking is not allowed.
1545 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001546}
1547
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001548void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001549 rtc::CritScope cs(&crit_capture_);
1550 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001551}
1552
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001553void AudioProcessingImpl::set_stream_analog_level(int level) {
1554 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001555
1556 if (submodules_.agc_manager) {
1557 submodules_.agc_manager->set_stream_analog_level(level);
1558 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1559 1, &level);
Per Åhgren0695df12020-01-13 14:43:13 +01001560 } else if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001561 int error = submodules_.gain_control->set_stream_analog_level(level);
1562 RTC_DCHECK_EQ(kNoError, error);
Per Åhgren0695df12020-01-13 14:43:13 +01001563 } else {
1564 capture_.cached_stream_analog_level_ = level;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001565 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001566}
1567
1568int AudioProcessingImpl::recommended_stream_analog_level() const {
1569 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001570 if (submodules_.agc_manager) {
1571 return submodules_.agc_manager->stream_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01001572 } else if (submodules_.gain_control) {
1573 return submodules_.gain_control->stream_analog_level();
1574 } else {
1575 return capture_.cached_stream_analog_level_;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001576 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001577}
1578
aleloi868f32f2017-05-23 07:20:05 -07001579void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1580 RTC_DCHECK(aec_dump);
1581 rtc::CritScope cs_render(&crit_render_);
1582 rtc::CritScope cs_capture(&crit_capture_);
1583
1584 // The previously attached AecDump will be destroyed with the
1585 // 'aec_dump' parameter, which is after locks are released.
1586 aec_dump_.swap(aec_dump);
1587 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001588 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001589}
1590
1591void AudioProcessingImpl::DetachAecDump() {
1592 // The d-tor of a task-queue based AecDump blocks until all pending
1593 // tasks are done. This construction avoids blocking while holding
1594 // the render and capture locks.
1595 std::unique_ptr<AecDump> aec_dump = nullptr;
1596 {
1597 rtc::CritScope cs_render(&crit_render_);
1598 rtc::CritScope cs_capture(&crit_capture_);
1599 aec_dump = std::move(aec_dump_);
1600 }
1601}
1602
Sam Zackrisson4d364492018-03-02 16:03:21 +01001603void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1604 std::unique_ptr<AudioGenerator> audio_generator) {
1605 // TODO(bugs.webrtc.org/8882) Stub.
1606 // Reset internal audio generator with audio_generator.
1607}
1608
1609void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1610 // TODO(bugs.webrtc.org/8882) Stub.
1611 // Delete audio generator, if one is attached.
1612}
1613
peah8271d042016-11-22 07:24:52 -08001614void AudioProcessingImpl::MutateConfig(
1615 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1616 rtc::CritScope cs_render(&crit_render_);
1617 rtc::CritScope cs_capture(&crit_capture_);
1618 mutator(&config_);
1619 ApplyConfig(config_);
1620}
1621
1622AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1623 rtc::CritScope cs_render(&crit_render_);
1624 rtc::CritScope cs_capture(&crit_capture_);
1625 return config_;
1626}
1627
peah2ace3f92016-09-10 04:42:27 -07001628bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1629 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001630 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Per Åhgren8ad9e742020-01-30 07:40:58 +01001631 config_.residual_echo_detector.enabled, !!submodules_.noise_suppressor,
Per Åhgren0695df12020-01-13 14:43:13 +01001632 !!submodules_.gain_control, !!submodules_.gain_controller2,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001633 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
Per Åhgrenc0734712020-01-02 15:15:36 +01001634 config_.voice_detection.enabled, !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001635}
1636
Per Åhgrenc0734712020-01-02 15:15:36 +01001637void AudioProcessingImpl::InitializeTransientSuppressor() {
1638 if (config_.transient_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02001639 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01001640 if (!submodules_.transient_suppressor) {
sazaaa42ecd2020-04-01 15:24:40 +02001641 submodules_.transient_suppressor = CreateTransientSuppressor();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001642 }
sazaaa42ecd2020-04-01 15:24:40 +02001643 if (submodules_.transient_suppressor) {
1644 submodules_.transient_suppressor->Initialize(
1645 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1646 num_proc_channels());
1647 } else {
1648 RTC_LOG(LS_WARNING)
1649 << "No transient suppressor created (probably disabled)";
1650 }
Per Åhgrenc0734712020-01-02 15:15:36 +01001651 } else {
1652 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001653 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001654}
1655
Per Åhgren0f14db22020-01-03 14:27:14 +01001656void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01001657 bool high_pass_filter_needed_by_aec =
1658 config_.echo_canceller.enabled &&
1659 config_.echo_canceller.enforce_high_pass_filtering &&
1660 !config_.echo_canceller.mobile_mode;
1661 if (submodule_states_.HighPassFilteringRequired() ||
1662 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001663 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1664 !constants_.enforce_split_band_hpf;
1665 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1666 : proc_split_sample_rate_hz();
1667 size_t num_channels =
1668 use_full_band ? num_output_channels() : num_proc_channels();
1669
Per Åhgren0f14db22020-01-03 14:27:14 +01001670 if (!submodules_.high_pass_filter ||
1671 rate != submodules_.high_pass_filter->sample_rate_hz() ||
1672 forced_reset ||
1673 num_channels != submodules_.high_pass_filter->num_channels()) {
1674 submodules_.high_pass_filter.reset(
1675 new HighPassFilter(rate, num_channels));
1676 }
peah8271d042016-11-22 07:24:52 -08001677 } else {
saza1d600522019-10-18 13:29:43 +02001678 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001679 }
1680}
alessiob3ec96df2017-05-22 06:57:06 -07001681
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001682void AudioProcessingImpl::InitializeVoiceDetector() {
1683 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001684 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001685 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1686 } else {
saza1d600522019-10-18 13:29:43 +02001687 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001688 }
1689}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001690void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001691 bool use_echo_controller =
1692 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001693 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001694
1695 if (use_echo_controller) {
1696 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001697 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001698 submodules_.echo_controller = echo_control_factory_->Create(
1699 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001700 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001701 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001702 EchoCanceller3Config config =
1703 use_setup_specific_default_aec3_config_
1704 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1705 num_proc_channels())
1706 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001707 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001708 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001709 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001710 }
1711
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001712 // Setup the storage for returning the linear AEC output.
1713 if (config_.echo_canceller.export_linear_aec_output) {
1714 constexpr int kLinearOutputRateHz = 16000;
1715 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1716 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1717 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1718 } else {
1719 capture_.linear_aec_output.reset();
1720 }
1721
Per Åhgren200feba2019-03-06 04:16:46 +01001722 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001723
saza1d600522019-10-18 13:29:43 +02001724 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001725 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001726 return;
peahe0eae3c2016-12-14 01:16:23 -08001727 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001728
saza1d600522019-10-18 13:29:43 +02001729 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001730 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001731 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001732
1733 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001734 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001735 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001736 return;
1737 }
1738
1739 if (config_.echo_canceller.mobile_mode) {
1740 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001741 size_t max_element_size =
1742 std::max(static_cast<size_t>(1),
1743 kMaxAllowedValuesOfSamplesPerBand *
1744 EchoControlMobileImpl::NumCancellersRequired(
1745 num_output_channels(), num_reverse_channels()));
1746
1747 std::vector<int16_t> template_queue_element(max_element_size);
1748
1749 aecm_render_signal_queue_.reset(
1750 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1751 kMaxNumFramesToBuffer, template_queue_element,
1752 RenderQueueItemVerifier<int16_t>(max_element_size)));
1753
1754 aecm_render_queue_buffer_.resize(max_element_size);
1755 aecm_capture_queue_buffer_.resize(max_element_size);
1756
saza1d600522019-10-18 13:29:43 +02001757 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001758
saza1d600522019-10-18 13:29:43 +02001759 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1760 num_reverse_channels(),
1761 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001762 return;
1763 }
1764
saza1d600522019-10-18 13:29:43 +02001765 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001766 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001767}
peah8271d042016-11-22 07:24:52 -08001768
Per Åhgren0695df12020-01-13 14:43:13 +01001769void AudioProcessingImpl::InitializeGainController1() {
1770 if (!config_.gain_controller1.enabled) {
1771 submodules_.agc_manager.reset();
1772 submodules_.gain_control.reset();
1773 return;
1774 }
1775
1776 if (!submodules_.gain_control) {
1777 submodules_.gain_control.reset(new GainControlImpl());
1778 }
1779
1780 submodules_.gain_control->Initialize(num_proc_channels(),
1781 proc_sample_rate_hz());
1782
1783 if (!config_.gain_controller1.analog_gain_controller.enabled) {
1784 int error = submodules_.gain_control->set_mode(
1785 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
1786 RTC_DCHECK_EQ(kNoError, error);
1787 error = submodules_.gain_control->set_target_level_dbfs(
1788 config_.gain_controller1.target_level_dbfs);
1789 RTC_DCHECK_EQ(kNoError, error);
1790 error = submodules_.gain_control->set_compression_gain_db(
1791 config_.gain_controller1.compression_gain_db);
1792 RTC_DCHECK_EQ(kNoError, error);
1793 error = submodules_.gain_control->enable_limiter(
1794 config_.gain_controller1.enable_limiter);
1795 RTC_DCHECK_EQ(kNoError, error);
1796 error = submodules_.gain_control->set_analog_level_limits(
1797 config_.gain_controller1.analog_level_minimum,
1798 config_.gain_controller1.analog_level_maximum);
1799 RTC_DCHECK_EQ(kNoError, error);
1800
1801 submodules_.agc_manager.reset();
1802 return;
1803 }
1804
1805 if (!submodules_.agc_manager.get() ||
1806 submodules_.agc_manager->num_channels() !=
1807 static_cast<int>(num_proc_channels()) ||
1808 submodules_.agc_manager->sample_rate_hz() !=
1809 capture_nonlocked_.split_rate) {
1810 int stream_analog_level = -1;
1811 const bool re_creation = !!submodules_.agc_manager;
1812 if (re_creation) {
1813 stream_analog_level = submodules_.agc_manager->stream_analog_level();
1814 }
1815 submodules_.agc_manager.reset(new AgcManagerDirect(
1816 num_proc_channels(),
1817 config_.gain_controller1.analog_gain_controller.startup_min_volume,
1818 config_.gain_controller1.analog_gain_controller.clipped_level_min,
1819 config_.gain_controller1.analog_gain_controller
1820 .enable_agc2_level_estimator,
1821 !config_.gain_controller1.analog_gain_controller
1822 .enable_digital_adaptive,
1823 capture_nonlocked_.split_rate));
1824 if (re_creation) {
1825 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
1826 }
1827 }
1828 submodules_.agc_manager->Initialize();
1829 submodules_.agc_manager->SetupDigitalGainControl(
1830 submodules_.gain_control.get());
1831 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
1832}
1833
alessiob3ec96df2017-05-22 06:57:06 -07001834void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001835 if (config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001836 if (!submodules_.gain_controller2) {
1837 // TODO(alessiob): Move the injected gain controller once injection is
1838 // implemented.
1839 submodules_.gain_controller2.reset(new GainController2());
1840 }
1841
saza1d600522019-10-18 13:29:43 +02001842 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001843 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
1844 } else {
1845 submodules_.gain_controller2.reset();
alessiob3ec96df2017-05-22 06:57:06 -07001846 }
1847}
1848
saza0bad15f2019-10-16 11:46:11 +02001849void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001850 submodules_.noise_suppressor.reset();
1851
saza0bad15f2019-10-16 11:46:11 +02001852 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02001853 auto map_level =
1854 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1855 using NoiseSuppresionConfig =
1856 AudioProcessing::Config::NoiseSuppression;
1857 switch (level) {
1858 case NoiseSuppresionConfig::kLow:
1859 return NsConfig::SuppressionLevel::k6dB;
1860 case NoiseSuppresionConfig::kModerate:
1861 return NsConfig::SuppressionLevel::k12dB;
1862 case NoiseSuppresionConfig::kHigh:
1863 return NsConfig::SuppressionLevel::k18dB;
1864 case NoiseSuppresionConfig::kVeryHigh:
1865 return NsConfig::SuppressionLevel::k21dB;
1866 default:
1867 RTC_NOTREACHED();
1868 }
1869 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001870
sazaaa42ecd2020-04-01 15:24:40 +02001871 NsConfig cfg;
1872 cfg.target_level = map_level(config_.noise_suppression.level);
1873 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1874 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02001875 }
1876}
1877
Alex Loikob5c9a792018-04-16 16:31:22 +02001878void AudioProcessingImpl::InitializePreAmplifier() {
1879 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001880 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001881 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1882 } else {
saza1d600522019-10-18 13:29:43 +02001883 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001884 }
1885}
1886
ivoc9f4a4a02016-10-28 05:39:16 -07001887void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001888 RTC_DCHECK(submodules_.echo_detector);
1889 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001890 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001891 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001892}
1893
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001894void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001895 if (submodules_.capture_analyzer) {
1896 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1897 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001898 }
1899}
1900
Sam Zackrisson0beac582017-09-25 12:04:02 +02001901void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001902 if (submodules_.capture_post_processor) {
1903 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001904 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001905 }
1906}
1907
Alex Loiko5825aa62017-12-18 16:02:40 +01001908void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001909 if (submodules_.render_pre_processor) {
1910 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001911 formats_.render_processing_format.sample_rate_hz(),
1912 formats_.render_processing_format.num_channels());
1913 }
1914}
1915
Per Åhgrenea4c5df2019-05-03 09:00:08 +02001916void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001917
aleloi868f32f2017-05-23 07:20:05 -07001918void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1919 if (!aec_dump_) {
1920 return;
1921 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001922
1923 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07001924 // TODO(peah): Add semicolon-separated concatenations of experiment
1925 // descriptions for other submodules.
Per Åhgren0695df12020-01-13 14:43:13 +01001926 if (config_.gain_controller1.analog_gain_controller.clipped_level_min !=
1927 kClippedLevelMin) {
aleloi868f32f2017-05-23 07:20:05 -07001928 experiments_description += "AgcClippingLevelExperiment;";
1929 }
Sam Zackrisson701bd172020-02-18 14:50:28 +01001930 if (!!submodules_.capture_post_processor) {
1931 experiments_description += "CapturePostProcessor;";
1932 }
1933 if (!!submodules_.render_pre_processor) {
1934 experiments_description += "RenderPreProcessor;";
1935 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001936 if (capture_nonlocked_.echo_controller_enabled) {
1937 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001938 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001939 if (config_.gain_controller2.enabled) {
1940 experiments_description += "GainController2;";
1941 }
aleloi868f32f2017-05-23 07:20:05 -07001942
1943 InternalAPMConfig apm_config;
1944
Per Åhgren200feba2019-03-06 04:16:46 +01001945 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001946 apm_config.aec_delay_agnostic_enabled = false;
1947 apm_config.aec_extended_filter_enabled = false;
1948 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07001949
saza1d600522019-10-18 13:29:43 +02001950 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07001951 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02001952 submodules_.echo_control_mobile &&
1953 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001954 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02001955 submodules_.echo_control_mobile
1956 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001957 : 0;
aleloi868f32f2017-05-23 07:20:05 -07001958
Per Åhgren0695df12020-01-13 14:43:13 +01001959 apm_config.agc_enabled = !!submodules_.gain_control;
1960
1961 apm_config.agc_mode = submodules_.gain_control
1962 ? static_cast<int>(submodules_.gain_control->mode())
1963 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07001964 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01001965 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
1966 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001967 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07001968
1969 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1970
saza0bad15f2019-10-16 11:46:11 +02001971 apm_config.ns_enabled = config_.noise_suppression.enabled;
1972 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07001973
1974 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01001975 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07001976 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001977 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1978 apm_config.pre_amplifier_fixed_gain_factor =
1979 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001980
1981 if (!forced && apm_config == apm_config_for_aec_dump_) {
1982 return;
1983 }
1984 aec_dump_->WriteConfig(apm_config);
1985 apm_config_for_aec_dump_ = apm_config;
1986}
1987
1988void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1989 const float* const* src) {
1990 RTC_DCHECK(aec_dump_);
1991 WriteAecDumpConfigMessage(false);
1992
1993 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1994 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1995 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001996 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001997 RecordAudioProcessingState();
1998}
1999
2000void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002001 const int16_t* const data,
2002 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002003 RTC_DCHECK(aec_dump_);
2004 WriteAecDumpConfigMessage(false);
2005
Per Åhgren645f24c2020-03-16 12:06:02 +01002006 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2007 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002008 RecordAudioProcessingState();
2009}
2010
2011void AudioProcessingImpl::RecordProcessedCaptureStream(
2012 const float* const* processed_capture_stream) {
2013 RTC_DCHECK(aec_dump_);
2014
2015 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2016 const size_t num_channels =
2017 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002018 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2019 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002020 aec_dump_->WriteCaptureStreamMessage();
2021}
2022
2023void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002024 const int16_t* const data,
2025 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002026 RTC_DCHECK(aec_dump_);
2027
Per Åhgren645f24c2020-03-16 12:06:02 +01002028 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002029 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002030 aec_dump_->WriteCaptureStreamMessage();
2031}
2032
2033void AudioProcessingImpl::RecordAudioProcessingState() {
2034 RTC_DCHECK(aec_dump_);
2035 AecDump::AudioProcessingState audio_proc_state;
2036 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002037 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002038 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002039 audio_proc_state.keypress = capture_.key_pressed;
2040 aec_dump_->AddAudioProcessingState(audio_proc_state);
2041}
2042
Per Åhgrenc0734712020-01-02 15:15:36 +01002043AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002044 : was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002045 output_will_be_muted(false),
2046 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002047 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002048 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002049 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002050 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002051 prev_pre_amp_gain(-1.f),
2052 playout_volume(-1),
2053 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002054
2055AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2056
Per Åhgrena1351272019-08-15 12:15:46 +02002057void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2058 const float* const* data,
2059 const StreamConfig& stream_config) {
2060 if (stream_config.has_keyboard()) {
2061 keyboard_data = data[stream_config.num_channels()];
2062 } else {
2063 keyboard_data = NULL;
2064 }
2065 num_keyboard_frames = stream_config.num_frames();
2066}
2067
kwiberg83ffe452016-08-29 14:46:07 -07002068AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2069
2070AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2071
Per Åhgrencf4c8722019-12-30 14:32:14 +01002072AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2073 : stats_message_queue_(1) {}
2074
2075AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2076
2077AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
2078 rtc::CritScope cs_stats(&crit_stats_);
2079 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2080 // If the message queue is full, return the cached stats.
2081 static_cast<void>(new_stats_available);
2082
2083 return cached_stats_;
2084}
2085
2086void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2087 const AudioProcessingStats& new_stats) {
2088 AudioProcessingStats stats_to_queue = new_stats;
2089 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2090 // If the message queue is full, discard the new stats.
2091 static_cast<void>(stats_message_passed);
2092}
2093
niklase@google.com470e71d2011-07-07 08:21:25 +00002094} // namespace webrtc