blob: ca73fcf900ce91c4e1329a49d425c87526401cab [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"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/ref_counted_object.h"
35#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020037#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000039
Michael Graczyk86c6d332015-07-23 11:41:39 -070040#define RETURN_ON_ERR(expr) \
41 do { \
42 int err = (expr); \
43 if (err != kNoError) { \
44 return err; \
45 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000046 } while (0)
47
niklase@google.com470e71d2011-07-07 08:21:25 +000048namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070049
Alex Loiko73ec0192018-05-15 10:52:28 +020050constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070051
Michael Graczyk86c6d332015-07-23 11:41:39 -070052namespace {
53
54static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
55 switch (layout) {
56 case AudioProcessing::kMono:
57 case AudioProcessing::kStereo:
58 return false;
59 case AudioProcessing::kMonoAndKeyboard:
60 case AudioProcessing::kStereoAndKeyboard:
61 return true;
62 }
63
kwiberg9e2be5f2016-09-14 05:23:22 -070064 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070065 return false;
66}
aluebsdf6416a2016-03-16 18:26:35 -070067
peah2ace3f92016-09-10 04:42:27 -070068bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070069 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
70 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
71}
72
Per Åhgrenc0424252019-12-10 13:04:15 +010073// Checks whether the high-pass filter should be done in the full-band.
74bool EnforceSplitBandHpf() {
75 return field_trial::IsEnabled("WebRTC-FullBandHpfKillSwitch");
76}
77
Per Åhgrenb2b58d82019-12-02 14:59:40 +010078// Checks whether AEC3 should be allowed to decide what the default
79// configuration should be based on the render and capture channel configuration
80// at hand.
81bool UseSetupSpecificDefaultAec3Congfig() {
82 return !field_trial::IsEnabled(
83 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
84}
85
Per Åhgrenc8626b62019-08-23 15:49:51 +020086// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020087int SuitableProcessRate(int minimum_rate,
88 int max_splitting_rate,
89 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020090 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020091 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020092 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070093 if (rate >= uppermost_native_rate) {
94 return uppermost_native_rate;
95 }
96 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070097 return rate;
98 }
99 }
peah2ace3f92016-09-10 04:42:27 -0700100 RTC_NOTREACHED();
101 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700102}
103
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100104GainControl::Mode Agc1ConfigModeToInterfaceMode(
105 AudioProcessing::Config::GainController1::Mode mode) {
106 using Agc1Config = AudioProcessing::Config::GainController1;
107 switch (mode) {
108 case Agc1Config::kAdaptiveAnalog:
109 return GainControl::kAdaptiveAnalog;
110 case Agc1Config::kAdaptiveDigital:
111 return GainControl::kAdaptiveDigital;
112 case Agc1Config::kFixedDigital:
113 return GainControl::kFixedDigital;
114 }
115}
116
peah9e6a2902017-05-15 07:19:21 -0700117// Maximum lengths that frame of samples being passed from the render side to
118// the capture side can have (does not apply to AEC3).
119static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
120static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
121
peah764e3642016-10-22 05:04:30 -0700122// Maximum number of frames to buffer in the render queue.
123// TODO(peah): Decrease this once we properly handle hugely unbalanced
124// reverse and forward call numbers.
125static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700126} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000127
128// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000129static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000130
saza1d600522019-10-18 13:29:43 +0200131AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100132 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200133 bool render_pre_processor_enabled,
134 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100135 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200136 render_pre_processor_enabled_(render_pre_processor_enabled),
137 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700138
saza1d600522019-10-18 13:29:43 +0200139bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200140 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700141 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700142 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700143 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700144 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700145 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200146 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200147 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200148 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700149 bool transient_suppressor_enabled) {
150 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200151 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700152 changed |=
153 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700154 changed |=
155 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700156 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
157 changed |=
peah2ace3f92016-09-10 04:42:27 -0700158 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200159 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200160 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200161 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200162 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700163 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
164 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200165 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700166 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700167 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700168 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700169 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700170 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200171 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200172 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200173 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700174 transient_suppressor_enabled_ = transient_suppressor_enabled;
175 }
176
177 changed |= first_update_;
178 first_update_ = false;
179 return changed;
180}
181
saza1d600522019-10-18 13:29:43 +0200182bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700183 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200184 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700185}
186
saza1d600522019-10-18 13:29:43 +0200187bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
188 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200189 // If echo controller is present, assume it performs active processing.
190 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
191}
192
saza1d600522019-10-18 13:29:43 +0200193bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200194 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100195 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
196 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200197 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700198}
199
saza1d600522019-10-18 13:29:43 +0200200bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700201 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200202 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
203 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700204}
205
saza1d600522019-10-18 13:29:43 +0200206bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200207 return capture_analyzer_enabled_;
208}
209
saza1d600522019-10-18 13:29:43 +0200210bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700211 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100212 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
213 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700214}
215
saza1d600522019-10-18 13:29:43 +0200216bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100217 const {
218 return render_pre_processor_enabled_;
219}
220
saza1d600522019-10-18 13:29:43 +0200221bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700222 const {
peah2ace3f92016-09-10 04:42:27 -0700223 return false;
peah2ace3f92016-09-10 04:42:27 -0700224}
225
saza1d600522019-10-18 13:29:43 +0200226bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100227 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
228 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200229}
230
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100231AudioProcessingBuilder::AudioProcessingBuilder() = default;
232AudioProcessingBuilder::~AudioProcessingBuilder() = default;
233
234AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
235 std::unique_ptr<CustomProcessing> capture_post_processing) {
236 capture_post_processing_ = std::move(capture_post_processing);
237 return *this;
238}
239
240AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
241 std::unique_ptr<CustomProcessing> render_pre_processing) {
242 render_pre_processing_ = std::move(render_pre_processing);
243 return *this;
244}
245
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200246AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
247 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
248 capture_analyzer_ = std::move(capture_analyzer);
249 return *this;
250}
251
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100252AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
253 std::unique_ptr<EchoControlFactory> echo_control_factory) {
254 echo_control_factory_ = std::move(echo_control_factory);
255 return *this;
256}
257
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100258AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200259 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100260 echo_detector_ = std::move(echo_detector);
261 return *this;
262}
263
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100264AudioProcessing* AudioProcessingBuilder::Create() {
265 webrtc::Config config;
266 return Create(config);
267}
268
269AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100270 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
271 config, std::move(capture_post_processing_),
272 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200273 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100274 if (apm->Initialize() != AudioProcessing::kNoError) {
275 delete apm;
276 apm = nullptr;
277 }
278 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100279}
280
peah88ac8532016-09-12 16:47:25 -0700281AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200282 : AudioProcessingImpl(config,
283 /*capture_post_processor=*/nullptr,
284 /*render_pre_processor=*/nullptr,
285 /*echo_control_factory=*/nullptr,
286 /*echo_detector=*/nullptr,
287 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000288
Per Åhgren13735822018-02-12 21:42:56 +0100289int AudioProcessingImpl::instance_count_ = 0;
290
Sam Zackrisson0beac582017-09-25 12:04:02 +0200291AudioProcessingImpl::AudioProcessingImpl(
292 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100293 std::unique_ptr<CustomProcessing> capture_post_processor,
294 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200295 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200296 rtc::scoped_refptr<EchoDetector> echo_detector,
297 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100298 : data_dumper_(
299 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100300 use_setup_specific_default_aec3_config_(
301 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200302 capture_runtime_settings_(kRuntimeSettingQueueSize),
303 render_runtime_settings_(kRuntimeSettingQueueSize),
304 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
305 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200306 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200307 submodule_states_(!!capture_post_processor,
308 !!render_pre_processor,
309 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200310 submodules_(std::move(capture_post_processor),
311 std::move(render_pre_processor),
312 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100313 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100314 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200315 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
316 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100317 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
318 EnforceSplitBandHpf()),
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200319 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200320 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100321 "\nEcho control factory: "
322 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200323 << "\nEcho detector: " << !!submodules_.echo_detector
324 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
325 << "\nCapture post processor: "
326 << !!submodules_.capture_post_processor
327 << "\nRender pre processor: "
328 << !!submodules_.render_pre_processor;
329
Sam Zackrisson421c8592019-02-11 13:39:46 +0100330 // Mark Echo Controller enabled if a factory is injected.
331 capture_nonlocked_.echo_controller_enabled =
332 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000333
Sam Zackrisson421c8592019-02-11 13:39:46 +0100334 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200335 if (!submodules_.echo_detector) {
336 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100337 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800338 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000339
Per Åhgren0695df12020-01-13 14:43:13 +0100340#if !(defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS))
Per Åhgrenc0734712020-01-02 15:15:36 +0100341 // TODO(webrtc:5298): Remove once the use of ExperimentalNs has been
342 // deprecated.
Per Åhgrenc0734712020-01-02 15:15:36 +0100343 config_.transient_suppression.enabled = config.Get<ExperimentalNs>().enabled;
Per Åhgren0695df12020-01-13 14:43:13 +0100344
345 // TODO(webrtc:5298): Remove once the use of ExperimentalAgc has been
346 // deprecated.
347 config_.gain_controller1.analog_gain_controller.enabled =
348 config.Get<ExperimentalAgc>().enabled;
349 config_.gain_controller1.analog_gain_controller.startup_min_volume =
350 config.Get<ExperimentalAgc>().startup_min_volume;
351 config_.gain_controller1.analog_gain_controller.clipped_level_min =
352 config.Get<ExperimentalAgc>().clipped_level_min;
353 config_.gain_controller1.analog_gain_controller.enable_agc2_level_estimator =
354 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator;
355 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive =
356 !config.Get<ExperimentalAgc>().digital_adaptive_disabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100357#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000358}
359
Per Åhgren0e3198e2019-11-18 08:52:22 +0100360AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000361
niklase@google.com470e71d2011-07-07 08:21:25 +0000362int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800363 // Run in a single-threaded manner during initialization.
364 rtc::CritScope cs_render(&crit_render_);
365 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000366 return InitializeLocked();
367}
368
peahde65ddc2016-09-16 15:02:15 -0700369int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
370 int capture_output_sample_rate_hz,
371 int render_input_sample_rate_hz,
372 ChannelLayout capture_input_layout,
373 ChannelLayout capture_output_layout,
374 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700375 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700376 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
377 LayoutHasKeyboard(capture_input_layout)},
378 {capture_output_sample_rate_hz,
379 ChannelsFromLayout(capture_output_layout),
380 LayoutHasKeyboard(capture_output_layout)},
381 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
382 LayoutHasKeyboard(render_input_layout)},
383 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
384 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700385
386 return Initialize(processing_config);
387}
388
389int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800390 // Run in a single-threaded manner during initialization.
391 rtc::CritScope cs_render(&crit_render_);
392 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700393 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000394}
395
peahdf3efa82015-11-28 12:35:15 -0800396int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800397 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800398 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200399 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800400 return kNoError;
401 }
peahdf3efa82015-11-28 12:35:15 -0800402
403 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800404 return InitializeLocked(processing_config);
405}
406
niklase@google.com470e71d2011-07-07 08:21:25 +0000407int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200408 UpdateActiveSubmoduleStates();
409
Per Åhgrend47941e2019-08-22 11:51:13 +0200410 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800411 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200412 ? formats_.render_processing_format.sample_rate_hz()
413 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800414 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
415 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200416 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800417 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200418 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700419 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200420 render_audiobuffer_sample_rate_hz,
421 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700422 if (formats_.api_format.reverse_input_stream() !=
423 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800424 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800425 formats_.api_format.reverse_input_stream().num_channels(),
426 formats_.api_format.reverse_input_stream().num_frames(),
427 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800428 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700429 } else {
peahdf3efa82015-11-28 12:35:15 -0800430 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700431 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700432 } else {
peahdf3efa82015-11-28 12:35:15 -0800433 render_.render_audio.reset(nullptr);
434 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700435 }
peahce4d9152017-05-19 01:28:05 -0700436
Per Åhgrend47941e2019-08-22 11:51:13 +0200437 capture_.capture_audio.reset(new AudioBuffer(
438 formats_.api_format.input_stream().sample_rate_hz(),
439 formats_.api_format.input_stream().num_channels(),
440 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
441 formats_.api_format.output_stream().num_channels(),
442 formats_.api_format.output_stream().sample_rate_hz(),
443 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200445 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
446 formats_.api_format.output_stream().sample_rate_hz() &&
447 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
448 capture_.capture_fullband_audio.reset(
449 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
450 formats_.api_format.input_stream().num_channels(),
451 formats_.api_format.output_stream().sample_rate_hz(),
452 formats_.api_format.output_stream().num_channels(),
453 formats_.api_format.output_stream().sample_rate_hz(),
454 formats_.api_format.output_stream().num_channels()));
455 } else {
456 capture_.capture_fullband_audio.reset();
457 }
458
peah764e3642016-10-22 05:04:30 -0700459 AllocateRenderQueue();
460
Per Åhgren0695df12020-01-13 14:43:13 +0100461 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100462 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100463 InitializeHighPassFilter(true);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200464 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700465 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200466 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700467 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200468 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200469 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200470 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100471 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800472
aleloi868f32f2017-05-23 07:20:05 -0700473 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200474 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700475 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000476 return kNoError;
477}
478
Michael Graczyk86c6d332015-07-23 11:41:39 -0700479int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200480 UpdateActiveSubmoduleStates();
481
Michael Graczyk86c6d332015-07-23 11:41:39 -0700482 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700483 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
484 return kBadSampleRateError;
485 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000486 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700487
Peter Kasting69558702016-01-12 16:26:35 -0800488 const size_t num_in_channels = config.input_stream().num_channels();
489 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700490
491 // Need at least one input channel.
492 // Need either one output channel or as many outputs as there are inputs.
493 if (num_in_channels == 0 ||
494 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700495 return kBadNumberChannelsError;
496 }
497
peahdf3efa82015-11-28 12:35:15 -0800498 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000499
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200500 // Choose maximum rate to use for the split filtering.
501 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
502 config_.pipeline.maximum_internal_processing_rate == 32000);
503 int max_splitting_rate = 48000;
504 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
505 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
506 }
507
Per Åhgrenc8626b62019-08-23 15:49:51 +0200508 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700509 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700510 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200511 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700512 submodule_states_.CaptureMultiBandSubModulesActive() ||
513 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200514 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000515
peahde65ddc2016-09-16 15:02:15 -0700516 capture_nonlocked_.capture_processing_format =
517 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700518
peah2ce640f2017-04-07 03:57:48 -0700519 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200520 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200521 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700522 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
523 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200524 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700525 submodule_states_.CaptureMultiBandSubModulesActive() ||
526 submodule_states_.RenderMultiBandSubModulesActive());
527 } else {
528 render_processing_rate = capture_processing_rate;
529 }
530
peahde65ddc2016-09-16 15:02:15 -0700531 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700532 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700533 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
534 kSampleRate8kHz) {
535 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000536 } else {
peahde65ddc2016-09-16 15:02:15 -0700537 render_processing_rate =
538 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000539 }
540
Per Åhgrenc8626b62019-08-23 15:49:51 +0200541 RTC_DCHECK_NE(8000, render_processing_rate);
542
peahce4d9152017-05-19 01:28:05 -0700543 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200544 // By default, downmix the render stream to mono for analysis. This has been
545 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100546 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
547 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200548 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100549 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200550 ? formats_.api_format.reverse_input_stream().num_channels()
551 : 1;
552 formats_.render_processing_format =
553 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700554 } else {
555 formats_.render_processing_format = StreamConfig(
556 formats_.api_format.reverse_input_stream().sample_rate_hz(),
557 formats_.api_format.reverse_input_stream().num_channels());
558 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000559
peahde65ddc2016-09-16 15:02:15 -0700560 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
561 kSampleRate32kHz ||
562 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
563 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800564 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000565 } else {
peahdf3efa82015-11-28 12:35:15 -0800566 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700567 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000568 }
569
570 return InitializeLocked();
571}
572
peah88ac8532016-09-12 16:47:25 -0700573void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200574 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
575
peah88ac8532016-09-12 16:47:25 -0700576 // Run in a single-threaded manner when applying the settings.
577 rtc::CritScope cs_render(&crit_render_);
578 rtc::CritScope cs_capture(&crit_capture_);
579
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200580 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100581 config_.pipeline.multi_channel_render !=
582 config.pipeline.multi_channel_render ||
583 config_.pipeline.multi_channel_capture !=
Per Åhgrenc0424252019-12-10 13:04:15 +0100584 config.pipeline.multi_channel_capture ||
585 config_.pipeline.maximum_internal_processing_rate !=
586 config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200587
Per Åhgren200feba2019-03-06 04:16:46 +0100588 const bool aec_config_changed =
589 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100590 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100591
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100592 const bool agc1_config_changed =
593 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
594 config_.gain_controller1.mode != config.gain_controller1.mode ||
595 config_.gain_controller1.target_level_dbfs !=
596 config.gain_controller1.target_level_dbfs ||
597 config_.gain_controller1.compression_gain_db !=
598 config.gain_controller1.compression_gain_db ||
599 config_.gain_controller1.enable_limiter !=
600 config.gain_controller1.enable_limiter ||
601 config_.gain_controller1.analog_level_minimum !=
602 config.gain_controller1.analog_level_minimum ||
603 config_.gain_controller1.analog_level_maximum !=
Per Åhgren0695df12020-01-13 14:43:13 +0100604 config.gain_controller1.analog_level_maximum ||
605 config_.gain_controller1.analog_gain_controller.enabled !=
606 config.gain_controller1.analog_gain_controller.enabled ||
607 config_.gain_controller1.analog_gain_controller.startup_min_volume !=
608 config.gain_controller1.analog_gain_controller.startup_min_volume ||
609 config_.gain_controller1.analog_gain_controller.clipped_level_min !=
610 config.gain_controller1.analog_gain_controller.clipped_level_min ||
611 config_.gain_controller1.analog_gain_controller
612 .enable_agc2_level_estimator !=
613 config.gain_controller1.analog_gain_controller
614 .enable_agc2_level_estimator ||
615 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive !=
616 config.gain_controller1.analog_gain_controller
617 .enable_digital_adaptive;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100618
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100619 const bool agc2_config_changed =
620 config_.gain_controller2.enabled != config.gain_controller2.enabled;
621
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200622 const bool voice_detection_config_changed =
623 config_.voice_detection.enabled != config.voice_detection.enabled;
624
saza0bad15f2019-10-16 11:46:11 +0200625 const bool ns_config_changed =
626 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
627 config_.noise_suppression.level != config.noise_suppression.level;
628
Per Åhgrenc0734712020-01-02 15:15:36 +0100629 const bool ts_config_changed = config_.transient_suppression.enabled !=
630 config.transient_suppression.enabled;
631
Per Åhgren0f14db22020-01-03 14:27:14 +0100632 const bool pre_amplifier_config_changed =
633 config_.pre_amplifier.enabled != config.pre_amplifier.enabled ||
634 config_.pre_amplifier.fixed_gain_factor !=
635 config.pre_amplifier.fixed_gain_factor;
636
Yves Gerey499bc6c2018-10-10 18:29:07 +0200637 config_ = config;
638
Per Åhgren200feba2019-03-06 04:16:46 +0100639 if (aec_config_changed) {
640 InitializeEchoController();
641 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200642
saza0bad15f2019-10-16 11:46:11 +0200643 if (ns_config_changed) {
644 InitializeNoiseSuppressor();
645 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100646
Per Åhgrenc0734712020-01-02 15:15:36 +0100647 if (ts_config_changed) {
648 InitializeTransientSuppressor();
649 }
650
Per Åhgren0f14db22020-01-03 14:27:14 +0100651 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800652
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100653 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100654 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100655 }
656
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100657 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700658 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100659 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
660 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100661 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100662 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700663 config_.gain_controller2 = AudioProcessing::Config::GainController2();
664 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100665
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100666 if (agc2_config_changed) {
667 InitializeGainController2();
668 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100669
670 if (pre_amplifier_config_changed) {
671 InitializePreAmplifier();
672 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100673
saza1d600522019-10-18 13:29:43 +0200674 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
675 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100676 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100677
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200678 if (voice_detection_config_changed) {
679 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100680 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200681
682 // Reinitialization must happen after all submodule configuration to avoid
683 // additional reinitializations on the next capture / render processing call.
684 if (pipeline_config_changed) {
685 InitializeLocked(formats_.api_format);
686 }
peah88ac8532016-09-12 16:47:25 -0700687}
688
Per Åhgrenc0734712020-01-02 15:15:36 +0100689// TODO(webrtc:5298): Remove.
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100690void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {}
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000691
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000692int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800693 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700694 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000695}
696
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200697int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
698 return capture_.capture_fullband_audio
699 ? capture_.capture_fullband_audio->num_frames() * 100
700 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
701}
702
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000703int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800704 // Used as callback from submodules, hence locking is not allowed.
705 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000706}
707
Peter Kasting69558702016-01-12 16:26:35 -0800708size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800709 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700710 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000711}
712
Peter Kasting69558702016-01-12 16:26:35 -0800713size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800714 // Used as callback from submodules, hence locking is not allowed.
715 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000716}
717
Peter Kasting69558702016-01-12 16:26:35 -0800718size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800719 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100720 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
721 constants_.multi_channel_capture_support;
722 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200723 return 1;
724 }
725 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800726}
727
Peter Kasting69558702016-01-12 16:26:35 -0800728size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800729 // Used as callback from submodules, hence locking is not allowed.
730 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000731}
732
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000733void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800734 rtc::CritScope cs(&crit_capture_);
735 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200736 if (submodules_.agc_manager.get()) {
737 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000738 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000739}
740
Alessio Bazzicac054e782018-04-16 12:10:09 +0200741void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200742 switch (setting.type()) {
743 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100744 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200745 render_runtime_settings_enqueuer_.Enqueue(setting);
746 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200747 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100748 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200749 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100750 capture_runtime_settings_enqueuer_.Enqueue(setting);
751 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200752 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200753 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100754 render_runtime_settings_enqueuer_.Enqueue(setting);
755 return;
756 case RuntimeSetting::Type::kNotSpecified:
757 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200758 return;
759 }
760 // The language allows the enum to have a non-enumerator
761 // value. Check that this doesn't happen.
762 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200763}
764
765AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
766 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200767 : runtime_settings_(*runtime_settings) {
768 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200769}
770
771AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
772 default;
773
774void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
775 RuntimeSetting setting) {
776 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200777 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200778 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200779 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200780 RTC_LOG(LS_ERROR)
781 << "The runtime settings queue is full. Oldest setting discarded.";
782 }
783 if (remaining_attempts == 0)
784 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
785}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000786
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100787int AudioProcessingImpl::MaybeInitializeCapture(
788 const StreamConfig& input_config,
789 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -0800790 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700791 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800792 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100793 // Acquire the capture lock in order to access api_format. The lock is
794 // released immediately, as we may need to acquire the render lock as part
795 // of the conditional reinitialization.
peahdf3efa82015-11-28 12:35:15 -0800796 rtc::CritScope cs_capture(&crit_capture_);
peahdf3efa82015-11-28 12:35:15 -0800797 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700798 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000799 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000800
Oskar Sundbom4b276482019-05-23 14:28:00 +0200801 if (processing_config.input_stream() != input_config) {
802 processing_config.input_stream() = input_config;
803 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800804 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200805
806 if (processing_config.output_stream() != output_config) {
807 processing_config.output_stream() = output_config;
808 reinitialization_required = true;
809 }
810
811 if (reinitialization_required) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200812 rtc::CritScope cs_render(&crit_render_);
813 rtc::CritScope cs_capture(&crit_capture_);
814 RETURN_ON_ERR(InitializeLocked(processing_config));
815 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100816 return kNoError;
817}
818
819int AudioProcessingImpl::ProcessStream(const float* const* src,
820 const StreamConfig& input_config,
821 const StreamConfig& output_config,
822 float* const* dest) {
823 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
824 if (!src || !dest) {
825 return kNullPointerError;
826 }
827
828 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +0200829
peahdf3efa82015-11-28 12:35:15 -0800830 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000831
aleloi868f32f2017-05-23 07:20:05 -0700832 if (aec_dump_) {
833 RecordUnprocessedCaptureStream(src);
834 }
835
Per Åhgrena1351272019-08-15 12:15:46 +0200836 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800837 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200838 if (capture_.capture_fullband_audio) {
839 capture_.capture_fullband_audio->CopyFrom(
840 src, formats_.api_format.input_stream());
841 }
peahde65ddc2016-09-16 15:02:15 -0700842 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200843 if (capture_.capture_fullband_audio) {
844 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
845 dest);
846 } else {
847 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
848 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000849
aleloi868f32f2017-05-23 07:20:05 -0700850 if (aec_dump_) {
851 RecordProcessedCaptureStream(dest);
852 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000853 return kNoError;
854}
855
Alex Loiko73ec0192018-05-15 10:52:28 +0200856void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200857 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200858 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200859 if (aec_dump_) {
860 aec_dump_->WriteRuntimeSetting(setting);
861 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200862 switch (setting.type()) {
863 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200864 if (config_.pre_amplifier.enabled) {
865 float value;
866 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200867 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200868 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200869 }
870 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200871 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100872 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100873 if (!submodules_.agc_manager) {
874 float value;
875 setting.GetFloat(&value);
876 int int_value = static_cast<int>(value + .5f);
877 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +0100878 if (submodules_.gain_control) {
879 int error =
880 submodules_.gain_control->set_compression_gain_db(int_value);
881 RTC_DCHECK_EQ(kNoError, error);
882 }
Per Åhgren0e3198e2019-11-18 08:52:22 +0100883 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100884 break;
885 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200886 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100887 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200888 float value;
889 setting.GetFloat(&value);
890 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200891 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200892 }
893 break;
894 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200895 case RuntimeSetting::Type::kPlayoutVolumeChange: {
896 int value;
897 setting.GetInt(&value);
898 capture_.playout_volume = value;
899 break;
900 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100901 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
902 RTC_NOTREACHED();
903 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200904 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
905 RTC_NOTREACHED();
906 break;
907 case RuntimeSetting::Type::kNotSpecified:
908 RTC_NOTREACHED();
909 break;
910 }
911 }
912}
913
914void AudioProcessingImpl::HandleRenderRuntimeSettings() {
915 RuntimeSetting setting;
916 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200917 if (aec_dump_) {
918 aec_dump_->WriteRuntimeSetting(setting);
919 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200920 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100921 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100922 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200923 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200924 if (submodules_.render_pre_processor) {
925 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200926 }
927 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100928 case RuntimeSetting::Type::kCapturePreGain: // fall-through
929 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200930 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200931 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200932 RTC_NOTREACHED();
933 break;
934 }
935 }
936}
937
peah9e6a2902017-05-15 07:19:21 -0700938void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800939 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700940
saza1d600522019-10-18 13:29:43 +0200941 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200942 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
943 num_reverse_channels(),
944 &aecm_render_queue_buffer_);
945 RTC_DCHECK(aecm_render_signal_queue_);
946 // Insert the samples into the queue.
947 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
948 // The data queue is full and needs to be emptied.
949 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -0700950
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200951 // Retry the insert (should always work).
952 bool result =
953 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
954 RTC_DCHECK(result);
955 }
peah764e3642016-10-22 05:04:30 -0700956 }
peah701d6282016-10-25 05:42:20 -0700957
Per Åhgren0695df12020-01-13 14:43:13 +0100958 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +0100959 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -0700960 // Insert the samples into the queue.
961 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
962 // The data queue is full and needs to be emptied.
963 EmptyQueuedRenderAudio();
964
965 // Retry the insert (should always work).
966 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
967 RTC_DCHECK(result);
968 }
969 }
peah9e6a2902017-05-15 07:19:21 -0700970}
ivoc9f4a4a02016-10-28 05:39:16 -0700971
peah9e6a2902017-05-15 07:19:21 -0700972void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700973 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
974
975 // Insert the samples into the queue.
976 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
977 // The data queue is full and needs to be emptied.
978 EmptyQueuedRenderAudio();
979
980 // Retry the insert (should always work).
981 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
982 RTC_DCHECK(result);
983 }
peah764e3642016-10-22 05:04:30 -0700984}
985
986void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700987 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700988 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700989
ivoc9f4a4a02016-10-28 05:39:16 -0700990 const size_t new_red_render_queue_element_max_size =
991 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
992
peaha0624602016-10-25 04:45:24 -0700993 // Reallocate the queues if the queue item sizes are too small to fit the
994 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700995
996 if (agc_render_queue_element_max_size_ <
997 new_agc_render_queue_element_max_size) {
998 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
999
1000 std::vector<int16_t> template_queue_element(
1001 agc_render_queue_element_max_size_);
1002
1003 agc_render_signal_queue_.reset(
1004 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1005 kMaxNumFramesToBuffer, template_queue_element,
1006 RenderQueueItemVerifier<int16_t>(
1007 agc_render_queue_element_max_size_)));
1008
1009 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1010 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1011 } else {
1012 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001013 }
ivoc9f4a4a02016-10-28 05:39:16 -07001014
1015 if (red_render_queue_element_max_size_ <
1016 new_red_render_queue_element_max_size) {
1017 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1018
1019 std::vector<float> template_queue_element(
1020 red_render_queue_element_max_size_);
1021
1022 red_render_signal_queue_.reset(
1023 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1024 kMaxNumFramesToBuffer, template_queue_element,
1025 RenderQueueItemVerifier<float>(
1026 red_render_queue_element_max_size_)));
1027
1028 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1029 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1030 } else {
1031 red_render_signal_queue_->Clear();
1032 }
peah764e3642016-10-22 05:04:30 -07001033}
1034
1035void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1036 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001037 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001038 RTC_DCHECK(aecm_render_signal_queue_);
1039 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001040 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001041 aecm_capture_queue_buffer_);
1042 }
peah701d6282016-10-25 05:42:20 -07001043 }
1044
Per Åhgren0695df12020-01-13 14:43:13 +01001045 if (submodules_.gain_control) {
1046 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1047 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1048 }
peah764e3642016-10-22 05:04:30 -07001049 }
ivoc9f4a4a02016-10-28 05:39:16 -07001050
1051 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001052 RTC_DCHECK(submodules_.echo_detector);
1053 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001054 }
peah764e3642016-10-22 05:04:30 -07001055}
1056
Per Åhgren645f24c2020-03-16 12:06:02 +01001057int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1058 const StreamConfig& input_config,
1059 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001060 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001061 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001062 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +02001063
peahdf3efa82015-11-28 12:35:15 -08001064 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001065
aleloi868f32f2017-05-23 07:20:05 -07001066 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001067 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001068 }
1069
Per Åhgren645f24c2020-03-16 12:06:02 +01001070 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001071 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001072 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001073 }
peahde65ddc2016-09-16 15:02:15 -07001074 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001075 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001076 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001077 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001078 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001079 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001080 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001081 }
Per Åhgrena1351272019-08-15 12:15:46 +02001082 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001083
aleloi868f32f2017-05-23 07:20:05 -07001084 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001085 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001086 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001087
1088 return kNoError;
1089}
1090
peahde65ddc2016-09-16 15:02:15 -07001091int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001092 EmptyQueuedRenderAudio();
Alex Loiko73ec0192018-05-15 10:52:28 +02001093 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001094
peahb58a1582016-03-15 09:34:24 -07001095 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001096 // TODO(peah): Simplify once the public API Enable functions for these
1097 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001098 RTC_DCHECK_LE(
1099 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001100
peahde65ddc2016-09-16 15:02:15 -07001101 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001102 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001103
Per Åhgrenc0424252019-12-10 13:04:15 +01001104 if (submodules_.high_pass_filter &&
1105 config_.high_pass_filter.apply_in_full_band &&
1106 !constants_.enforce_split_band_hpf) {
1107 submodules_.high_pass_filter->Process(capture_buffer,
1108 /*use_split_band_data=*/false);
1109 }
1110
saza1d600522019-10-18 13:29:43 +02001111 if (submodules_.pre_amplifier) {
1112 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001113 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001114 capture_buffer->num_frames()));
1115 }
1116
Per Åhgren928146f2019-08-20 09:19:21 +02001117 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001118 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001119 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001120 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1121 if (log_rms) {
1122 capture_rms_interval_counter_ = 0;
1123 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001124 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1125 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1126 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1127 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001128 }
1129
saza1d600522019-10-18 13:29:43 +02001130 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001131 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001132 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001133 capture_.echo_path_gain_change =
1134 capture_.prev_analog_mic_level != analog_mic_level &&
1135 capture_.prev_analog_mic_level != -1;
1136 capture_.prev_analog_mic_level = analog_mic_level;
1137
Per Åhgrend2650d12018-10-02 17:00:59 +02001138 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001139 if (submodules_.pre_amplifier) {
1140 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001141 capture_.echo_path_gain_change =
1142 capture_.echo_path_gain_change ||
1143 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001144 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001145 capture_.prev_pre_amp_gain = pre_amp_gain;
1146 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001147
1148 // Detect volume change.
1149 capture_.echo_path_gain_change =
1150 capture_.echo_path_gain_change ||
1151 (capture_.prev_playout_volume != capture_.playout_volume &&
1152 capture_.prev_playout_volume >= 0);
1153 capture_.prev_playout_volume = capture_.playout_volume;
1154
saza1d600522019-10-18 13:29:43 +02001155 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001156 }
1157
Per Åhgren0695df12020-01-13 14:43:13 +01001158 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001159 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001160 }
1161
peah2ace3f92016-09-10 04:42:27 -07001162 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1163 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001164 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1165 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001166 }
1167
Per Åhgrene14cb992019-11-27 09:34:22 +01001168 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1169 constants_.multi_channel_capture_support;
1170 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001171 // Force down-mixing of the number of channels after the detection of
1172 // capture signal saturation.
1173 // TODO(peah): Look into ensuring that this kind of tampering with the
1174 // AudioBuffer functionality should not be needed.
1175 capture_buffer->set_num_channels(1);
1176 }
1177
Per Åhgrenc0424252019-12-10 13:04:15 +01001178 if (submodules_.high_pass_filter &&
1179 (!config_.high_pass_filter.apply_in_full_band ||
1180 constants_.enforce_split_band_hpf)) {
1181 submodules_.high_pass_filter->Process(capture_buffer,
1182 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001183 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001184
Per Åhgren0695df12020-01-13 14:43:13 +01001185 if (submodules_.gain_control) {
1186 RETURN_ON_ERR(
1187 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1188 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001189
Per Åhgren8ad9e742020-01-30 07:40:58 +01001190 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1191 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1192 submodules_.noise_suppressor) {
1193 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001194 }
peahb58a1582016-03-15 09:34:24 -07001195
saza1d600522019-10-18 13:29:43 +02001196 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001197 // Ensure that the stream delay was set before the call to the
1198 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001199 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001200 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001201 }
1202
saza1d600522019-10-18 13:29:43 +02001203 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001204 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001205 }
peahe0eae3c2016-12-14 01:16:23 -08001206
saza1d600522019-10-18 13:29:43 +02001207 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001208 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001209 } else {
saza1d600522019-10-18 13:29:43 +02001210 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001211 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1212
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001213 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001214 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001215 }
1216
saza1d600522019-10-18 13:29:43 +02001217 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001218 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001219 }
1220
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001221 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001222 linear_aec_buffer && submodules_.noise_suppressor) {
1223 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001224 }
1225
saza1d600522019-10-18 13:29:43 +02001226 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001227 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001228 }
Per Åhgren46537a32017-06-07 10:08:10 +02001229 }
ivoc9f4a4a02016-10-28 05:39:16 -07001230
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001231 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001232 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001233 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001234 } else {
1235 capture_.stats.voice_detected = absl::nullopt;
1236 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001237
Per Åhgren0695df12020-01-13 14:43:13 +01001238 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001239 submodules_.agc_manager->Process(capture_buffer);
1240
1241 absl::optional<int> new_digital_gain =
1242 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001243 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001244 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1245 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001246 }
Per Åhgren0695df12020-01-13 14:43:13 +01001247
1248 if (submodules_.gain_control) {
1249 // TODO(peah): Add reporting from AEC3 whether there is echo.
1250 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1251 capture_buffer, /*stream_has_echo*/ false));
1252 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001253
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001254 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001255 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001256 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1257 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001258 }
1259
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001260 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001261 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001262 bool ec_active = ec ? ec->ActiveProcessing() : false;
1263 // Only update the fullband buffer if the multiband processing has changed
1264 // the signal. Keep the original signal otherwise.
1265 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1266 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1267 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001268 capture_buffer = capture_.capture_fullband_audio.get();
1269 }
1270
peah9e6a2902017-05-15 07:19:21 -07001271 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001272 RTC_DCHECK(submodules_.echo_detector);
1273 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1274 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001275 }
1276
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001277 // TODO(aluebs): Investigate if the transient suppression placement should be
1278 // before or after the AGC.
Per Åhgrenc0734712020-01-02 15:15:36 +01001279 if (submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001280 float voice_probability = submodules_.agc_manager.get()
1281 ? submodules_.agc_manager->voice_probability()
1282 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001283
saza1d600522019-10-18 13:29:43 +02001284 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001285 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001286 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001287 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001288 capture_buffer->num_frames_per_band(),
1289 capture_.keyboard_info.keyboard_data,
1290 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001291 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001292 }
1293
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001294 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001295 if (submodules_.capture_analyzer) {
1296 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001297 }
1298
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001299 if (submodules_.gain_controller2) {
saza1d600522019-10-18 13:29:43 +02001300 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001301 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001302 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001303 }
1304
saza1d600522019-10-18 13:29:43 +02001305 if (submodules_.capture_post_processor) {
1306 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001307 }
1308
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001309 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001310 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001311 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1312 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001313 } else {
1314 capture_.stats.output_rms_dbfs = absl::nullopt;
1315 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001316
Per Åhgren928146f2019-08-20 09:19:21 +02001317 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001318 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001319 capture_nonlocked_.capture_processing_format.num_frames()));
1320 if (log_rms) {
1321 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1322 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1323 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1324 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1325 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1326 }
1327
Per Åhgren0e3198e2019-11-18 08:52:22 +01001328 if (submodules_.agc_manager) {
1329 int level = recommended_stream_analog_level();
1330 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1331 &level);
1332 }
1333
Per Åhgrencf4c8722019-12-30 14:32:14 +01001334 // Compute echo-related stats.
1335 if (submodules_.echo_controller) {
1336 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1337 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1338 capture_.stats.echo_return_loss_enhancement =
1339 ec_metrics.echo_return_loss_enhancement;
1340 capture_.stats.delay_ms = ec_metrics.delay_ms;
1341 }
1342 if (config_.residual_echo_detector.enabled) {
1343 RTC_DCHECK(submodules_.echo_detector);
1344 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1345 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1346 capture_.stats.residual_echo_likelihood_recent_max =
1347 ed_metrics.echo_likelihood_recent_max;
1348 }
1349
1350 // Pass stats for reporting.
1351 stats_reporter_.UpdateStatistics(capture_.stats);
1352
peahdf3efa82015-11-28 12:35:15 -08001353 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001354 return kNoError;
1355}
1356
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001357int AudioProcessingImpl::AnalyzeReverseStream(
1358 const float* const* data,
1359 const StreamConfig& reverse_config) {
1360 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1361 rtc::CritScope cs(&crit_render_);
1362 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1363}
1364
peahde65ddc2016-09-16 15:02:15 -07001365int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1366 const StreamConfig& input_config,
1367 const StreamConfig& output_config,
1368 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001369 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001370 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001371 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001372 if (submodule_states_.RenderMultiBandProcessingActive() ||
1373 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001374 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1375 dest);
peah2ace3f92016-09-10 04:42:27 -07001376 } else if (formats_.api_format.reverse_input_stream() !=
1377 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001378 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1379 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001380 } else {
peahde65ddc2016-09-16 15:02:15 -07001381 CopyAudioIfNeeded(src, input_config.num_frames(),
1382 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001383 }
1384
1385 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001386}
1387
peahdf3efa82015-11-28 12:35:15 -08001388int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001389 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001390 const StreamConfig& input_config,
1391 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001392 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001393 return kNullPointerError;
1394 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001395
peahde65ddc2016-09-16 15:02:15 -07001396 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001397 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001398 }
1399
peahdf3efa82015-11-28 12:35:15 -08001400 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001401 processing_config.reverse_input_stream() = input_config;
1402 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001403
peahdf3efa82015-11-28 12:35:15 -08001404 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001405 RTC_DCHECK_EQ(input_config.num_frames(),
1406 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001407
aleloi868f32f2017-05-23 07:20:05 -07001408 if (aec_dump_) {
1409 const size_t channel_size =
1410 formats_.api_format.reverse_input_stream().num_frames();
1411 const size_t num_channels =
1412 formats_.api_format.reverse_input_stream().num_channels();
1413 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001414 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001415 }
peahdf3efa82015-11-28 12:35:15 -08001416 render_.render_audio->CopyFrom(src,
1417 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001418 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001419}
1420
Per Åhgren645f24c2020-03-16 12:06:02 +01001421int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1422 const StreamConfig& input_config,
1423 const StreamConfig& output_config,
1424 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001425 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001426
1427 if (input_config.num_channels() <= 0) {
1428 return AudioProcessing::Error::kBadNumberChannelsError;
1429 }
1430
Per Åhgren645f24c2020-03-16 12:06:02 +01001431 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001432 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001433 processing_config.reverse_input_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001434 input_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001435 processing_config.reverse_input_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001436 input_config.num_channels());
ekmeyerson60d9b332015-08-14 10:35:55 -07001437 processing_config.reverse_output_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001438 output_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001439 processing_config.reverse_output_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001440 output_config.num_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001441
peahdf3efa82015-11-28 12:35:15 -08001442 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Per Åhgren645f24c2020-03-16 12:06:02 +01001443 if (input_config.num_frames() !=
peahdf3efa82015-11-28 12:35:15 -08001444 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001445 return kBadDataLengthError;
1446 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001447
aleloi868f32f2017-05-23 07:20:05 -07001448 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001449 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1450 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001451 }
1452
Per Åhgren645f24c2020-03-16 12:06:02 +01001453 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001454 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001455 if (submodule_states_.RenderMultiBandProcessingActive() ||
1456 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001457 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001458 }
aluebsb0319552016-03-17 20:39:53 -07001459 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001460}
niklase@google.com470e71d2011-07-07 08:21:25 +00001461
peahde65ddc2016-09-16 15:02:15 -07001462int AudioProcessingImpl::ProcessRenderStreamLocked() {
1463 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001464
Alex Loiko73ec0192018-05-15 10:52:28 +02001465 HandleRenderRuntimeSettings();
1466
saza1d600522019-10-18 13:29:43 +02001467 if (submodules_.render_pre_processor) {
1468 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001469 }
1470
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001471 QueueNonbandedRenderAudio(render_buffer);
1472
peah2ace3f92016-09-10 04:42:27 -07001473 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001474 SampleRateSupportsMultiBand(
1475 formats_.render_processing_format.sample_rate_hz())) {
1476 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001477 }
1478
peahce4d9152017-05-19 01:28:05 -07001479 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1480 QueueBandedRenderAudio(render_buffer);
1481 }
1482
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001483 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001484 if (submodules_.echo_controller) {
1485 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001486 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001487
peah2ace3f92016-09-10 04:42:27 -07001488 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001489 SampleRateSupportsMultiBand(
1490 formats_.render_processing_format.sample_rate_hz())) {
1491 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001492 }
1493
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001494 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001495}
1496
1497int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001498 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001499 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001500 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001501
niklase@google.com470e71d2011-07-07 08:21:25 +00001502 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001503 delay = 0;
1504 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001505 }
1506
1507 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1508 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001509 delay = 500;
1510 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001511 }
1512
peahdf3efa82015-11-28 12:35:15 -08001513 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001514 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001515}
1516
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001517bool AudioProcessingImpl::GetLinearAecOutput(
1518 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1519 rtc::CritScope cs(&crit_capture_);
1520 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1521
1522 RTC_DCHECK(linear_aec_buffer);
1523 if (linear_aec_buffer) {
1524 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1525 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1526
1527 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1528 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1529 rtc::ArrayView<const float> channel_view =
1530 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1531 linear_aec_buffer->num_frames());
1532 std::copy(channel_view.begin(), channel_view.end(),
1533 linear_output[ch].begin());
1534 }
1535 return true;
1536 }
1537 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1538 RTC_NOTREACHED();
1539 return false;
1540}
1541
niklase@google.com470e71d2011-07-07 08:21:25 +00001542int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001543 // Used as callback from submodules, hence locking is not allowed.
1544 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001545}
1546
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001547void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001548 rtc::CritScope cs(&crit_capture_);
1549 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001550}
1551
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001552void AudioProcessingImpl::set_stream_analog_level(int level) {
1553 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001554
1555 if (submodules_.agc_manager) {
1556 submodules_.agc_manager->set_stream_analog_level(level);
1557 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1558 1, &level);
Per Åhgren0695df12020-01-13 14:43:13 +01001559 } else if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001560 int error = submodules_.gain_control->set_stream_analog_level(level);
1561 RTC_DCHECK_EQ(kNoError, error);
Per Åhgren0695df12020-01-13 14:43:13 +01001562 } else {
1563 capture_.cached_stream_analog_level_ = level;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001564 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001565}
1566
1567int AudioProcessingImpl::recommended_stream_analog_level() const {
1568 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001569 if (submodules_.agc_manager) {
1570 return submodules_.agc_manager->stream_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01001571 } else if (submodules_.gain_control) {
1572 return submodules_.gain_control->stream_analog_level();
1573 } else {
1574 return capture_.cached_stream_analog_level_;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001575 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001576}
1577
aleloi868f32f2017-05-23 07:20:05 -07001578void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1579 RTC_DCHECK(aec_dump);
1580 rtc::CritScope cs_render(&crit_render_);
1581 rtc::CritScope cs_capture(&crit_capture_);
1582
1583 // The previously attached AecDump will be destroyed with the
1584 // 'aec_dump' parameter, which is after locks are released.
1585 aec_dump_.swap(aec_dump);
1586 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001587 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001588}
1589
1590void AudioProcessingImpl::DetachAecDump() {
1591 // The d-tor of a task-queue based AecDump blocks until all pending
1592 // tasks are done. This construction avoids blocking while holding
1593 // the render and capture locks.
1594 std::unique_ptr<AecDump> aec_dump = nullptr;
1595 {
1596 rtc::CritScope cs_render(&crit_render_);
1597 rtc::CritScope cs_capture(&crit_capture_);
1598 aec_dump = std::move(aec_dump_);
1599 }
1600}
1601
Sam Zackrisson4d364492018-03-02 16:03:21 +01001602void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1603 std::unique_ptr<AudioGenerator> audio_generator) {
1604 // TODO(bugs.webrtc.org/8882) Stub.
1605 // Reset internal audio generator with audio_generator.
1606}
1607
1608void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1609 // TODO(bugs.webrtc.org/8882) Stub.
1610 // Delete audio generator, if one is attached.
1611}
1612
peah8271d042016-11-22 07:24:52 -08001613void AudioProcessingImpl::MutateConfig(
1614 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1615 rtc::CritScope cs_render(&crit_render_);
1616 rtc::CritScope cs_capture(&crit_capture_);
1617 mutator(&config_);
1618 ApplyConfig(config_);
1619}
1620
1621AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1622 rtc::CritScope cs_render(&crit_render_);
1623 rtc::CritScope cs_capture(&crit_capture_);
1624 return config_;
1625}
1626
peah2ace3f92016-09-10 04:42:27 -07001627bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1628 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001629 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Per Åhgren8ad9e742020-01-30 07:40:58 +01001630 config_.residual_echo_detector.enabled, !!submodules_.noise_suppressor,
Per Åhgren0695df12020-01-13 14:43:13 +01001631 !!submodules_.gain_control, !!submodules_.gain_controller2,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001632 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
Per Åhgrenc0734712020-01-02 15:15:36 +01001633 config_.voice_detection.enabled, !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001634}
1635
Per Åhgrenc0734712020-01-02 15:15:36 +01001636void AudioProcessingImpl::InitializeTransientSuppressor() {
1637 if (config_.transient_suppression.enabled) {
1638 if (!submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001639 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001640 }
saza1d600522019-10-18 13:29:43 +02001641 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1642 capture_nonlocked_.split_rate,
1643 num_proc_channels());
Per Åhgrenc0734712020-01-02 15:15:36 +01001644 } else {
1645 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001646 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001647}
1648
Per Åhgren0f14db22020-01-03 14:27:14 +01001649void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01001650 bool high_pass_filter_needed_by_aec =
1651 config_.echo_canceller.enabled &&
1652 config_.echo_canceller.enforce_high_pass_filtering &&
1653 !config_.echo_canceller.mobile_mode;
1654 if (submodule_states_.HighPassFilteringRequired() ||
1655 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001656 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1657 !constants_.enforce_split_band_hpf;
1658 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1659 : proc_split_sample_rate_hz();
1660 size_t num_channels =
1661 use_full_band ? num_output_channels() : num_proc_channels();
1662
Per Åhgren0f14db22020-01-03 14:27:14 +01001663 if (!submodules_.high_pass_filter ||
1664 rate != submodules_.high_pass_filter->sample_rate_hz() ||
1665 forced_reset ||
1666 num_channels != submodules_.high_pass_filter->num_channels()) {
1667 submodules_.high_pass_filter.reset(
1668 new HighPassFilter(rate, num_channels));
1669 }
peah8271d042016-11-22 07:24:52 -08001670 } else {
saza1d600522019-10-18 13:29:43 +02001671 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001672 }
1673}
alessiob3ec96df2017-05-22 06:57:06 -07001674
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001675void AudioProcessingImpl::InitializeVoiceDetector() {
1676 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001677 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001678 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1679 } else {
saza1d600522019-10-18 13:29:43 +02001680 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001681 }
1682}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001683void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001684 bool use_echo_controller =
1685 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001686 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001687
1688 if (use_echo_controller) {
1689 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001690 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001691 submodules_.echo_controller = echo_control_factory_->Create(
1692 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001693 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001694 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001695 EchoCanceller3Config config =
1696 use_setup_specific_default_aec3_config_
1697 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1698 num_proc_channels())
1699 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001700 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001701 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001702 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001703 }
1704
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001705 // Setup the storage for returning the linear AEC output.
1706 if (config_.echo_canceller.export_linear_aec_output) {
1707 constexpr int kLinearOutputRateHz = 16000;
1708 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1709 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1710 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1711 } else {
1712 capture_.linear_aec_output.reset();
1713 }
1714
Per Åhgren200feba2019-03-06 04:16:46 +01001715 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001716
saza1d600522019-10-18 13:29:43 +02001717 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001718 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001719 return;
peahe0eae3c2016-12-14 01:16:23 -08001720 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001721
saza1d600522019-10-18 13:29:43 +02001722 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001723 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001724 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001725
1726 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001727 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001728 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001729 return;
1730 }
1731
1732 if (config_.echo_canceller.mobile_mode) {
1733 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001734 size_t max_element_size =
1735 std::max(static_cast<size_t>(1),
1736 kMaxAllowedValuesOfSamplesPerBand *
1737 EchoControlMobileImpl::NumCancellersRequired(
1738 num_output_channels(), num_reverse_channels()));
1739
1740 std::vector<int16_t> template_queue_element(max_element_size);
1741
1742 aecm_render_signal_queue_.reset(
1743 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1744 kMaxNumFramesToBuffer, template_queue_element,
1745 RenderQueueItemVerifier<int16_t>(max_element_size)));
1746
1747 aecm_render_queue_buffer_.resize(max_element_size);
1748 aecm_capture_queue_buffer_.resize(max_element_size);
1749
saza1d600522019-10-18 13:29:43 +02001750 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001751
saza1d600522019-10-18 13:29:43 +02001752 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1753 num_reverse_channels(),
1754 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001755 return;
1756 }
1757
saza1d600522019-10-18 13:29:43 +02001758 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001759 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001760}
peah8271d042016-11-22 07:24:52 -08001761
Per Åhgren0695df12020-01-13 14:43:13 +01001762void AudioProcessingImpl::InitializeGainController1() {
1763 if (!config_.gain_controller1.enabled) {
1764 submodules_.agc_manager.reset();
1765 submodules_.gain_control.reset();
1766 return;
1767 }
1768
1769 if (!submodules_.gain_control) {
1770 submodules_.gain_control.reset(new GainControlImpl());
1771 }
1772
1773 submodules_.gain_control->Initialize(num_proc_channels(),
1774 proc_sample_rate_hz());
1775
1776 if (!config_.gain_controller1.analog_gain_controller.enabled) {
1777 int error = submodules_.gain_control->set_mode(
1778 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
1779 RTC_DCHECK_EQ(kNoError, error);
1780 error = submodules_.gain_control->set_target_level_dbfs(
1781 config_.gain_controller1.target_level_dbfs);
1782 RTC_DCHECK_EQ(kNoError, error);
1783 error = submodules_.gain_control->set_compression_gain_db(
1784 config_.gain_controller1.compression_gain_db);
1785 RTC_DCHECK_EQ(kNoError, error);
1786 error = submodules_.gain_control->enable_limiter(
1787 config_.gain_controller1.enable_limiter);
1788 RTC_DCHECK_EQ(kNoError, error);
1789 error = submodules_.gain_control->set_analog_level_limits(
1790 config_.gain_controller1.analog_level_minimum,
1791 config_.gain_controller1.analog_level_maximum);
1792 RTC_DCHECK_EQ(kNoError, error);
1793
1794 submodules_.agc_manager.reset();
1795 return;
1796 }
1797
1798 if (!submodules_.agc_manager.get() ||
1799 submodules_.agc_manager->num_channels() !=
1800 static_cast<int>(num_proc_channels()) ||
1801 submodules_.agc_manager->sample_rate_hz() !=
1802 capture_nonlocked_.split_rate) {
1803 int stream_analog_level = -1;
1804 const bool re_creation = !!submodules_.agc_manager;
1805 if (re_creation) {
1806 stream_analog_level = submodules_.agc_manager->stream_analog_level();
1807 }
1808 submodules_.agc_manager.reset(new AgcManagerDirect(
1809 num_proc_channels(),
1810 config_.gain_controller1.analog_gain_controller.startup_min_volume,
1811 config_.gain_controller1.analog_gain_controller.clipped_level_min,
1812 config_.gain_controller1.analog_gain_controller
1813 .enable_agc2_level_estimator,
1814 !config_.gain_controller1.analog_gain_controller
1815 .enable_digital_adaptive,
1816 capture_nonlocked_.split_rate));
1817 if (re_creation) {
1818 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
1819 }
1820 }
1821 submodules_.agc_manager->Initialize();
1822 submodules_.agc_manager->SetupDigitalGainControl(
1823 submodules_.gain_control.get());
1824 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
1825}
1826
alessiob3ec96df2017-05-22 06:57:06 -07001827void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001828 if (config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001829 if (!submodules_.gain_controller2) {
1830 // TODO(alessiob): Move the injected gain controller once injection is
1831 // implemented.
1832 submodules_.gain_controller2.reset(new GainController2());
1833 }
1834
saza1d600522019-10-18 13:29:43 +02001835 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001836 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
1837 } else {
1838 submodules_.gain_controller2.reset();
alessiob3ec96df2017-05-22 06:57:06 -07001839 }
1840}
1841
saza0bad15f2019-10-16 11:46:11 +02001842void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001843 submodules_.noise_suppressor.reset();
1844
saza0bad15f2019-10-16 11:46:11 +02001845 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001846 auto map_level =
1847 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1848 using NoiseSuppresionConfig =
1849 AudioProcessing::Config::NoiseSuppression;
1850 switch (level) {
1851 case NoiseSuppresionConfig::kLow:
1852 return NsConfig::SuppressionLevel::k6dB;
1853 case NoiseSuppresionConfig::kModerate:
1854 return NsConfig::SuppressionLevel::k12dB;
1855 case NoiseSuppresionConfig::kHigh:
1856 return NsConfig::SuppressionLevel::k18dB;
1857 case NoiseSuppresionConfig::kVeryHigh:
1858 return NsConfig::SuppressionLevel::k21dB;
1859 default:
1860 RTC_NOTREACHED();
1861 }
1862 };
1863
1864 NsConfig cfg;
1865 cfg.target_level = map_level(config_.noise_suppression.level);
1866 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1867 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02001868 }
1869}
1870
Alex Loikob5c9a792018-04-16 16:31:22 +02001871void AudioProcessingImpl::InitializePreAmplifier() {
1872 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001873 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001874 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1875 } else {
saza1d600522019-10-18 13:29:43 +02001876 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001877 }
1878}
1879
ivoc9f4a4a02016-10-28 05:39:16 -07001880void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001881 RTC_DCHECK(submodules_.echo_detector);
1882 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001883 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001884 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001885}
1886
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001887void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001888 if (submodules_.capture_analyzer) {
1889 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1890 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001891 }
1892}
1893
Sam Zackrisson0beac582017-09-25 12:04:02 +02001894void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001895 if (submodules_.capture_post_processor) {
1896 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001897 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001898 }
1899}
1900
Alex Loiko5825aa62017-12-18 16:02:40 +01001901void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001902 if (submodules_.render_pre_processor) {
1903 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001904 formats_.render_processing_format.sample_rate_hz(),
1905 formats_.render_processing_format.num_channels());
1906 }
1907}
1908
Per Åhgrenea4c5df2019-05-03 09:00:08 +02001909void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001910
aleloi868f32f2017-05-23 07:20:05 -07001911void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1912 if (!aec_dump_) {
1913 return;
1914 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001915
1916 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07001917 // TODO(peah): Add semicolon-separated concatenations of experiment
1918 // descriptions for other submodules.
Per Åhgren0695df12020-01-13 14:43:13 +01001919 if (config_.gain_controller1.analog_gain_controller.clipped_level_min !=
1920 kClippedLevelMin) {
aleloi868f32f2017-05-23 07:20:05 -07001921 experiments_description += "AgcClippingLevelExperiment;";
1922 }
Sam Zackrisson701bd172020-02-18 14:50:28 +01001923 if (!!submodules_.capture_post_processor) {
1924 experiments_description += "CapturePostProcessor;";
1925 }
1926 if (!!submodules_.render_pre_processor) {
1927 experiments_description += "RenderPreProcessor;";
1928 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001929 if (capture_nonlocked_.echo_controller_enabled) {
1930 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001931 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001932 if (config_.gain_controller2.enabled) {
1933 experiments_description += "GainController2;";
1934 }
aleloi868f32f2017-05-23 07:20:05 -07001935
1936 InternalAPMConfig apm_config;
1937
Per Åhgren200feba2019-03-06 04:16:46 +01001938 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001939 apm_config.aec_delay_agnostic_enabled = false;
1940 apm_config.aec_extended_filter_enabled = false;
1941 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07001942
saza1d600522019-10-18 13:29:43 +02001943 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07001944 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02001945 submodules_.echo_control_mobile &&
1946 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001947 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02001948 submodules_.echo_control_mobile
1949 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001950 : 0;
aleloi868f32f2017-05-23 07:20:05 -07001951
Per Åhgren0695df12020-01-13 14:43:13 +01001952 apm_config.agc_enabled = !!submodules_.gain_control;
1953
1954 apm_config.agc_mode = submodules_.gain_control
1955 ? static_cast<int>(submodules_.gain_control->mode())
1956 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07001957 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01001958 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
1959 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001960 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07001961
1962 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1963
saza0bad15f2019-10-16 11:46:11 +02001964 apm_config.ns_enabled = config_.noise_suppression.enabled;
1965 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07001966
1967 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01001968 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07001969 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001970 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1971 apm_config.pre_amplifier_fixed_gain_factor =
1972 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001973
1974 if (!forced && apm_config == apm_config_for_aec_dump_) {
1975 return;
1976 }
1977 aec_dump_->WriteConfig(apm_config);
1978 apm_config_for_aec_dump_ = apm_config;
1979}
1980
1981void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1982 const float* const* src) {
1983 RTC_DCHECK(aec_dump_);
1984 WriteAecDumpConfigMessage(false);
1985
1986 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1987 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1988 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001989 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001990 RecordAudioProcessingState();
1991}
1992
1993void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01001994 const int16_t* const data,
1995 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07001996 RTC_DCHECK(aec_dump_);
1997 WriteAecDumpConfigMessage(false);
1998
Per Åhgren645f24c2020-03-16 12:06:02 +01001999 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2000 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002001 RecordAudioProcessingState();
2002}
2003
2004void AudioProcessingImpl::RecordProcessedCaptureStream(
2005 const float* const* processed_capture_stream) {
2006 RTC_DCHECK(aec_dump_);
2007
2008 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2009 const size_t num_channels =
2010 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002011 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2012 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002013 aec_dump_->WriteCaptureStreamMessage();
2014}
2015
2016void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002017 const int16_t* const data,
2018 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002019 RTC_DCHECK(aec_dump_);
2020
Per Åhgren645f24c2020-03-16 12:06:02 +01002021 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002022 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002023 aec_dump_->WriteCaptureStreamMessage();
2024}
2025
2026void AudioProcessingImpl::RecordAudioProcessingState() {
2027 RTC_DCHECK(aec_dump_);
2028 AecDump::AudioProcessingState audio_proc_state;
2029 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002030 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002031 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002032 audio_proc_state.keypress = capture_.key_pressed;
2033 aec_dump_->AddAudioProcessingState(audio_proc_state);
2034}
2035
Per Åhgrenc0734712020-01-02 15:15:36 +01002036AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002037 : was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002038 output_will_be_muted(false),
2039 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002040 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002041 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002042 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002043 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002044 prev_pre_amp_gain(-1.f),
2045 playout_volume(-1),
2046 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002047
2048AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2049
Per Åhgrena1351272019-08-15 12:15:46 +02002050void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2051 const float* const* data,
2052 const StreamConfig& stream_config) {
2053 if (stream_config.has_keyboard()) {
2054 keyboard_data = data[stream_config.num_channels()];
2055 } else {
2056 keyboard_data = NULL;
2057 }
2058 num_keyboard_frames = stream_config.num_frames();
2059}
2060
kwiberg83ffe452016-08-29 14:46:07 -07002061AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2062
2063AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2064
Per Åhgrencf4c8722019-12-30 14:32:14 +01002065AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2066 : stats_message_queue_(1) {}
2067
2068AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2069
2070AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
2071 rtc::CritScope cs_stats(&crit_stats_);
2072 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2073 // If the message queue is full, return the cached stats.
2074 static_cast<void>(new_stats_available);
2075
2076 return cached_stats_;
2077}
2078
2079void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2080 const AudioProcessingStats& new_stats) {
2081 AudioProcessingStats stats_to_queue = new_stats;
2082 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2083 // If the message queue is full, discard the new stats.
2084 static_cast<void>(stats_message_passed);
2085}
2086
niklase@google.com470e71d2011-07-07 08:21:25 +00002087} // namespace webrtc