blob: bdef05968664be1bf17ed691bad8cd3f6c8eed48 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
alessiob3ec96df2017-05-22 06:57:06 -070016#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020017#include <type_traits>
18#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Yves Gerey988cc082018-10-23 12:03:01 +020020#include "absl/types/optional.h"
21#include "api/array_view.h"
Per Åhgren645f24c2020-03-16 12:06:02 +010022#include "api/audio/audio_frame.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "common_audio/include/audio_util.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020025#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/audio_processing/common.h"
Yves Gerey988cc082018-10-23 12:03:01 +020028#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 21:42:56 +010029#include "modules/audio_processing/logging/apm_data_dumper.h"
sazaaa42ecd2020-04-01 15:24:40 +020030#include "modules/audio_processing/transient/transient_suppressor_creator.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "rtc_base/ref_counted_object.h"
36#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020038#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000040
Michael Graczyk86c6d332015-07-23 11:41:39 -070041#define RETURN_ON_ERR(expr) \
42 do { \
43 int err = (expr); \
44 if (err != kNoError) { \
45 return err; \
46 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000047 } while (0)
48
niklase@google.com470e71d2011-07-07 08:21:25 +000049namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070050
Alex Loiko73ec0192018-05-15 10:52:28 +020051constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070052
Michael Graczyk86c6d332015-07-23 11:41:39 -070053namespace {
54
55static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
56 switch (layout) {
57 case AudioProcessing::kMono:
58 case AudioProcessing::kStereo:
59 return false;
60 case AudioProcessing::kMonoAndKeyboard:
61 case AudioProcessing::kStereoAndKeyboard:
62 return true;
63 }
64
kwiberg9e2be5f2016-09-14 05:23:22 -070065 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070066 return false;
67}
aluebsdf6416a2016-03-16 18:26:35 -070068
peah2ace3f92016-09-10 04:42:27 -070069bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070070 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
71 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
72}
73
Per Åhgrenc0424252019-12-10 13:04:15 +010074// Checks whether the high-pass filter should be done in the full-band.
75bool EnforceSplitBandHpf() {
76 return field_trial::IsEnabled("WebRTC-FullBandHpfKillSwitch");
77}
78
Per Åhgrenb2b58d82019-12-02 14:59:40 +010079// Checks whether AEC3 should be allowed to decide what the default
80// configuration should be based on the render and capture channel configuration
81// at hand.
82bool UseSetupSpecificDefaultAec3Congfig() {
83 return !field_trial::IsEnabled(
84 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
85}
86
Per Åhgrenc8626b62019-08-23 15:49:51 +020087// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020088int SuitableProcessRate(int minimum_rate,
89 int max_splitting_rate,
90 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020091 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020092 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020093 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070094 if (rate >= uppermost_native_rate) {
95 return uppermost_native_rate;
96 }
97 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070098 return rate;
99 }
100 }
peah2ace3f92016-09-10 04:42:27 -0700101 RTC_NOTREACHED();
102 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700103}
104
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100105GainControl::Mode Agc1ConfigModeToInterfaceMode(
106 AudioProcessing::Config::GainController1::Mode mode) {
107 using Agc1Config = AudioProcessing::Config::GainController1;
108 switch (mode) {
109 case Agc1Config::kAdaptiveAnalog:
110 return GainControl::kAdaptiveAnalog;
111 case Agc1Config::kAdaptiveDigital:
112 return GainControl::kAdaptiveDigital;
113 case Agc1Config::kFixedDigital:
114 return GainControl::kFixedDigital;
115 }
116}
117
peah9e6a2902017-05-15 07:19:21 -0700118// Maximum lengths that frame of samples being passed from the render side to
119// the capture side can have (does not apply to AEC3).
120static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
121static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
122
peah764e3642016-10-22 05:04:30 -0700123// Maximum number of frames to buffer in the render queue.
124// TODO(peah): Decrease this once we properly handle hugely unbalanced
125// reverse and forward call numbers.
126static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700127} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000128
129// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000130static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000131
saza1d600522019-10-18 13:29:43 +0200132AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100133 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200134 bool render_pre_processor_enabled,
135 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100136 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200137 render_pre_processor_enabled_(render_pre_processor_enabled),
138 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700139
saza1d600522019-10-18 13:29:43 +0200140bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200141 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700142 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700143 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700144 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700145 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700146 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200147 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200148 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200149 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700150 bool transient_suppressor_enabled) {
151 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200152 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700153 changed |=
154 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700155 changed |=
156 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700157 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
158 changed |=
peah2ace3f92016-09-10 04:42:27 -0700159 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200160 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200161 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200162 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200163 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700164 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
165 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200166 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700167 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700168 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700169 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700170 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700171 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200172 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200173 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200174 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700175 transient_suppressor_enabled_ = transient_suppressor_enabled;
176 }
177
178 changed |= first_update_;
179 first_update_ = false;
180 return changed;
181}
182
saza1d600522019-10-18 13:29:43 +0200183bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700184 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200185 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700186}
187
saza1d600522019-10-18 13:29:43 +0200188bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
189 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200190 // If echo controller is present, assume it performs active processing.
191 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
192}
193
saza1d600522019-10-18 13:29:43 +0200194bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200195 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100196 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
197 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200198 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700199}
200
saza1d600522019-10-18 13:29:43 +0200201bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700202 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200203 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
204 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700205}
206
saza1d600522019-10-18 13:29:43 +0200207bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200208 return capture_analyzer_enabled_;
209}
210
saza1d600522019-10-18 13:29:43 +0200211bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700212 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100213 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
214 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700215}
216
saza1d600522019-10-18 13:29:43 +0200217bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100218 const {
219 return render_pre_processor_enabled_;
220}
221
saza1d600522019-10-18 13:29:43 +0200222bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700223 const {
peah2ace3f92016-09-10 04:42:27 -0700224 return false;
peah2ace3f92016-09-10 04:42:27 -0700225}
226
saza1d600522019-10-18 13:29:43 +0200227bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100228 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
229 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200230}
231
peah88ac8532016-09-12 16:47:25 -0700232AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200233 : AudioProcessingImpl(config,
234 /*capture_post_processor=*/nullptr,
235 /*render_pre_processor=*/nullptr,
236 /*echo_control_factory=*/nullptr,
237 /*echo_detector=*/nullptr,
238 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000239
Per Åhgren13735822018-02-12 21:42:56 +0100240int AudioProcessingImpl::instance_count_ = 0;
241
Sam Zackrisson0beac582017-09-25 12:04:02 +0200242AudioProcessingImpl::AudioProcessingImpl(
243 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100244 std::unique_ptr<CustomProcessing> capture_post_processor,
245 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200246 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200247 rtc::scoped_refptr<EchoDetector> echo_detector,
248 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100249 : data_dumper_(
250 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100251 use_setup_specific_default_aec3_config_(
252 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200253 capture_runtime_settings_(kRuntimeSettingQueueSize),
254 render_runtime_settings_(kRuntimeSettingQueueSize),
255 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
256 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200257 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200258 submodule_states_(!!capture_post_processor,
259 !!render_pre_processor,
260 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200261 submodules_(std::move(capture_post_processor),
262 std::move(render_pre_processor),
263 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100264 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100265 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200266 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
267 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100268 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
269 EnforceSplitBandHpf()),
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200270 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200271 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100272 "\nEcho control factory: "
273 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200274 << "\nEcho detector: " << !!submodules_.echo_detector
275 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
276 << "\nCapture post processor: "
277 << !!submodules_.capture_post_processor
278 << "\nRender pre processor: "
279 << !!submodules_.render_pre_processor;
280
Sam Zackrisson421c8592019-02-11 13:39:46 +0100281 // Mark Echo Controller enabled if a factory is injected.
282 capture_nonlocked_.echo_controller_enabled =
283 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000284
Sam Zackrisson421c8592019-02-11 13:39:46 +0100285 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200286 if (!submodules_.echo_detector) {
287 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100288 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800289 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000290
Per Åhgren0695df12020-01-13 14:43:13 +0100291#if !(defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS))
Per Åhgrenc0734712020-01-02 15:15:36 +0100292 // TODO(webrtc:5298): Remove once the use of ExperimentalNs has been
293 // deprecated.
Per Åhgrenc0734712020-01-02 15:15:36 +0100294 config_.transient_suppression.enabled = config.Get<ExperimentalNs>().enabled;
Per Åhgren0695df12020-01-13 14:43:13 +0100295
296 // TODO(webrtc:5298): Remove once the use of ExperimentalAgc has been
297 // deprecated.
298 config_.gain_controller1.analog_gain_controller.enabled =
299 config.Get<ExperimentalAgc>().enabled;
300 config_.gain_controller1.analog_gain_controller.startup_min_volume =
301 config.Get<ExperimentalAgc>().startup_min_volume;
302 config_.gain_controller1.analog_gain_controller.clipped_level_min =
303 config.Get<ExperimentalAgc>().clipped_level_min;
304 config_.gain_controller1.analog_gain_controller.enable_agc2_level_estimator =
305 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator;
306 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive =
307 !config.Get<ExperimentalAgc>().digital_adaptive_disabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100308#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000309}
310
Per Åhgren0e3198e2019-11-18 08:52:22 +0100311AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000312
niklase@google.com470e71d2011-07-07 08:21:25 +0000313int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800314 // Run in a single-threaded manner during initialization.
315 rtc::CritScope cs_render(&crit_render_);
316 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000317 return InitializeLocked();
318}
319
peahde65ddc2016-09-16 15:02:15 -0700320int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
321 int capture_output_sample_rate_hz,
322 int render_input_sample_rate_hz,
323 ChannelLayout capture_input_layout,
324 ChannelLayout capture_output_layout,
325 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700326 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700327 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
328 LayoutHasKeyboard(capture_input_layout)},
329 {capture_output_sample_rate_hz,
330 ChannelsFromLayout(capture_output_layout),
331 LayoutHasKeyboard(capture_output_layout)},
332 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
333 LayoutHasKeyboard(render_input_layout)},
334 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
335 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700336
337 return Initialize(processing_config);
338}
339
340int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800341 // Run in a single-threaded manner during initialization.
342 rtc::CritScope cs_render(&crit_render_);
343 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700344 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000345}
346
peahdf3efa82015-11-28 12:35:15 -0800347int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800348 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800349 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200350 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800351 return kNoError;
352 }
peahdf3efa82015-11-28 12:35:15 -0800353
354 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800355 return InitializeLocked(processing_config);
356}
357
niklase@google.com470e71d2011-07-07 08:21:25 +0000358int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200359 UpdateActiveSubmoduleStates();
360
Per Åhgrend47941e2019-08-22 11:51:13 +0200361 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800362 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200363 ? formats_.render_processing_format.sample_rate_hz()
364 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800365 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
366 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200367 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800368 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200369 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700370 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200371 render_audiobuffer_sample_rate_hz,
372 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700373 if (formats_.api_format.reverse_input_stream() !=
374 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800375 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800376 formats_.api_format.reverse_input_stream().num_channels(),
377 formats_.api_format.reverse_input_stream().num_frames(),
378 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800379 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700380 } else {
peahdf3efa82015-11-28 12:35:15 -0800381 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700382 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700383 } else {
peahdf3efa82015-11-28 12:35:15 -0800384 render_.render_audio.reset(nullptr);
385 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700386 }
peahce4d9152017-05-19 01:28:05 -0700387
Per Åhgrend47941e2019-08-22 11:51:13 +0200388 capture_.capture_audio.reset(new AudioBuffer(
389 formats_.api_format.input_stream().sample_rate_hz(),
390 formats_.api_format.input_stream().num_channels(),
391 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
392 formats_.api_format.output_stream().num_channels(),
393 formats_.api_format.output_stream().sample_rate_hz(),
394 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000395
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200396 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
397 formats_.api_format.output_stream().sample_rate_hz() &&
398 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
399 capture_.capture_fullband_audio.reset(
400 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
401 formats_.api_format.input_stream().num_channels(),
402 formats_.api_format.output_stream().sample_rate_hz(),
403 formats_.api_format.output_stream().num_channels(),
404 formats_.api_format.output_stream().sample_rate_hz(),
405 formats_.api_format.output_stream().num_channels()));
406 } else {
407 capture_.capture_fullband_audio.reset();
408 }
409
peah764e3642016-10-22 05:04:30 -0700410 AllocateRenderQueue();
411
Per Åhgren0695df12020-01-13 14:43:13 +0100412 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100413 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100414 InitializeHighPassFilter(true);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200415 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700416 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200417 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700418 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200419 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200420 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200421 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100422 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800423
aleloi868f32f2017-05-23 07:20:05 -0700424 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200425 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700426 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000427 return kNoError;
428}
429
Michael Graczyk86c6d332015-07-23 11:41:39 -0700430int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200431 UpdateActiveSubmoduleStates();
432
Michael Graczyk86c6d332015-07-23 11:41:39 -0700433 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700434 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
435 return kBadSampleRateError;
436 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000437 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700438
Peter Kasting69558702016-01-12 16:26:35 -0800439 const size_t num_in_channels = config.input_stream().num_channels();
440 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700441
442 // Need at least one input channel.
443 // Need either one output channel or as many outputs as there are inputs.
444 if (num_in_channels == 0 ||
445 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700446 return kBadNumberChannelsError;
447 }
448
peahdf3efa82015-11-28 12:35:15 -0800449 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000450
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200451 // Choose maximum rate to use for the split filtering.
452 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
453 config_.pipeline.maximum_internal_processing_rate == 32000);
454 int max_splitting_rate = 48000;
455 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
456 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
457 }
458
Per Åhgrenc8626b62019-08-23 15:49:51 +0200459 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700460 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700461 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200462 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700463 submodule_states_.CaptureMultiBandSubModulesActive() ||
464 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200465 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000466
peahde65ddc2016-09-16 15:02:15 -0700467 capture_nonlocked_.capture_processing_format =
468 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700469
peah2ce640f2017-04-07 03:57:48 -0700470 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200471 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200472 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700473 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
474 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200475 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700476 submodule_states_.CaptureMultiBandSubModulesActive() ||
477 submodule_states_.RenderMultiBandSubModulesActive());
478 } else {
479 render_processing_rate = capture_processing_rate;
480 }
481
peahde65ddc2016-09-16 15:02:15 -0700482 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700483 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700484 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
485 kSampleRate8kHz) {
486 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000487 } else {
peahde65ddc2016-09-16 15:02:15 -0700488 render_processing_rate =
489 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000490 }
491
Per Åhgrenc8626b62019-08-23 15:49:51 +0200492 RTC_DCHECK_NE(8000, render_processing_rate);
493
peahce4d9152017-05-19 01:28:05 -0700494 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200495 // By default, downmix the render stream to mono for analysis. This has been
496 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100497 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
498 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200499 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100500 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200501 ? formats_.api_format.reverse_input_stream().num_channels()
502 : 1;
503 formats_.render_processing_format =
504 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700505 } else {
506 formats_.render_processing_format = StreamConfig(
507 formats_.api_format.reverse_input_stream().sample_rate_hz(),
508 formats_.api_format.reverse_input_stream().num_channels());
509 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000510
peahde65ddc2016-09-16 15:02:15 -0700511 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
512 kSampleRate32kHz ||
513 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
514 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800515 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000516 } else {
peahdf3efa82015-11-28 12:35:15 -0800517 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700518 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000519 }
520
521 return InitializeLocked();
522}
523
peah88ac8532016-09-12 16:47:25 -0700524void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200525 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
526
peah88ac8532016-09-12 16:47:25 -0700527 // Run in a single-threaded manner when applying the settings.
528 rtc::CritScope cs_render(&crit_render_);
529 rtc::CritScope cs_capture(&crit_capture_);
530
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200531 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100532 config_.pipeline.multi_channel_render !=
533 config.pipeline.multi_channel_render ||
534 config_.pipeline.multi_channel_capture !=
Per Åhgrenc0424252019-12-10 13:04:15 +0100535 config.pipeline.multi_channel_capture ||
536 config_.pipeline.maximum_internal_processing_rate !=
537 config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200538
Per Åhgren200feba2019-03-06 04:16:46 +0100539 const bool aec_config_changed =
540 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100541 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100542
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100543 const bool agc1_config_changed =
544 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
545 config_.gain_controller1.mode != config.gain_controller1.mode ||
546 config_.gain_controller1.target_level_dbfs !=
547 config.gain_controller1.target_level_dbfs ||
548 config_.gain_controller1.compression_gain_db !=
549 config.gain_controller1.compression_gain_db ||
550 config_.gain_controller1.enable_limiter !=
551 config.gain_controller1.enable_limiter ||
552 config_.gain_controller1.analog_level_minimum !=
553 config.gain_controller1.analog_level_minimum ||
554 config_.gain_controller1.analog_level_maximum !=
Per Åhgren0695df12020-01-13 14:43:13 +0100555 config.gain_controller1.analog_level_maximum ||
556 config_.gain_controller1.analog_gain_controller.enabled !=
557 config.gain_controller1.analog_gain_controller.enabled ||
558 config_.gain_controller1.analog_gain_controller.startup_min_volume !=
559 config.gain_controller1.analog_gain_controller.startup_min_volume ||
560 config_.gain_controller1.analog_gain_controller.clipped_level_min !=
561 config.gain_controller1.analog_gain_controller.clipped_level_min ||
562 config_.gain_controller1.analog_gain_controller
563 .enable_agc2_level_estimator !=
564 config.gain_controller1.analog_gain_controller
565 .enable_agc2_level_estimator ||
566 config_.gain_controller1.analog_gain_controller.enable_digital_adaptive !=
567 config.gain_controller1.analog_gain_controller
568 .enable_digital_adaptive;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100569
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100570 const bool agc2_config_changed =
571 config_.gain_controller2.enabled != config.gain_controller2.enabled;
572
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200573 const bool voice_detection_config_changed =
574 config_.voice_detection.enabled != config.voice_detection.enabled;
575
saza0bad15f2019-10-16 11:46:11 +0200576 const bool ns_config_changed =
577 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
578 config_.noise_suppression.level != config.noise_suppression.level;
579
Per Åhgrenc0734712020-01-02 15:15:36 +0100580 const bool ts_config_changed = config_.transient_suppression.enabled !=
581 config.transient_suppression.enabled;
582
Per Åhgren0f14db22020-01-03 14:27:14 +0100583 const bool pre_amplifier_config_changed =
584 config_.pre_amplifier.enabled != config.pre_amplifier.enabled ||
585 config_.pre_amplifier.fixed_gain_factor !=
586 config.pre_amplifier.fixed_gain_factor;
587
Yves Gerey499bc6c2018-10-10 18:29:07 +0200588 config_ = config;
589
Per Åhgren200feba2019-03-06 04:16:46 +0100590 if (aec_config_changed) {
591 InitializeEchoController();
592 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200593
saza0bad15f2019-10-16 11:46:11 +0200594 if (ns_config_changed) {
595 InitializeNoiseSuppressor();
596 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100597
Per Åhgrenc0734712020-01-02 15:15:36 +0100598 if (ts_config_changed) {
599 InitializeTransientSuppressor();
600 }
601
Per Åhgren0f14db22020-01-03 14:27:14 +0100602 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800603
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100604 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100605 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100606 }
607
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100608 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700609 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100610 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
611 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100612 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100613 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700614 config_.gain_controller2 = AudioProcessing::Config::GainController2();
615 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100616
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100617 if (agc2_config_changed) {
618 InitializeGainController2();
619 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100620
621 if (pre_amplifier_config_changed) {
622 InitializePreAmplifier();
623 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100624
saza1d600522019-10-18 13:29:43 +0200625 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
626 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100627 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100628
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200629 if (voice_detection_config_changed) {
630 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100631 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200632
633 // Reinitialization must happen after all submodule configuration to avoid
634 // additional reinitializations on the next capture / render processing call.
635 if (pipeline_config_changed) {
636 InitializeLocked(formats_.api_format);
637 }
peah88ac8532016-09-12 16:47:25 -0700638}
639
Per Åhgrenc0734712020-01-02 15:15:36 +0100640// TODO(webrtc:5298): Remove.
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100641void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {}
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000642
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000643int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800644 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700645 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000646}
647
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200648int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
649 return capture_.capture_fullband_audio
650 ? capture_.capture_fullband_audio->num_frames() * 100
651 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
652}
653
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000654int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800655 // Used as callback from submodules, hence locking is not allowed.
656 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000657}
658
Peter Kasting69558702016-01-12 16:26:35 -0800659size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800660 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700661 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000662}
663
Peter Kasting69558702016-01-12 16:26:35 -0800664size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800665 // Used as callback from submodules, hence locking is not allowed.
666 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000667}
668
Peter Kasting69558702016-01-12 16:26:35 -0800669size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800670 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100671 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
672 constants_.multi_channel_capture_support;
673 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200674 return 1;
675 }
676 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800677}
678
Peter Kasting69558702016-01-12 16:26:35 -0800679size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800680 // Used as callback from submodules, hence locking is not allowed.
681 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000682}
683
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000684void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800685 rtc::CritScope cs(&crit_capture_);
686 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200687 if (submodules_.agc_manager.get()) {
688 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000689 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000690}
691
Alessio Bazzicac054e782018-04-16 12:10:09 +0200692void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200693 switch (setting.type()) {
694 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100695 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200696 render_runtime_settings_enqueuer_.Enqueue(setting);
697 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200698 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100699 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200700 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100701 capture_runtime_settings_enqueuer_.Enqueue(setting);
702 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200703 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200704 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100705 render_runtime_settings_enqueuer_.Enqueue(setting);
706 return;
707 case RuntimeSetting::Type::kNotSpecified:
708 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200709 return;
710 }
711 // The language allows the enum to have a non-enumerator
712 // value. Check that this doesn't happen.
713 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200714}
715
716AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
717 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200718 : runtime_settings_(*runtime_settings) {
719 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200720}
721
722AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
723 default;
724
725void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
726 RuntimeSetting setting) {
727 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200728 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200729 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200730 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200731 RTC_LOG(LS_ERROR)
732 << "The runtime settings queue is full. Oldest setting discarded.";
733 }
734 if (remaining_attempts == 0)
735 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
736}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000737
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100738int AudioProcessingImpl::MaybeInitializeCapture(
739 const StreamConfig& input_config,
740 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -0800741 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700742 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800743 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100744 // Acquire the capture lock in order to access api_format. The lock is
745 // released immediately, as we may need to acquire the render lock as part
746 // of the conditional reinitialization.
peahdf3efa82015-11-28 12:35:15 -0800747 rtc::CritScope cs_capture(&crit_capture_);
peahdf3efa82015-11-28 12:35:15 -0800748 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700749 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000750 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000751
Oskar Sundbom4b276482019-05-23 14:28:00 +0200752 if (processing_config.input_stream() != input_config) {
753 processing_config.input_stream() = input_config;
754 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800755 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200756
757 if (processing_config.output_stream() != output_config) {
758 processing_config.output_stream() = output_config;
759 reinitialization_required = true;
760 }
761
762 if (reinitialization_required) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200763 rtc::CritScope cs_render(&crit_render_);
764 rtc::CritScope cs_capture(&crit_capture_);
765 RETURN_ON_ERR(InitializeLocked(processing_config));
766 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100767 return kNoError;
768}
769
770int AudioProcessingImpl::ProcessStream(const float* const* src,
771 const StreamConfig& input_config,
772 const StreamConfig& output_config,
773 float* const* dest) {
774 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
775 if (!src || !dest) {
776 return kNullPointerError;
777 }
778
779 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +0200780
peahdf3efa82015-11-28 12:35:15 -0800781 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000782
aleloi868f32f2017-05-23 07:20:05 -0700783 if (aec_dump_) {
784 RecordUnprocessedCaptureStream(src);
785 }
786
Per Åhgrena1351272019-08-15 12:15:46 +0200787 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800788 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200789 if (capture_.capture_fullband_audio) {
790 capture_.capture_fullband_audio->CopyFrom(
791 src, formats_.api_format.input_stream());
792 }
peahde65ddc2016-09-16 15:02:15 -0700793 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200794 if (capture_.capture_fullband_audio) {
795 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
796 dest);
797 } else {
798 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
799 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000800
aleloi868f32f2017-05-23 07:20:05 -0700801 if (aec_dump_) {
802 RecordProcessedCaptureStream(dest);
803 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000804 return kNoError;
805}
806
Alex Loiko73ec0192018-05-15 10:52:28 +0200807void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200808 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200809 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200810 if (aec_dump_) {
811 aec_dump_->WriteRuntimeSetting(setting);
812 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200813 switch (setting.type()) {
814 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200815 if (config_.pre_amplifier.enabled) {
816 float value;
817 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200818 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200819 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200820 }
821 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200822 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100823 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100824 if (!submodules_.agc_manager) {
825 float value;
826 setting.GetFloat(&value);
827 int int_value = static_cast<int>(value + .5f);
828 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +0100829 if (submodules_.gain_control) {
830 int error =
831 submodules_.gain_control->set_compression_gain_db(int_value);
832 RTC_DCHECK_EQ(kNoError, error);
833 }
Per Åhgren0e3198e2019-11-18 08:52:22 +0100834 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100835 break;
836 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200837 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100838 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200839 float value;
840 setting.GetFloat(&value);
841 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200842 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200843 }
844 break;
845 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200846 case RuntimeSetting::Type::kPlayoutVolumeChange: {
847 int value;
848 setting.GetInt(&value);
849 capture_.playout_volume = value;
850 break;
851 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100852 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
853 RTC_NOTREACHED();
854 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200855 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
856 RTC_NOTREACHED();
857 break;
858 case RuntimeSetting::Type::kNotSpecified:
859 RTC_NOTREACHED();
860 break;
861 }
862 }
863}
864
865void AudioProcessingImpl::HandleRenderRuntimeSettings() {
866 RuntimeSetting setting;
867 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200868 if (aec_dump_) {
869 aec_dump_->WriteRuntimeSetting(setting);
870 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200871 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100872 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100873 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200874 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200875 if (submodules_.render_pre_processor) {
876 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200877 }
878 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100879 case RuntimeSetting::Type::kCapturePreGain: // fall-through
880 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200881 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200882 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200883 RTC_NOTREACHED();
884 break;
885 }
886 }
887}
888
peah9e6a2902017-05-15 07:19:21 -0700889void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800890 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700891
saza1d600522019-10-18 13:29:43 +0200892 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200893 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
894 num_reverse_channels(),
895 &aecm_render_queue_buffer_);
896 RTC_DCHECK(aecm_render_signal_queue_);
897 // Insert the samples into the queue.
898 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
899 // The data queue is full and needs to be emptied.
900 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -0700901
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200902 // Retry the insert (should always work).
903 bool result =
904 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
905 RTC_DCHECK(result);
906 }
peah764e3642016-10-22 05:04:30 -0700907 }
peah701d6282016-10-25 05:42:20 -0700908
Per Åhgren0695df12020-01-13 14:43:13 +0100909 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +0100910 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -0700911 // Insert the samples into the queue.
912 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
913 // The data queue is full and needs to be emptied.
914 EmptyQueuedRenderAudio();
915
916 // Retry the insert (should always work).
917 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
918 RTC_DCHECK(result);
919 }
920 }
peah9e6a2902017-05-15 07:19:21 -0700921}
ivoc9f4a4a02016-10-28 05:39:16 -0700922
peah9e6a2902017-05-15 07:19:21 -0700923void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700924 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
925
926 // Insert the samples into the queue.
927 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
928 // The data queue is full and needs to be emptied.
929 EmptyQueuedRenderAudio();
930
931 // Retry the insert (should always work).
932 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
933 RTC_DCHECK(result);
934 }
peah764e3642016-10-22 05:04:30 -0700935}
936
937void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700938 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700939 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700940
ivoc9f4a4a02016-10-28 05:39:16 -0700941 const size_t new_red_render_queue_element_max_size =
942 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
943
peaha0624602016-10-25 04:45:24 -0700944 // Reallocate the queues if the queue item sizes are too small to fit the
945 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700946
947 if (agc_render_queue_element_max_size_ <
948 new_agc_render_queue_element_max_size) {
949 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
950
951 std::vector<int16_t> template_queue_element(
952 agc_render_queue_element_max_size_);
953
954 agc_render_signal_queue_.reset(
955 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
956 kMaxNumFramesToBuffer, template_queue_element,
957 RenderQueueItemVerifier<int16_t>(
958 agc_render_queue_element_max_size_)));
959
960 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
961 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
962 } else {
963 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700964 }
ivoc9f4a4a02016-10-28 05:39:16 -0700965
966 if (red_render_queue_element_max_size_ <
967 new_red_render_queue_element_max_size) {
968 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
969
970 std::vector<float> template_queue_element(
971 red_render_queue_element_max_size_);
972
973 red_render_signal_queue_.reset(
974 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
975 kMaxNumFramesToBuffer, template_queue_element,
976 RenderQueueItemVerifier<float>(
977 red_render_queue_element_max_size_)));
978
979 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
980 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
981 } else {
982 red_render_signal_queue_->Clear();
983 }
peah764e3642016-10-22 05:04:30 -0700984}
985
986void AudioProcessingImpl::EmptyQueuedRenderAudio() {
987 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +0200988 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200989 RTC_DCHECK(aecm_render_signal_queue_);
990 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +0200991 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200992 aecm_capture_queue_buffer_);
993 }
peah701d6282016-10-25 05:42:20 -0700994 }
995
Per Åhgren0695df12020-01-13 14:43:13 +0100996 if (submodules_.gain_control) {
997 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
998 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
999 }
peah764e3642016-10-22 05:04:30 -07001000 }
ivoc9f4a4a02016-10-28 05:39:16 -07001001
1002 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001003 RTC_DCHECK(submodules_.echo_detector);
1004 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001005 }
peah764e3642016-10-22 05:04:30 -07001006}
1007
Per Åhgren645f24c2020-03-16 12:06:02 +01001008int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1009 const StreamConfig& input_config,
1010 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001011 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001012 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001013 RETURN_ON_ERR(MaybeInitializeCapture(input_config, output_config));
Oskar Sundbom4b276482019-05-23 14:28:00 +02001014
peahdf3efa82015-11-28 12:35:15 -08001015 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001016
aleloi868f32f2017-05-23 07:20:05 -07001017 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001018 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001019 }
1020
Per Åhgren645f24c2020-03-16 12:06:02 +01001021 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001022 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001023 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001024 }
peahde65ddc2016-09-16 15:02:15 -07001025 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001026 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001027 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001028 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001029 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001030 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001031 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001032 }
Per Åhgrena1351272019-08-15 12:15:46 +02001033 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001034
aleloi868f32f2017-05-23 07:20:05 -07001035 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001036 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001037 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001038
1039 return kNoError;
1040}
1041
peahde65ddc2016-09-16 15:02:15 -07001042int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001043 EmptyQueuedRenderAudio();
Alex Loiko73ec0192018-05-15 10:52:28 +02001044 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001045
peahb58a1582016-03-15 09:34:24 -07001046 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001047 // TODO(peah): Simplify once the public API Enable functions for these
1048 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001049 RTC_DCHECK_LE(
1050 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001051
peahde65ddc2016-09-16 15:02:15 -07001052 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001053 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001054
Per Åhgrenc0424252019-12-10 13:04:15 +01001055 if (submodules_.high_pass_filter &&
1056 config_.high_pass_filter.apply_in_full_band &&
1057 !constants_.enforce_split_band_hpf) {
1058 submodules_.high_pass_filter->Process(capture_buffer,
1059 /*use_split_band_data=*/false);
1060 }
1061
saza1d600522019-10-18 13:29:43 +02001062 if (submodules_.pre_amplifier) {
1063 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001064 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001065 capture_buffer->num_frames()));
1066 }
1067
Per Åhgren928146f2019-08-20 09:19:21 +02001068 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001069 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001070 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001071 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1072 if (log_rms) {
1073 capture_rms_interval_counter_ = 0;
1074 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001075 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1076 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1077 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1078 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001079 }
1080
saza1d600522019-10-18 13:29:43 +02001081 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001082 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001083 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001084 capture_.echo_path_gain_change =
1085 capture_.prev_analog_mic_level != analog_mic_level &&
1086 capture_.prev_analog_mic_level != -1;
1087 capture_.prev_analog_mic_level = analog_mic_level;
1088
Per Åhgrend2650d12018-10-02 17:00:59 +02001089 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001090 if (submodules_.pre_amplifier) {
1091 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001092 capture_.echo_path_gain_change =
1093 capture_.echo_path_gain_change ||
1094 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001095 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001096 capture_.prev_pre_amp_gain = pre_amp_gain;
1097 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001098
1099 // Detect volume change.
1100 capture_.echo_path_gain_change =
1101 capture_.echo_path_gain_change ||
1102 (capture_.prev_playout_volume != capture_.playout_volume &&
1103 capture_.prev_playout_volume >= 0);
1104 capture_.prev_playout_volume = capture_.playout_volume;
1105
saza1d600522019-10-18 13:29:43 +02001106 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001107 }
1108
Per Åhgren0695df12020-01-13 14:43:13 +01001109 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001110 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001111 }
1112
peah2ace3f92016-09-10 04:42:27 -07001113 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1114 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001115 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1116 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001117 }
1118
Per Åhgrene14cb992019-11-27 09:34:22 +01001119 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1120 constants_.multi_channel_capture_support;
1121 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001122 // Force down-mixing of the number of channels after the detection of
1123 // capture signal saturation.
1124 // TODO(peah): Look into ensuring that this kind of tampering with the
1125 // AudioBuffer functionality should not be needed.
1126 capture_buffer->set_num_channels(1);
1127 }
1128
Per Åhgrenc0424252019-12-10 13:04:15 +01001129 if (submodules_.high_pass_filter &&
1130 (!config_.high_pass_filter.apply_in_full_band ||
1131 constants_.enforce_split_band_hpf)) {
1132 submodules_.high_pass_filter->Process(capture_buffer,
1133 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001134 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001135
Per Åhgren0695df12020-01-13 14:43:13 +01001136 if (submodules_.gain_control) {
1137 RETURN_ON_ERR(
1138 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1139 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001140
Per Åhgren8ad9e742020-01-30 07:40:58 +01001141 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1142 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1143 submodules_.noise_suppressor) {
1144 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001145 }
peahb58a1582016-03-15 09:34:24 -07001146
saza1d600522019-10-18 13:29:43 +02001147 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001148 // Ensure that the stream delay was set before the call to the
1149 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001150 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001151 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001152 }
1153
saza1d600522019-10-18 13:29:43 +02001154 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001155 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001156 }
peahe0eae3c2016-12-14 01:16:23 -08001157
saza1d600522019-10-18 13:29:43 +02001158 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001159 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001160 } else {
saza1d600522019-10-18 13:29:43 +02001161 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001162 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1163
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001164 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001165 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001166 }
1167
saza1d600522019-10-18 13:29:43 +02001168 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001169 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001170 }
1171
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001172 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001173 linear_aec_buffer && submodules_.noise_suppressor) {
1174 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001175 }
1176
saza1d600522019-10-18 13:29:43 +02001177 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001178 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001179 }
Per Åhgren46537a32017-06-07 10:08:10 +02001180 }
ivoc9f4a4a02016-10-28 05:39:16 -07001181
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001182 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001183 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001184 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001185 } else {
1186 capture_.stats.voice_detected = absl::nullopt;
1187 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001188
Per Åhgren0695df12020-01-13 14:43:13 +01001189 if (submodules_.agc_manager) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001190 submodules_.agc_manager->Process(capture_buffer);
1191
1192 absl::optional<int> new_digital_gain =
1193 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001194 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001195 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1196 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001197 }
Per Åhgren0695df12020-01-13 14:43:13 +01001198
1199 if (submodules_.gain_control) {
1200 // TODO(peah): Add reporting from AEC3 whether there is echo.
1201 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1202 capture_buffer, /*stream_has_echo*/ false));
1203 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001204
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001205 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001206 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001207 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1208 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001209 }
1210
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001211 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001212 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001213 bool ec_active = ec ? ec->ActiveProcessing() : false;
1214 // Only update the fullband buffer if the multiband processing has changed
1215 // the signal. Keep the original signal otherwise.
1216 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1217 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1218 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001219 capture_buffer = capture_.capture_fullband_audio.get();
1220 }
1221
peah9e6a2902017-05-15 07:19:21 -07001222 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001223 RTC_DCHECK(submodules_.echo_detector);
1224 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1225 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001226 }
1227
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001228 // TODO(aluebs): Investigate if the transient suppression placement should be
1229 // before or after the AGC.
Per Åhgrenc0734712020-01-02 15:15:36 +01001230 if (submodules_.transient_suppressor) {
saza1d600522019-10-18 13:29:43 +02001231 float voice_probability = submodules_.agc_manager.get()
1232 ? submodules_.agc_manager->voice_probability()
1233 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001234
saza1d600522019-10-18 13:29:43 +02001235 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001236 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001237 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001238 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001239 capture_buffer->num_frames_per_band(),
1240 capture_.keyboard_info.keyboard_data,
1241 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001242 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001243 }
1244
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001245 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001246 if (submodules_.capture_analyzer) {
1247 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001248 }
1249
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001250 if (submodules_.gain_controller2) {
saza1d600522019-10-18 13:29:43 +02001251 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001252 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001253 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001254 }
1255
saza1d600522019-10-18 13:29:43 +02001256 if (submodules_.capture_post_processor) {
1257 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001258 }
1259
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001260 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001261 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001262 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1263 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001264 } else {
1265 capture_.stats.output_rms_dbfs = absl::nullopt;
1266 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001267
Per Åhgren928146f2019-08-20 09:19:21 +02001268 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001269 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001270 capture_nonlocked_.capture_processing_format.num_frames()));
1271 if (log_rms) {
1272 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1273 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1274 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1275 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1276 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1277 }
1278
Per Åhgren0e3198e2019-11-18 08:52:22 +01001279 if (submodules_.agc_manager) {
1280 int level = recommended_stream_analog_level();
1281 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1282 &level);
1283 }
1284
Per Åhgrencf4c8722019-12-30 14:32:14 +01001285 // Compute echo-related stats.
1286 if (submodules_.echo_controller) {
1287 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1288 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1289 capture_.stats.echo_return_loss_enhancement =
1290 ec_metrics.echo_return_loss_enhancement;
1291 capture_.stats.delay_ms = ec_metrics.delay_ms;
1292 }
1293 if (config_.residual_echo_detector.enabled) {
1294 RTC_DCHECK(submodules_.echo_detector);
1295 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1296 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1297 capture_.stats.residual_echo_likelihood_recent_max =
1298 ed_metrics.echo_likelihood_recent_max;
1299 }
1300
1301 // Pass stats for reporting.
1302 stats_reporter_.UpdateStatistics(capture_.stats);
1303
peahdf3efa82015-11-28 12:35:15 -08001304 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001305 return kNoError;
1306}
1307
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001308int AudioProcessingImpl::AnalyzeReverseStream(
1309 const float* const* data,
1310 const StreamConfig& reverse_config) {
1311 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1312 rtc::CritScope cs(&crit_render_);
1313 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1314}
1315
peahde65ddc2016-09-16 15:02:15 -07001316int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1317 const StreamConfig& input_config,
1318 const StreamConfig& output_config,
1319 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001320 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001321 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001322 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001323 if (submodule_states_.RenderMultiBandProcessingActive() ||
1324 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001325 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1326 dest);
peah2ace3f92016-09-10 04:42:27 -07001327 } else if (formats_.api_format.reverse_input_stream() !=
1328 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001329 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1330 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001331 } else {
peahde65ddc2016-09-16 15:02:15 -07001332 CopyAudioIfNeeded(src, input_config.num_frames(),
1333 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001334 }
1335
1336 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001337}
1338
peahdf3efa82015-11-28 12:35:15 -08001339int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001340 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001341 const StreamConfig& input_config,
1342 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001343 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001344 return kNullPointerError;
1345 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001346
peahde65ddc2016-09-16 15:02:15 -07001347 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001348 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001349 }
1350
peahdf3efa82015-11-28 12:35:15 -08001351 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001352 processing_config.reverse_input_stream() = input_config;
1353 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001354
peahdf3efa82015-11-28 12:35:15 -08001355 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001356 RTC_DCHECK_EQ(input_config.num_frames(),
1357 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001358
aleloi868f32f2017-05-23 07:20:05 -07001359 if (aec_dump_) {
1360 const size_t channel_size =
1361 formats_.api_format.reverse_input_stream().num_frames();
1362 const size_t num_channels =
1363 formats_.api_format.reverse_input_stream().num_channels();
1364 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001365 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001366 }
peahdf3efa82015-11-28 12:35:15 -08001367 render_.render_audio->CopyFrom(src,
1368 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001369 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001370}
1371
Per Åhgren645f24c2020-03-16 12:06:02 +01001372int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1373 const StreamConfig& input_config,
1374 const StreamConfig& output_config,
1375 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001376 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001377
1378 if (input_config.num_channels() <= 0) {
1379 return AudioProcessing::Error::kBadNumberChannelsError;
1380 }
1381
Per Åhgren645f24c2020-03-16 12:06:02 +01001382 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001383 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001384 processing_config.reverse_input_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001385 input_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001386 processing_config.reverse_input_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001387 input_config.num_channels());
ekmeyerson60d9b332015-08-14 10:35:55 -07001388 processing_config.reverse_output_stream().set_sample_rate_hz(
Per Åhgren645f24c2020-03-16 12:06:02 +01001389 output_config.sample_rate_hz());
ekmeyerson60d9b332015-08-14 10:35:55 -07001390 processing_config.reverse_output_stream().set_num_channels(
Per Åhgren645f24c2020-03-16 12:06:02 +01001391 output_config.num_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001392
peahdf3efa82015-11-28 12:35:15 -08001393 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Per Åhgren645f24c2020-03-16 12:06:02 +01001394 if (input_config.num_frames() !=
peahdf3efa82015-11-28 12:35:15 -08001395 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001396 return kBadDataLengthError;
1397 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001398
aleloi868f32f2017-05-23 07:20:05 -07001399 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001400 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1401 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001402 }
1403
Per Åhgren645f24c2020-03-16 12:06:02 +01001404 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001405 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001406 if (submodule_states_.RenderMultiBandProcessingActive() ||
1407 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001408 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001409 }
aluebsb0319552016-03-17 20:39:53 -07001410 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001411}
niklase@google.com470e71d2011-07-07 08:21:25 +00001412
peahde65ddc2016-09-16 15:02:15 -07001413int AudioProcessingImpl::ProcessRenderStreamLocked() {
1414 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001415
Alex Loiko73ec0192018-05-15 10:52:28 +02001416 HandleRenderRuntimeSettings();
1417
saza1d600522019-10-18 13:29:43 +02001418 if (submodules_.render_pre_processor) {
1419 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001420 }
1421
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001422 QueueNonbandedRenderAudio(render_buffer);
1423
peah2ace3f92016-09-10 04:42:27 -07001424 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001425 SampleRateSupportsMultiBand(
1426 formats_.render_processing_format.sample_rate_hz())) {
1427 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001428 }
1429
peahce4d9152017-05-19 01:28:05 -07001430 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1431 QueueBandedRenderAudio(render_buffer);
1432 }
1433
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001434 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001435 if (submodules_.echo_controller) {
1436 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001437 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001438
peah2ace3f92016-09-10 04:42:27 -07001439 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001440 SampleRateSupportsMultiBand(
1441 formats_.render_processing_format.sample_rate_hz())) {
1442 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001443 }
1444
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001445 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001446}
1447
1448int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001449 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001450 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001451 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001452
niklase@google.com470e71d2011-07-07 08:21:25 +00001453 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001454 delay = 0;
1455 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001456 }
1457
1458 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1459 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001460 delay = 500;
1461 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001462 }
1463
peahdf3efa82015-11-28 12:35:15 -08001464 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001465 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466}
1467
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001468bool AudioProcessingImpl::GetLinearAecOutput(
1469 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1470 rtc::CritScope cs(&crit_capture_);
1471 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1472
1473 RTC_DCHECK(linear_aec_buffer);
1474 if (linear_aec_buffer) {
1475 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1476 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1477
1478 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1479 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1480 rtc::ArrayView<const float> channel_view =
1481 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1482 linear_aec_buffer->num_frames());
1483 std::copy(channel_view.begin(), channel_view.end(),
1484 linear_output[ch].begin());
1485 }
1486 return true;
1487 }
1488 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1489 RTC_NOTREACHED();
1490 return false;
1491}
1492
niklase@google.com470e71d2011-07-07 08:21:25 +00001493int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001494 // Used as callback from submodules, hence locking is not allowed.
1495 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001496}
1497
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001498void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001499 rtc::CritScope cs(&crit_capture_);
1500 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001501}
1502
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001503void AudioProcessingImpl::set_stream_analog_level(int level) {
1504 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001505
1506 if (submodules_.agc_manager) {
1507 submodules_.agc_manager->set_stream_analog_level(level);
1508 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1509 1, &level);
Per Åhgren0695df12020-01-13 14:43:13 +01001510 } else if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001511 int error = submodules_.gain_control->set_stream_analog_level(level);
1512 RTC_DCHECK_EQ(kNoError, error);
Per Åhgren0695df12020-01-13 14:43:13 +01001513 } else {
1514 capture_.cached_stream_analog_level_ = level;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001515 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001516}
1517
1518int AudioProcessingImpl::recommended_stream_analog_level() const {
1519 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001520 if (submodules_.agc_manager) {
1521 return submodules_.agc_manager->stream_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01001522 } else if (submodules_.gain_control) {
1523 return submodules_.gain_control->stream_analog_level();
1524 } else {
1525 return capture_.cached_stream_analog_level_;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001526 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001527}
1528
aleloi868f32f2017-05-23 07:20:05 -07001529void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1530 RTC_DCHECK(aec_dump);
1531 rtc::CritScope cs_render(&crit_render_);
1532 rtc::CritScope cs_capture(&crit_capture_);
1533
1534 // The previously attached AecDump will be destroyed with the
1535 // 'aec_dump' parameter, which is after locks are released.
1536 aec_dump_.swap(aec_dump);
1537 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001538 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001539}
1540
1541void AudioProcessingImpl::DetachAecDump() {
1542 // The d-tor of a task-queue based AecDump blocks until all pending
1543 // tasks are done. This construction avoids blocking while holding
1544 // the render and capture locks.
1545 std::unique_ptr<AecDump> aec_dump = nullptr;
1546 {
1547 rtc::CritScope cs_render(&crit_render_);
1548 rtc::CritScope cs_capture(&crit_capture_);
1549 aec_dump = std::move(aec_dump_);
1550 }
1551}
1552
Sam Zackrisson4d364492018-03-02 16:03:21 +01001553void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1554 std::unique_ptr<AudioGenerator> audio_generator) {
1555 // TODO(bugs.webrtc.org/8882) Stub.
1556 // Reset internal audio generator with audio_generator.
1557}
1558
1559void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1560 // TODO(bugs.webrtc.org/8882) Stub.
1561 // Delete audio generator, if one is attached.
1562}
1563
peah8271d042016-11-22 07:24:52 -08001564void AudioProcessingImpl::MutateConfig(
1565 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1566 rtc::CritScope cs_render(&crit_render_);
1567 rtc::CritScope cs_capture(&crit_capture_);
1568 mutator(&config_);
1569 ApplyConfig(config_);
1570}
1571
1572AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1573 rtc::CritScope cs_render(&crit_render_);
1574 rtc::CritScope cs_capture(&crit_capture_);
1575 return config_;
1576}
1577
peah2ace3f92016-09-10 04:42:27 -07001578bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1579 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001580 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Per Åhgren8ad9e742020-01-30 07:40:58 +01001581 config_.residual_echo_detector.enabled, !!submodules_.noise_suppressor,
Per Åhgren0695df12020-01-13 14:43:13 +01001582 !!submodules_.gain_control, !!submodules_.gain_controller2,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001583 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
Per Åhgrenc0734712020-01-02 15:15:36 +01001584 config_.voice_detection.enabled, !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001585}
1586
Per Åhgrenc0734712020-01-02 15:15:36 +01001587void AudioProcessingImpl::InitializeTransientSuppressor() {
1588 if (config_.transient_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02001589 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01001590 if (!submodules_.transient_suppressor) {
sazaaa42ecd2020-04-01 15:24:40 +02001591 submodules_.transient_suppressor = CreateTransientSuppressor();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001592 }
sazaaa42ecd2020-04-01 15:24:40 +02001593 if (submodules_.transient_suppressor) {
1594 submodules_.transient_suppressor->Initialize(
1595 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1596 num_proc_channels());
1597 } else {
1598 RTC_LOG(LS_WARNING)
1599 << "No transient suppressor created (probably disabled)";
1600 }
Per Åhgrenc0734712020-01-02 15:15:36 +01001601 } else {
1602 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001603 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001604}
1605
Per Åhgren0f14db22020-01-03 14:27:14 +01001606void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01001607 bool high_pass_filter_needed_by_aec =
1608 config_.echo_canceller.enabled &&
1609 config_.echo_canceller.enforce_high_pass_filtering &&
1610 !config_.echo_canceller.mobile_mode;
1611 if (submodule_states_.HighPassFilteringRequired() ||
1612 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001613 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1614 !constants_.enforce_split_band_hpf;
1615 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1616 : proc_split_sample_rate_hz();
1617 size_t num_channels =
1618 use_full_band ? num_output_channels() : num_proc_channels();
1619
Per Åhgren0f14db22020-01-03 14:27:14 +01001620 if (!submodules_.high_pass_filter ||
1621 rate != submodules_.high_pass_filter->sample_rate_hz() ||
1622 forced_reset ||
1623 num_channels != submodules_.high_pass_filter->num_channels()) {
1624 submodules_.high_pass_filter.reset(
1625 new HighPassFilter(rate, num_channels));
1626 }
peah8271d042016-11-22 07:24:52 -08001627 } else {
saza1d600522019-10-18 13:29:43 +02001628 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001629 }
1630}
alessiob3ec96df2017-05-22 06:57:06 -07001631
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001632void AudioProcessingImpl::InitializeVoiceDetector() {
1633 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001634 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001635 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1636 } else {
saza1d600522019-10-18 13:29:43 +02001637 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001638 }
1639}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001640void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001641 bool use_echo_controller =
1642 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001643 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001644
1645 if (use_echo_controller) {
1646 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001647 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001648 submodules_.echo_controller = echo_control_factory_->Create(
1649 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001650 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001651 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001652 EchoCanceller3Config config =
1653 use_setup_specific_default_aec3_config_
1654 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1655 num_proc_channels())
1656 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001657 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001658 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001659 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001660 }
1661
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001662 // Setup the storage for returning the linear AEC output.
1663 if (config_.echo_canceller.export_linear_aec_output) {
1664 constexpr int kLinearOutputRateHz = 16000;
1665 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1666 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1667 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1668 } else {
1669 capture_.linear_aec_output.reset();
1670 }
1671
Per Åhgren200feba2019-03-06 04:16:46 +01001672 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001673
saza1d600522019-10-18 13:29:43 +02001674 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001675 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001676 return;
peahe0eae3c2016-12-14 01:16:23 -08001677 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001678
saza1d600522019-10-18 13:29:43 +02001679 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001680 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001681 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001682
1683 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001684 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001685 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001686 return;
1687 }
1688
1689 if (config_.echo_canceller.mobile_mode) {
1690 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001691 size_t max_element_size =
1692 std::max(static_cast<size_t>(1),
1693 kMaxAllowedValuesOfSamplesPerBand *
1694 EchoControlMobileImpl::NumCancellersRequired(
1695 num_output_channels(), num_reverse_channels()));
1696
1697 std::vector<int16_t> template_queue_element(max_element_size);
1698
1699 aecm_render_signal_queue_.reset(
1700 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1701 kMaxNumFramesToBuffer, template_queue_element,
1702 RenderQueueItemVerifier<int16_t>(max_element_size)));
1703
1704 aecm_render_queue_buffer_.resize(max_element_size);
1705 aecm_capture_queue_buffer_.resize(max_element_size);
1706
saza1d600522019-10-18 13:29:43 +02001707 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001708
saza1d600522019-10-18 13:29:43 +02001709 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1710 num_reverse_channels(),
1711 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001712 return;
1713 }
1714
saza1d600522019-10-18 13:29:43 +02001715 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001716 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001717}
peah8271d042016-11-22 07:24:52 -08001718
Per Åhgren0695df12020-01-13 14:43:13 +01001719void AudioProcessingImpl::InitializeGainController1() {
1720 if (!config_.gain_controller1.enabled) {
1721 submodules_.agc_manager.reset();
1722 submodules_.gain_control.reset();
1723 return;
1724 }
1725
1726 if (!submodules_.gain_control) {
1727 submodules_.gain_control.reset(new GainControlImpl());
1728 }
1729
1730 submodules_.gain_control->Initialize(num_proc_channels(),
1731 proc_sample_rate_hz());
1732
1733 if (!config_.gain_controller1.analog_gain_controller.enabled) {
1734 int error = submodules_.gain_control->set_mode(
1735 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
1736 RTC_DCHECK_EQ(kNoError, error);
1737 error = submodules_.gain_control->set_target_level_dbfs(
1738 config_.gain_controller1.target_level_dbfs);
1739 RTC_DCHECK_EQ(kNoError, error);
1740 error = submodules_.gain_control->set_compression_gain_db(
1741 config_.gain_controller1.compression_gain_db);
1742 RTC_DCHECK_EQ(kNoError, error);
1743 error = submodules_.gain_control->enable_limiter(
1744 config_.gain_controller1.enable_limiter);
1745 RTC_DCHECK_EQ(kNoError, error);
1746 error = submodules_.gain_control->set_analog_level_limits(
1747 config_.gain_controller1.analog_level_minimum,
1748 config_.gain_controller1.analog_level_maximum);
1749 RTC_DCHECK_EQ(kNoError, error);
1750
1751 submodules_.agc_manager.reset();
1752 return;
1753 }
1754
1755 if (!submodules_.agc_manager.get() ||
1756 submodules_.agc_manager->num_channels() !=
1757 static_cast<int>(num_proc_channels()) ||
1758 submodules_.agc_manager->sample_rate_hz() !=
1759 capture_nonlocked_.split_rate) {
1760 int stream_analog_level = -1;
1761 const bool re_creation = !!submodules_.agc_manager;
1762 if (re_creation) {
1763 stream_analog_level = submodules_.agc_manager->stream_analog_level();
1764 }
1765 submodules_.agc_manager.reset(new AgcManagerDirect(
1766 num_proc_channels(),
1767 config_.gain_controller1.analog_gain_controller.startup_min_volume,
1768 config_.gain_controller1.analog_gain_controller.clipped_level_min,
1769 config_.gain_controller1.analog_gain_controller
1770 .enable_agc2_level_estimator,
1771 !config_.gain_controller1.analog_gain_controller
1772 .enable_digital_adaptive,
1773 capture_nonlocked_.split_rate));
1774 if (re_creation) {
1775 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
1776 }
1777 }
1778 submodules_.agc_manager->Initialize();
1779 submodules_.agc_manager->SetupDigitalGainControl(
1780 submodules_.gain_control.get());
1781 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
1782}
1783
alessiob3ec96df2017-05-22 06:57:06 -07001784void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001785 if (config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001786 if (!submodules_.gain_controller2) {
1787 // TODO(alessiob): Move the injected gain controller once injection is
1788 // implemented.
1789 submodules_.gain_controller2.reset(new GainController2());
1790 }
1791
saza1d600522019-10-18 13:29:43 +02001792 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001793 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
1794 } else {
1795 submodules_.gain_controller2.reset();
alessiob3ec96df2017-05-22 06:57:06 -07001796 }
1797}
1798
saza0bad15f2019-10-16 11:46:11 +02001799void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001800 submodules_.noise_suppressor.reset();
1801
saza0bad15f2019-10-16 11:46:11 +02001802 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02001803 auto map_level =
1804 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1805 using NoiseSuppresionConfig =
1806 AudioProcessing::Config::NoiseSuppression;
1807 switch (level) {
1808 case NoiseSuppresionConfig::kLow:
1809 return NsConfig::SuppressionLevel::k6dB;
1810 case NoiseSuppresionConfig::kModerate:
1811 return NsConfig::SuppressionLevel::k12dB;
1812 case NoiseSuppresionConfig::kHigh:
1813 return NsConfig::SuppressionLevel::k18dB;
1814 case NoiseSuppresionConfig::kVeryHigh:
1815 return NsConfig::SuppressionLevel::k21dB;
1816 default:
1817 RTC_NOTREACHED();
1818 }
1819 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001820
sazaaa42ecd2020-04-01 15:24:40 +02001821 NsConfig cfg;
1822 cfg.target_level = map_level(config_.noise_suppression.level);
1823 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1824 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02001825 }
1826}
1827
Alex Loikob5c9a792018-04-16 16:31:22 +02001828void AudioProcessingImpl::InitializePreAmplifier() {
1829 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001830 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001831 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1832 } else {
saza1d600522019-10-18 13:29:43 +02001833 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001834 }
1835}
1836
ivoc9f4a4a02016-10-28 05:39:16 -07001837void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001838 RTC_DCHECK(submodules_.echo_detector);
1839 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001840 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001841 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001842}
1843
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001844void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001845 if (submodules_.capture_analyzer) {
1846 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1847 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001848 }
1849}
1850
Sam Zackrisson0beac582017-09-25 12:04:02 +02001851void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001852 if (submodules_.capture_post_processor) {
1853 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001854 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001855 }
1856}
1857
Alex Loiko5825aa62017-12-18 16:02:40 +01001858void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001859 if (submodules_.render_pre_processor) {
1860 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001861 formats_.render_processing_format.sample_rate_hz(),
1862 formats_.render_processing_format.num_channels());
1863 }
1864}
1865
aleloi868f32f2017-05-23 07:20:05 -07001866void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1867 if (!aec_dump_) {
1868 return;
1869 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001870
1871 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07001872 // TODO(peah): Add semicolon-separated concatenations of experiment
1873 // descriptions for other submodules.
Per Åhgren0695df12020-01-13 14:43:13 +01001874 if (config_.gain_controller1.analog_gain_controller.clipped_level_min !=
1875 kClippedLevelMin) {
aleloi868f32f2017-05-23 07:20:05 -07001876 experiments_description += "AgcClippingLevelExperiment;";
1877 }
Sam Zackrisson701bd172020-02-18 14:50:28 +01001878 if (!!submodules_.capture_post_processor) {
1879 experiments_description += "CapturePostProcessor;";
1880 }
1881 if (!!submodules_.render_pre_processor) {
1882 experiments_description += "RenderPreProcessor;";
1883 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001884 if (capture_nonlocked_.echo_controller_enabled) {
1885 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001886 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001887 if (config_.gain_controller2.enabled) {
1888 experiments_description += "GainController2;";
1889 }
aleloi868f32f2017-05-23 07:20:05 -07001890
1891 InternalAPMConfig apm_config;
1892
Per Åhgren200feba2019-03-06 04:16:46 +01001893 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001894 apm_config.aec_delay_agnostic_enabled = false;
1895 apm_config.aec_extended_filter_enabled = false;
1896 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07001897
saza1d600522019-10-18 13:29:43 +02001898 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07001899 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02001900 submodules_.echo_control_mobile &&
1901 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001902 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02001903 submodules_.echo_control_mobile
1904 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001905 : 0;
aleloi868f32f2017-05-23 07:20:05 -07001906
Per Åhgren0695df12020-01-13 14:43:13 +01001907 apm_config.agc_enabled = !!submodules_.gain_control;
1908
1909 apm_config.agc_mode = submodules_.gain_control
1910 ? static_cast<int>(submodules_.gain_control->mode())
1911 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07001912 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01001913 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
1914 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001915 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07001916
1917 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1918
saza0bad15f2019-10-16 11:46:11 +02001919 apm_config.ns_enabled = config_.noise_suppression.enabled;
1920 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07001921
1922 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01001923 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07001924 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001925 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1926 apm_config.pre_amplifier_fixed_gain_factor =
1927 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001928
1929 if (!forced && apm_config == apm_config_for_aec_dump_) {
1930 return;
1931 }
1932 aec_dump_->WriteConfig(apm_config);
1933 apm_config_for_aec_dump_ = apm_config;
1934}
1935
1936void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1937 const float* const* src) {
1938 RTC_DCHECK(aec_dump_);
1939 WriteAecDumpConfigMessage(false);
1940
1941 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1942 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1943 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001944 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001945 RecordAudioProcessingState();
1946}
1947
1948void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01001949 const int16_t* const data,
1950 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07001951 RTC_DCHECK(aec_dump_);
1952 WriteAecDumpConfigMessage(false);
1953
Per Åhgren645f24c2020-03-16 12:06:02 +01001954 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
1955 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07001956 RecordAudioProcessingState();
1957}
1958
1959void AudioProcessingImpl::RecordProcessedCaptureStream(
1960 const float* const* processed_capture_stream) {
1961 RTC_DCHECK(aec_dump_);
1962
1963 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1964 const size_t num_channels =
1965 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001966 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1967 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001968 aec_dump_->WriteCaptureStreamMessage();
1969}
1970
1971void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01001972 const int16_t* const data,
1973 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07001974 RTC_DCHECK(aec_dump_);
1975
Per Åhgren645f24c2020-03-16 12:06:02 +01001976 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01001977 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07001978 aec_dump_->WriteCaptureStreamMessage();
1979}
1980
1981void AudioProcessingImpl::RecordAudioProcessingState() {
1982 RTC_DCHECK(aec_dump_);
1983 AecDump::AudioProcessingState audio_proc_state;
1984 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001985 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001986 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07001987 audio_proc_state.keypress = capture_.key_pressed;
1988 aec_dump_->AddAudioProcessingState(audio_proc_state);
1989}
1990
Per Åhgrenc0734712020-01-02 15:15:36 +01001991AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001992 : was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07001993 output_will_be_muted(false),
1994 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07001995 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001996 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02001997 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02001998 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001999 prev_pre_amp_gain(-1.f),
2000 playout_volume(-1),
2001 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002002
2003AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2004
Per Åhgrena1351272019-08-15 12:15:46 +02002005void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2006 const float* const* data,
2007 const StreamConfig& stream_config) {
2008 if (stream_config.has_keyboard()) {
2009 keyboard_data = data[stream_config.num_channels()];
2010 } else {
2011 keyboard_data = NULL;
2012 }
2013 num_keyboard_frames = stream_config.num_frames();
2014}
2015
kwiberg83ffe452016-08-29 14:46:07 -07002016AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2017
2018AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2019
Per Åhgrencf4c8722019-12-30 14:32:14 +01002020AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2021 : stats_message_queue_(1) {}
2022
2023AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2024
2025AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
2026 rtc::CritScope cs_stats(&crit_stats_);
2027 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2028 // If the message queue is full, return the cached stats.
2029 static_cast<void>(new_stats_available);
2030
2031 return cached_stats_;
2032}
2033
2034void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2035 const AudioProcessingStats& new_stats) {
2036 AudioProcessingStats stats_to_queue = new_stats;
2037 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2038 // If the message queue is full, discard the new stats.
2039 static_cast<void>(stats_message_passed);
2040}
2041
niklase@google.com470e71d2011-07-07 08:21:25 +00002042} // namespace webrtc