blob: 4d9cdb4d65aa465a093113946a99edbb67eda25d [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
alessiob3ec96df2017-05-22 06:57:06 -070016#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020017#include <type_traits>
18#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Yves Gerey988cc082018-10-23 12:03:01 +020020#include "absl/types/optional.h"
21#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/include/audio_util.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020024#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/common.h"
Yves Gerey988cc082018-10-23 12:03:01 +020027#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 21:42:56 +010028#include "modules/audio_processing/logging/apm_data_dumper.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/ref_counted_object.h"
34#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020036#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000038
Michael Graczyk86c6d332015-07-23 11:41:39 -070039#define RETURN_ON_ERR(expr) \
40 do { \
41 int err = (expr); \
42 if (err != kNoError) { \
43 return err; \
44 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000045 } while (0)
46
niklase@google.com470e71d2011-07-07 08:21:25 +000047namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070048
kwibergd59d3bb2016-09-13 07:49:33 -070049constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020050constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070051
Michael Graczyk86c6d332015-07-23 11:41:39 -070052namespace {
53
54static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
55 switch (layout) {
56 case AudioProcessing::kMono:
57 case AudioProcessing::kStereo:
58 return false;
59 case AudioProcessing::kMonoAndKeyboard:
60 case AudioProcessing::kStereoAndKeyboard:
61 return true;
62 }
63
kwiberg9e2be5f2016-09-14 05:23:22 -070064 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070065 return false;
66}
aluebsdf6416a2016-03-16 18:26:35 -070067
peah2ace3f92016-09-10 04:42:27 -070068bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070069 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
70 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
71}
72
Per Åhgren0cbb58e2019-10-29 22:59:44 +010073// Checks whether the legacy ns functionality should be enforced.
74bool DetectLegacyNsEnforcement() {
75 return field_trial::IsEnabled("WebRTC-NewNoiseSuppressionKillSwitch");
76}
77
Per Åhgrenb2b58d82019-12-02 14:59:40 +010078// Checks whether AEC3 should be allowed to decide what the default
79// configuration should be based on the render and capture channel configuration
80// at hand.
81bool UseSetupSpecificDefaultAec3Congfig() {
82 return !field_trial::IsEnabled(
83 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
84}
85
Per Åhgrenc8626b62019-08-23 15:49:51 +020086// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020087int SuitableProcessRate(int minimum_rate,
88 int max_splitting_rate,
89 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020090 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020091 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020092 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070093 if (rate >= uppermost_native_rate) {
94 return uppermost_native_rate;
95 }
96 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070097 return rate;
98 }
99 }
peah2ace3f92016-09-10 04:42:27 -0700100 RTC_NOTREACHED();
101 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700102}
103
Sam Zackrisson23513132019-01-11 15:10:32 +0100104NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
105 AudioProcessing::Config::NoiseSuppression::Level level) {
106 using NsConfig = AudioProcessing::Config::NoiseSuppression;
107 switch (level) {
108 case NsConfig::kLow:
saza0bad15f2019-10-16 11:46:11 +0200109 return NoiseSuppression::Level::kLow;
Sam Zackrisson23513132019-01-11 15:10:32 +0100110 case NsConfig::kModerate:
saza0bad15f2019-10-16 11:46:11 +0200111 return NoiseSuppression::Level::kModerate;
Sam Zackrisson23513132019-01-11 15:10:32 +0100112 case NsConfig::kHigh:
saza0bad15f2019-10-16 11:46:11 +0200113 return NoiseSuppression::Level::kHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100114 case NsConfig::kVeryHigh:
saza0bad15f2019-10-16 11:46:11 +0200115 return NoiseSuppression::Level::kVeryHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100116 default:
117 RTC_NOTREACHED();
118 }
119}
120
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100121GainControl::Mode Agc1ConfigModeToInterfaceMode(
122 AudioProcessing::Config::GainController1::Mode mode) {
123 using Agc1Config = AudioProcessing::Config::GainController1;
124 switch (mode) {
125 case Agc1Config::kAdaptiveAnalog:
126 return GainControl::kAdaptiveAnalog;
127 case Agc1Config::kAdaptiveDigital:
128 return GainControl::kAdaptiveDigital;
129 case Agc1Config::kFixedDigital:
130 return GainControl::kFixedDigital;
131 }
132}
133
peah9e6a2902017-05-15 07:19:21 -0700134// Maximum lengths that frame of samples being passed from the render side to
135// the capture side can have (does not apply to AEC3).
136static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
137static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
138
peah764e3642016-10-22 05:04:30 -0700139// Maximum number of frames to buffer in the render queue.
140// TODO(peah): Decrease this once we properly handle hugely unbalanced
141// reverse and forward call numbers.
142static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700143} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000144
145// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000146static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000147
saza1d600522019-10-18 13:29:43 +0200148AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100149 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200150 bool render_pre_processor_enabled,
151 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100152 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200153 render_pre_processor_enabled_(render_pre_processor_enabled),
154 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700155
saza1d600522019-10-18 13:29:43 +0200156bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200157 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700158 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700159 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700160 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700161 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700162 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200163 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200164 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200165 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool transient_suppressor_enabled) {
167 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200168 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700169 changed |=
170 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700171 changed |=
172 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700173 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
174 changed |=
peah2ace3f92016-09-10 04:42:27 -0700175 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200176 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200177 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200178 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200179 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700180 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
181 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200182 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700183 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700184 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700185 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700186 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700187 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200188 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200189 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200190 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700191 transient_suppressor_enabled_ = transient_suppressor_enabled;
192 }
193
194 changed |= first_update_;
195 first_update_ = false;
196 return changed;
197}
198
saza1d600522019-10-18 13:29:43 +0200199bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700200 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200201 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700202}
203
saza1d600522019-10-18 13:29:43 +0200204bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
205 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200206 // If echo controller is present, assume it performs active processing.
207 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
208}
209
saza1d600522019-10-18 13:29:43 +0200210bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200211 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100212 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
213 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200214 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700215}
216
saza1d600522019-10-18 13:29:43 +0200217bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700218 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200219 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
220 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700221}
222
saza1d600522019-10-18 13:29:43 +0200223bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200224 return capture_analyzer_enabled_;
225}
226
saza1d600522019-10-18 13:29:43 +0200227bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700228 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100229 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
230 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700231}
232
saza1d600522019-10-18 13:29:43 +0200233bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100234 const {
235 return render_pre_processor_enabled_;
236}
237
saza1d600522019-10-18 13:29:43 +0200238bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700239 const {
peah2ace3f92016-09-10 04:42:27 -0700240 return false;
peah2ace3f92016-09-10 04:42:27 -0700241}
242
saza1d600522019-10-18 13:29:43 +0200243bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100244 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
245 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200246}
247
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100248AudioProcessingBuilder::AudioProcessingBuilder() = default;
249AudioProcessingBuilder::~AudioProcessingBuilder() = default;
250
251AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
252 std::unique_ptr<CustomProcessing> capture_post_processing) {
253 capture_post_processing_ = std::move(capture_post_processing);
254 return *this;
255}
256
257AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
258 std::unique_ptr<CustomProcessing> render_pre_processing) {
259 render_pre_processing_ = std::move(render_pre_processing);
260 return *this;
261}
262
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200263AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
264 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
265 capture_analyzer_ = std::move(capture_analyzer);
266 return *this;
267}
268
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100269AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
270 std::unique_ptr<EchoControlFactory> echo_control_factory) {
271 echo_control_factory_ = std::move(echo_control_factory);
272 return *this;
273}
274
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100275AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200276 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100277 echo_detector_ = std::move(echo_detector);
278 return *this;
279}
280
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100281AudioProcessing* AudioProcessingBuilder::Create() {
282 webrtc::Config config;
283 return Create(config);
284}
285
286AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100287 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
288 config, std::move(capture_post_processing_),
289 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200290 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100291 if (apm->Initialize() != AudioProcessing::kNoError) {
292 delete apm;
293 apm = nullptr;
294 }
295 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100296}
297
peah88ac8532016-09-12 16:47:25 -0700298AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200299 : AudioProcessingImpl(config,
300 /*capture_post_processor=*/nullptr,
301 /*render_pre_processor=*/nullptr,
302 /*echo_control_factory=*/nullptr,
303 /*echo_detector=*/nullptr,
304 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000305
Per Åhgren13735822018-02-12 21:42:56 +0100306int AudioProcessingImpl::instance_count_ = 0;
307
Sam Zackrisson0beac582017-09-25 12:04:02 +0200308AudioProcessingImpl::AudioProcessingImpl(
309 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100310 std::unique_ptr<CustomProcessing> capture_post_processor,
311 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200312 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200313 rtc::scoped_refptr<EchoDetector> echo_detector,
314 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100315 : data_dumper_(
316 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgren0cbb58e2019-10-29 22:59:44 +0100317 enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100318 use_setup_specific_default_aec3_config_(
319 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200320 capture_runtime_settings_(kRuntimeSettingQueueSize),
321 render_runtime_settings_(kRuntimeSettingQueueSize),
322 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
323 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200324 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200325 submodule_states_(!!capture_post_processor,
326 !!render_pre_processor,
327 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200328 submodules_(std::move(capture_post_processor),
329 std::move(render_pre_processor),
330 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100331 std::move(capture_analyzer)),
332 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
333 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000334#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Per Åhgren3daedb62019-11-22 12:11:40 +0100335 /* enabled= */ false,
336 /* enabled_agc2_level_estimator= */ false,
337 /* digital_adaptive_disabled= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000338#else
Per Åhgren3daedb62019-11-22 12:11:40 +0100339 config.Get<ExperimentalAgc>().enabled,
340 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
341 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000342#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200343 !field_trial::IsEnabled(
344 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
345 !field_trial::IsEnabled(
346 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700347#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200348 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700349#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200350 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700351#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200352 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200353 RTC_LOG(LS_INFO) << "Injected APM submodules:"
354 << "\nEcho control factory: " << !!echo_control_factory_
355 << "\nEcho detector: " << !!submodules_.echo_detector
356 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
357 << "\nCapture post processor: "
358 << !!submodules_.capture_post_processor
359 << "\nRender pre processor: "
360 << !!submodules_.render_pre_processor;
361
Sam Zackrisson421c8592019-02-11 13:39:46 +0100362 // Mark Echo Controller enabled if a factory is injected.
363 capture_nonlocked_.echo_controller_enabled =
364 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000365
saza1d600522019-10-18 13:29:43 +0200366 submodules_.gain_control.reset(new GainControlImpl());
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200367
Sam Zackrisson421c8592019-02-11 13:39:46 +0100368 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200369 if (!submodules_.echo_detector) {
370 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100371 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800372 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000373
Sam Zackrisson421c8592019-02-11 13:39:46 +0100374 // TODO(alessiob): Move the injected gain controller once injection is
375 // implemented.
saza1d600522019-10-18 13:29:43 +0200376 submodules_.gain_controller2.reset(new GainController2());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100377
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000378 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000379}
380
Per Åhgren0e3198e2019-11-18 08:52:22 +0100381AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000382
niklase@google.com470e71d2011-07-07 08:21:25 +0000383int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800384 // Run in a single-threaded manner during initialization.
385 rtc::CritScope cs_render(&crit_render_);
386 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000387 return InitializeLocked();
388}
389
peahde65ddc2016-09-16 15:02:15 -0700390int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
391 int capture_output_sample_rate_hz,
392 int render_input_sample_rate_hz,
393 ChannelLayout capture_input_layout,
394 ChannelLayout capture_output_layout,
395 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700396 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700397 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
398 LayoutHasKeyboard(capture_input_layout)},
399 {capture_output_sample_rate_hz,
400 ChannelsFromLayout(capture_output_layout),
401 LayoutHasKeyboard(capture_output_layout)},
402 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
403 LayoutHasKeyboard(render_input_layout)},
404 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
405 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700406
407 return Initialize(processing_config);
408}
409
410int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800411 // Run in a single-threaded manner during initialization.
412 rtc::CritScope cs_render(&crit_render_);
413 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700414 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000415}
416
peahdf3efa82015-11-28 12:35:15 -0800417int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800418 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800419 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200420 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800421 return kNoError;
422 }
peahdf3efa82015-11-28 12:35:15 -0800423
424 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800425 return InitializeLocked(processing_config);
426}
427
niklase@google.com470e71d2011-07-07 08:21:25 +0000428int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200429 UpdateActiveSubmoduleStates();
430
Per Åhgrend47941e2019-08-22 11:51:13 +0200431 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800432 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200433 ? formats_.render_processing_format.sample_rate_hz()
434 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800435 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
436 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200437 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800438 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200439 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700440 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200441 render_audiobuffer_sample_rate_hz,
442 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700443 if (formats_.api_format.reverse_input_stream() !=
444 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800445 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800446 formats_.api_format.reverse_input_stream().num_channels(),
447 formats_.api_format.reverse_input_stream().num_frames(),
448 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800449 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700450 } else {
peahdf3efa82015-11-28 12:35:15 -0800451 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700452 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700453 } else {
peahdf3efa82015-11-28 12:35:15 -0800454 render_.render_audio.reset(nullptr);
455 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700456 }
peahce4d9152017-05-19 01:28:05 -0700457
Per Åhgrend47941e2019-08-22 11:51:13 +0200458 capture_.capture_audio.reset(new AudioBuffer(
459 formats_.api_format.input_stream().sample_rate_hz(),
460 formats_.api_format.input_stream().num_channels(),
461 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
462 formats_.api_format.output_stream().num_channels(),
463 formats_.api_format.output_stream().sample_rate_hz(),
464 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000465
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200466 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
467 formats_.api_format.output_stream().sample_rate_hz() &&
468 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
469 capture_.capture_fullband_audio.reset(
470 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
471 formats_.api_format.input_stream().num_channels(),
472 formats_.api_format.output_stream().sample_rate_hz(),
473 formats_.api_format.output_stream().num_channels(),
474 formats_.api_format.output_stream().sample_rate_hz(),
475 formats_.api_format.output_stream().num_channels()));
476 } else {
477 capture_.capture_fullband_audio.reset();
478 }
479
peah764e3642016-10-22 05:04:30 -0700480 AllocateRenderQueue();
481
saza1d600522019-10-18 13:29:43 +0200482 submodules_.gain_control->Initialize(num_proc_channels(),
483 proc_sample_rate_hz());
Per Åhgren3daedb62019-11-22 12:11:40 +0100484 if (constants_.use_experimental_agc) {
485 if (!submodules_.agc_manager.get() ||
486 submodules_.agc_manager->num_channels() !=
487 static_cast<int>(num_proc_channels()) ||
488 submodules_.agc_manager->sample_rate_hz() !=
489 capture_nonlocked_.split_rate) {
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100490 int stream_analog_level = -1;
491 const bool re_creation = !!submodules_.agc_manager;
492 if (re_creation) {
493 stream_analog_level = submodules_.agc_manager->stream_analog_level();
494 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100495 submodules_.agc_manager.reset(new AgcManagerDirect(
496 num_proc_channels(), constants_.agc_startup_min_volume,
497 constants_.agc_clipped_level_min,
498 constants_.use_experimental_agc_agc2_level_estimation,
499 constants_.use_experimental_agc_agc2_digital_adaptive,
500 capture_nonlocked_.split_rate));
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100501 if (re_creation) {
502 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
503 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100504 }
saza1d600522019-10-18 13:29:43 +0200505 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 12:11:40 +0100506 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 08:52:22 +0100507 submodules_.gain_control.get());
saza1d600522019-10-18 13:29:43 +0200508 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 15:02:15 -0700509 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200510 InitializeTransient();
Per Åhgren4011de02019-12-03 11:48:48 +0000511 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200512 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700513 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200514 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700515 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200516 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200517 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200518 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100519 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800520
aleloi868f32f2017-05-23 07:20:05 -0700521 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200522 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700523 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000524 return kNoError;
525}
526
Michael Graczyk86c6d332015-07-23 11:41:39 -0700527int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200528 UpdateActiveSubmoduleStates();
529
Michael Graczyk86c6d332015-07-23 11:41:39 -0700530 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700531 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
532 return kBadSampleRateError;
533 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000534 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700535
Peter Kasting69558702016-01-12 16:26:35 -0800536 const size_t num_in_channels = config.input_stream().num_channels();
537 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700538
539 // Need at least one input channel.
540 // Need either one output channel or as many outputs as there are inputs.
541 if (num_in_channels == 0 ||
542 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700543 return kBadNumberChannelsError;
544 }
545
peahdf3efa82015-11-28 12:35:15 -0800546 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000547
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200548 // Choose maximum rate to use for the split filtering.
549 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
550 config_.pipeline.maximum_internal_processing_rate == 32000);
551 int max_splitting_rate = 48000;
552 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
553 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
554 }
555
Per Åhgrenc8626b62019-08-23 15:49:51 +0200556 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700557 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700558 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200559 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700560 submodule_states_.CaptureMultiBandSubModulesActive() ||
561 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200562 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000563
peahde65ddc2016-09-16 15:02:15 -0700564 capture_nonlocked_.capture_processing_format =
565 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700566
peah2ce640f2017-04-07 03:57:48 -0700567 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200568 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200569 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700570 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
571 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200572 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700573 submodule_states_.CaptureMultiBandSubModulesActive() ||
574 submodule_states_.RenderMultiBandSubModulesActive());
575 } else {
576 render_processing_rate = capture_processing_rate;
577 }
578
peahde65ddc2016-09-16 15:02:15 -0700579 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700580 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700581 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
582 kSampleRate8kHz) {
583 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000584 } else {
peahde65ddc2016-09-16 15:02:15 -0700585 render_processing_rate =
586 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000587 }
588
Per Åhgrenc8626b62019-08-23 15:49:51 +0200589 RTC_DCHECK_NE(8000, render_processing_rate);
590
peahce4d9152017-05-19 01:28:05 -0700591 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200592 // By default, downmix the render stream to mono for analysis. This has been
593 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100594 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
595 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200596 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100597 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200598 ? formats_.api_format.reverse_input_stream().num_channels()
599 : 1;
600 formats_.render_processing_format =
601 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700602 } else {
603 formats_.render_processing_format = StreamConfig(
604 formats_.api_format.reverse_input_stream().sample_rate_hz(),
605 formats_.api_format.reverse_input_stream().num_channels());
606 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000607
peahde65ddc2016-09-16 15:02:15 -0700608 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
609 kSampleRate32kHz ||
610 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
611 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800612 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000613 } else {
peahdf3efa82015-11-28 12:35:15 -0800614 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700615 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000616 }
617
618 return InitializeLocked();
619}
620
peah88ac8532016-09-12 16:47:25 -0700621void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200622 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
623
peah88ac8532016-09-12 16:47:25 -0700624 // Run in a single-threaded manner when applying the settings.
625 rtc::CritScope cs_render(&crit_render_);
626 rtc::CritScope cs_capture(&crit_capture_);
627
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200628 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100629 config_.pipeline.multi_channel_render !=
630 config.pipeline.multi_channel_render ||
631 config_.pipeline.multi_channel_capture !=
632 config.pipeline.multi_channel_capture;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200633
Per Åhgren200feba2019-03-06 04:16:46 +0100634 const bool aec_config_changed =
635 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100636 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100637
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100638 const bool agc1_config_changed =
639 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
640 config_.gain_controller1.mode != config.gain_controller1.mode ||
641 config_.gain_controller1.target_level_dbfs !=
642 config.gain_controller1.target_level_dbfs ||
643 config_.gain_controller1.compression_gain_db !=
644 config.gain_controller1.compression_gain_db ||
645 config_.gain_controller1.enable_limiter !=
646 config.gain_controller1.enable_limiter ||
647 config_.gain_controller1.analog_level_minimum !=
648 config.gain_controller1.analog_level_minimum ||
649 config_.gain_controller1.analog_level_maximum !=
650 config.gain_controller1.analog_level_maximum;
651
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200652 const bool voice_detection_config_changed =
653 config_.voice_detection.enabled != config.voice_detection.enabled;
654
saza0bad15f2019-10-16 11:46:11 +0200655 const bool ns_config_changed =
656 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
657 config_.noise_suppression.level != config.noise_suppression.level;
658
Yves Gerey499bc6c2018-10-10 18:29:07 +0200659 config_ = config;
660
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100661 // Ensure that this deprecated setting is not used by mistake.
662 RTC_DCHECK(!config_.echo_canceller.use_legacy_aec);
663
Per Åhgren200feba2019-03-06 04:16:46 +0100664 if (aec_config_changed) {
665 InitializeEchoController();
666 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200667
saza0bad15f2019-10-16 11:46:11 +0200668 if (ns_config_changed) {
669 InitializeNoiseSuppressor();
670 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100671
Per Åhgren4011de02019-12-03 11:48:48 +0000672 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800673
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100674 if (agc1_config_changed) {
675 ApplyAgc1Config(config_.gain_controller1);
676 }
677
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100678 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700679 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100680 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
681 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100682 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100683 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700684 config_.gain_controller2 = AudioProcessing::Config::GainController2();
685 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200686 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200687 InitializePreAmplifier();
saza1d600522019-10-18 13:29:43 +0200688 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100689
saza1d600522019-10-18 13:29:43 +0200690 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
691 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100692 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100693
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200694 if (voice_detection_config_changed) {
695 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100696 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200697
698 // Reinitialization must happen after all submodule configuration to avoid
699 // additional reinitializations on the next capture / render processing call.
700 if (pipeline_config_changed) {
701 InitializeLocked(formats_.api_format);
702 }
peah88ac8532016-09-12 16:47:25 -0700703}
704
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100705void AudioProcessingImpl::ApplyAgc1Config(
706 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100707 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100708 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100709
Per Åhgren0e3198e2019-11-18 08:52:22 +0100710 if (!submodules_.agc_manager) {
711 error = submodules_.gain_control->set_mode(
712 Agc1ConfigModeToInterfaceMode(config.mode));
713 RTC_DCHECK_EQ(kNoError, error);
714 error = submodules_.gain_control->set_target_level_dbfs(
715 config.target_level_dbfs);
716 RTC_DCHECK_EQ(kNoError, error);
717 error = submodules_.gain_control->set_compression_gain_db(
718 config.compression_gain_db);
719 RTC_DCHECK_EQ(kNoError, error);
720 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
721 RTC_DCHECK_EQ(kNoError, error);
722 error = submodules_.gain_control->set_analog_level_limits(
723 config.analog_level_minimum, config.analog_level_maximum);
724 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100725 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100726}
727
peah88ac8532016-09-12 16:47:25 -0700728void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800729 // Run in a single-threaded manner when setting the extra options.
730 rtc::CritScope cs_render(&crit_render_);
731 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000732
peahdf3efa82015-11-28 12:35:15 -0800733 if (capture_.transient_suppressor_enabled !=
734 config.Get<ExperimentalNs>().enabled) {
735 capture_.transient_suppressor_enabled =
736 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000737 InitializeTransient();
738 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000739}
740
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000741int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800742 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700743 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200746int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
747 return capture_.capture_fullband_audio
748 ? capture_.capture_fullband_audio->num_frames() * 100
749 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
750}
751
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000752int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800753 // Used as callback from submodules, hence locking is not allowed.
754 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000755}
756
Peter Kasting69558702016-01-12 16:26:35 -0800757size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800758 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700759 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000760}
761
Peter Kasting69558702016-01-12 16:26:35 -0800762size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800763 // Used as callback from submodules, hence locking is not allowed.
764 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000765}
766
Peter Kasting69558702016-01-12 16:26:35 -0800767size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800768 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100769 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
770 constants_.multi_channel_capture_support;
771 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200772 return 1;
773 }
774 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800775}
776
Peter Kasting69558702016-01-12 16:26:35 -0800777size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800778 // Used as callback from submodules, hence locking is not allowed.
779 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000780}
781
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000782void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800783 rtc::CritScope cs(&crit_capture_);
784 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200785 if (submodules_.agc_manager.get()) {
786 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000787 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000788}
789
Alessio Bazzicac054e782018-04-16 12:10:09 +0200790void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200791 switch (setting.type()) {
792 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100793 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200794 render_runtime_settings_enqueuer_.Enqueue(setting);
795 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200796 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100797 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200798 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100799 capture_runtime_settings_enqueuer_.Enqueue(setting);
800 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200801 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200802 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100803 render_runtime_settings_enqueuer_.Enqueue(setting);
804 return;
805 case RuntimeSetting::Type::kNotSpecified:
806 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200807 return;
808 }
809 // The language allows the enum to have a non-enumerator
810 // value. Check that this doesn't happen.
811 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200812}
813
814AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
815 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200816 : runtime_settings_(*runtime_settings) {
817 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200818}
819
820AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
821 default;
822
823void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
824 RuntimeSetting setting) {
825 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200826 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200827 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200828 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200829 RTC_LOG(LS_ERROR)
830 << "The runtime settings queue is full. Oldest setting discarded.";
831 }
832 if (remaining_attempts == 0)
833 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
834}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000835
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000836int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700837 const StreamConfig& input_config,
838 const StreamConfig& output_config,
839 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800840 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800841 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700842 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800843 {
844 // Acquire the capture lock in order to safely call the function
845 // that retrieves the render side data. This function accesses apm
846 // getters that need the capture lock held when being called.
847 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700848 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800849
850 if (!src || !dest) {
851 return kNullPointerError;
852 }
853
854 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700855 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000856 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000857
Oskar Sundbom4b276482019-05-23 14:28:00 +0200858 if (processing_config.input_stream() != input_config) {
859 processing_config.input_stream() = input_config;
860 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800861 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200862
863 if (processing_config.output_stream() != output_config) {
864 processing_config.output_stream() = output_config;
865 reinitialization_required = true;
866 }
867
868 if (reinitialization_required) {
869 // Reinitialize.
870 rtc::CritScope cs_render(&crit_render_);
871 rtc::CritScope cs_capture(&crit_capture_);
872 RETURN_ON_ERR(InitializeLocked(processing_config));
873 }
874
peahdf3efa82015-11-28 12:35:15 -0800875 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700876 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
877 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000878
aleloi868f32f2017-05-23 07:20:05 -0700879 if (aec_dump_) {
880 RecordUnprocessedCaptureStream(src);
881 }
882
Per Åhgrena1351272019-08-15 12:15:46 +0200883 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800884 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200885 if (capture_.capture_fullband_audio) {
886 capture_.capture_fullband_audio->CopyFrom(
887 src, formats_.api_format.input_stream());
888 }
peahde65ddc2016-09-16 15:02:15 -0700889 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200890 if (capture_.capture_fullband_audio) {
891 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
892 dest);
893 } else {
894 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
895 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000896
aleloi868f32f2017-05-23 07:20:05 -0700897 if (aec_dump_) {
898 RecordProcessedCaptureStream(dest);
899 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000900 return kNoError;
901}
902
Alex Loiko73ec0192018-05-15 10:52:28 +0200903void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200904 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200905 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200906 if (aec_dump_) {
907 aec_dump_->WriteRuntimeSetting(setting);
908 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200909 switch (setting.type()) {
910 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200911 if (config_.pre_amplifier.enabled) {
912 float value;
913 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200914 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200915 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200916 }
917 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200918 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100919 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100920 if (!submodules_.agc_manager) {
921 float value;
922 setting.GetFloat(&value);
923 int int_value = static_cast<int>(value + .5f);
924 config_.gain_controller1.compression_gain_db = int_value;
925 int error =
926 submodules_.gain_control->set_compression_gain_db(int_value);
927 RTC_DCHECK_EQ(kNoError, error);
928 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100929 break;
930 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200931 case RuntimeSetting::Type::kCaptureFixedPostGain: {
932 if (config_.gain_controller2.enabled) {
933 float value;
934 setting.GetFloat(&value);
935 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200936 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200937 }
938 break;
939 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200940 case RuntimeSetting::Type::kPlayoutVolumeChange: {
941 int value;
942 setting.GetInt(&value);
943 capture_.playout_volume = value;
944 break;
945 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100946 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
947 RTC_NOTREACHED();
948 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200949 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
950 RTC_NOTREACHED();
951 break;
952 case RuntimeSetting::Type::kNotSpecified:
953 RTC_NOTREACHED();
954 break;
955 }
956 }
957}
958
959void AudioProcessingImpl::HandleRenderRuntimeSettings() {
960 RuntimeSetting setting;
961 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200962 if (aec_dump_) {
963 aec_dump_->WriteRuntimeSetting(setting);
964 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200965 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100966 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100967 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200968 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200969 if (submodules_.render_pre_processor) {
970 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200971 }
972 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100973 case RuntimeSetting::Type::kCapturePreGain: // fall-through
974 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200975 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200976 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200977 RTC_NOTREACHED();
978 break;
979 }
980 }
981}
982
peah9e6a2902017-05-15 07:19:21 -0700983void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800984 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700985
saza1d600522019-10-18 13:29:43 +0200986 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200987 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
988 num_reverse_channels(),
989 &aecm_render_queue_buffer_);
990 RTC_DCHECK(aecm_render_signal_queue_);
991 // Insert the samples into the queue.
992 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
993 // The data queue is full and needs to be emptied.
994 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -0700995
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200996 // Retry the insert (should always work).
997 bool result =
998 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
999 RTC_DCHECK(result);
1000 }
peah764e3642016-10-22 05:04:30 -07001001 }
peah701d6282016-10-25 05:42:20 -07001002
Per Åhgren0e3198e2019-11-18 08:52:22 +01001003 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001004 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001005 // Insert the samples into the queue.
1006 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1007 // The data queue is full and needs to be emptied.
1008 EmptyQueuedRenderAudio();
1009
1010 // Retry the insert (should always work).
1011 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1012 RTC_DCHECK(result);
1013 }
1014 }
peah9e6a2902017-05-15 07:19:21 -07001015}
ivoc9f4a4a02016-10-28 05:39:16 -07001016
peah9e6a2902017-05-15 07:19:21 -07001017void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001018 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1019
1020 // Insert the samples into the queue.
1021 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1022 // The data queue is full and needs to be emptied.
1023 EmptyQueuedRenderAudio();
1024
1025 // Retry the insert (should always work).
1026 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1027 RTC_DCHECK(result);
1028 }
peah764e3642016-10-22 05:04:30 -07001029}
1030
1031void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001032 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001033 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001034
ivoc9f4a4a02016-10-28 05:39:16 -07001035 const size_t new_red_render_queue_element_max_size =
1036 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1037
peaha0624602016-10-25 04:45:24 -07001038 // Reallocate the queues if the queue item sizes are too small to fit the
1039 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001040
1041 if (agc_render_queue_element_max_size_ <
1042 new_agc_render_queue_element_max_size) {
1043 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1044
1045 std::vector<int16_t> template_queue_element(
1046 agc_render_queue_element_max_size_);
1047
1048 agc_render_signal_queue_.reset(
1049 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1050 kMaxNumFramesToBuffer, template_queue_element,
1051 RenderQueueItemVerifier<int16_t>(
1052 agc_render_queue_element_max_size_)));
1053
1054 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1055 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1056 } else {
1057 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001058 }
ivoc9f4a4a02016-10-28 05:39:16 -07001059
1060 if (red_render_queue_element_max_size_ <
1061 new_red_render_queue_element_max_size) {
1062 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1063
1064 std::vector<float> template_queue_element(
1065 red_render_queue_element_max_size_);
1066
1067 red_render_signal_queue_.reset(
1068 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1069 kMaxNumFramesToBuffer, template_queue_element,
1070 RenderQueueItemVerifier<float>(
1071 red_render_queue_element_max_size_)));
1072
1073 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1074 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1075 } else {
1076 red_render_signal_queue_->Clear();
1077 }
peah764e3642016-10-22 05:04:30 -07001078}
1079
1080void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1081 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001082 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001083 RTC_DCHECK(aecm_render_signal_queue_);
1084 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001085 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001086 aecm_capture_queue_buffer_);
1087 }
peah701d6282016-10-25 05:42:20 -07001088 }
1089
1090 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001091 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001092 }
ivoc9f4a4a02016-10-28 05:39:16 -07001093
1094 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001095 RTC_DCHECK(submodules_.echo_detector);
1096 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001097 }
peah764e3642016-10-22 05:04:30 -07001098}
1099
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001100int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001101 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001102 {
1103 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001104 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001105 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001106 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001107 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001108 }
peahfa6228e2015-11-16 16:27:42 -08001109
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001110 if (!frame) {
1111 return kNullPointerError;
1112 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001113 // Must be a native rate.
1114 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1115 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001116 frame->sample_rate_hz_ != kSampleRate32kHz &&
1117 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001118 return kBadSampleRateError;
1119 }
peah192164e2015-11-17 02:16:45 -08001120
peahdf3efa82015-11-28 12:35:15 -08001121 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001122 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001123 {
1124 // Aquire lock for the access of api_format.
1125 // The lock is released immediately due to the conditional
1126 // reinitialization.
1127 rtc::CritScope cs_capture(&crit_capture_);
1128 // TODO(ajm): The input and output rates and channels are currently
1129 // constrained to be identical in the int16 interface.
1130 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001131
1132 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001133 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001134
Oskar Sundbom4b276482019-05-23 14:28:00 +02001135 reinitialization_required =
1136 reinitialization_required ||
1137 processing_config.input_stream().sample_rate_hz() !=
1138 frame->sample_rate_hz_ ||
1139 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1140 processing_config.output_stream().sample_rate_hz() !=
1141 frame->sample_rate_hz_ ||
1142 processing_config.output_stream().num_channels() != frame->num_channels_;
1143
1144 if (reinitialization_required) {
1145 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1146 processing_config.input_stream().set_num_channels(frame->num_channels_);
1147 processing_config.output_stream().set_sample_rate_hz(
1148 frame->sample_rate_hz_);
1149 processing_config.output_stream().set_num_channels(frame->num_channels_);
1150
1151 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001152 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001153 rtc::CritScope cs_capture(&crit_capture_);
1154 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001155 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001156
peahdf3efa82015-11-28 12:35:15 -08001157 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001158 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001159 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001160 return kBadDataLengthError;
1161 }
1162
aleloi868f32f2017-05-23 07:20:05 -07001163 if (aec_dump_) {
1164 RecordUnprocessedCaptureStream(*frame);
1165 }
1166
Per Åhgrend47941e2019-08-22 11:51:13 +02001167 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001168 if (capture_.capture_fullband_audio) {
1169 capture_.capture_fullband_audio->CopyFrom(frame);
1170 }
peahde65ddc2016-09-16 15:02:15 -07001171 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001172 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001173 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001174 if (capture_.capture_fullband_audio) {
1175 capture_.capture_fullband_audio->CopyTo(frame);
1176 } else {
1177 capture_.capture_audio->CopyTo(frame);
1178 }
Per Åhgrena1351272019-08-15 12:15:46 +02001179 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001180 if (capture_.stats.voice_detected) {
1181 frame->vad_activity_ = *capture_.stats.voice_detected
1182 ? AudioFrame::kVadActive
1183 : AudioFrame::kVadPassive;
1184 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001185
aleloi868f32f2017-05-23 07:20:05 -07001186 if (aec_dump_) {
1187 RecordProcessedCaptureStream(*frame);
1188 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001189
1190 return kNoError;
1191}
1192
peahde65ddc2016-09-16 15:02:15 -07001193int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001194 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001195
peahb58a1582016-03-15 09:34:24 -07001196 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001197 // TODO(peah): Simplify once the public API Enable functions for these
1198 // are moved to APM.
saza1d600522019-10-18 13:29:43 +02001199 RTC_DCHECK_LE(!!submodules_.echo_controller +
saza1d600522019-10-18 13:29:43 +02001200 !!submodules_.echo_control_mobile,
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001201 1);
peahb58a1582016-03-15 09:34:24 -07001202
peahde65ddc2016-09-16 15:02:15 -07001203 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001204
saza1d600522019-10-18 13:29:43 +02001205 if (submodules_.pre_amplifier) {
1206 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001207 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001208 capture_buffer->num_frames()));
1209 }
1210
Per Åhgren928146f2019-08-20 09:19:21 +02001211 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001212 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001213 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001214 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1215 if (log_rms) {
1216 capture_rms_interval_counter_ = 0;
1217 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001218 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1219 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1220 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1221 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001222 }
1223
saza1d600522019-10-18 13:29:43 +02001224 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001225 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001226 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001227 capture_.echo_path_gain_change =
1228 capture_.prev_analog_mic_level != analog_mic_level &&
1229 capture_.prev_analog_mic_level != -1;
1230 capture_.prev_analog_mic_level = analog_mic_level;
1231
Per Åhgrend2650d12018-10-02 17:00:59 +02001232 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001233 if (submodules_.pre_amplifier) {
1234 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001235 capture_.echo_path_gain_change =
1236 capture_.echo_path_gain_change ||
1237 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001238 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001239 capture_.prev_pre_amp_gain = pre_amp_gain;
1240 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001241
1242 // Detect volume change.
1243 capture_.echo_path_gain_change =
1244 capture_.echo_path_gain_change ||
1245 (capture_.prev_playout_volume != capture_.playout_volume &&
1246 capture_.prev_playout_volume >= 0);
1247 capture_.prev_playout_volume = capture_.playout_volume;
1248
saza1d600522019-10-18 13:29:43 +02001249 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001250 }
1251
Per Åhgren3daedb62019-11-22 12:11:40 +01001252 if (constants_.use_experimental_agc &&
1253 submodules_.gain_control->is_enabled()) {
1254 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001255 }
1256
peah2ace3f92016-09-10 04:42:27 -07001257 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1258 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001259 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1260 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001261 }
1262
Per Åhgrene14cb992019-11-27 09:34:22 +01001263 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1264 constants_.multi_channel_capture_support;
1265 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001266 // Force down-mixing of the number of channels after the detection of
1267 // capture signal saturation.
1268 // TODO(peah): Look into ensuring that this kind of tampering with the
1269 // AudioBuffer functionality should not be needed.
1270 capture_buffer->set_num_channels(1);
1271 }
1272
saza1d600522019-10-18 13:29:43 +02001273 if (submodules_.high_pass_filter) {
1274 submodules_.high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001275 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001276
Per Åhgrene35b32c2019-11-22 18:22:04 +01001277 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001278 RTC_DCHECK(
1279 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
saza1d600522019-10-18 13:29:43 +02001280 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001281 submodules_.noise_suppressor->Analyze(*capture_buffer);
1282 } else if (submodules_.legacy_noise_suppressor) {
1283 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001284 }
peahb58a1582016-03-15 09:34:24 -07001285
saza1d600522019-10-18 13:29:43 +02001286 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001287 // Ensure that the stream delay was set before the call to the
1288 // AECM ProcessCaptureAudio function.
1289 if (!was_stream_delay_set()) {
1290 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001291 }
1292
saza1d600522019-10-18 13:29:43 +02001293 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001294 submodules_.noise_suppressor->Process(capture_buffer);
1295 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001296 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001297 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001298 }
peahe0eae3c2016-12-14 01:16:23 -08001299
saza1d600522019-10-18 13:29:43 +02001300 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001301 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001302 } else {
saza1d600522019-10-18 13:29:43 +02001303 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001304 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1305
1306 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001307 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001308 }
1309
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001310 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
saza1d600522019-10-18 13:29:43 +02001311 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001312 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001313 }
1314
saza1d600522019-10-18 13:29:43 +02001315 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001316 submodules_.noise_suppressor->Process(capture_buffer);
1317 } else if (submodules_.legacy_noise_suppressor) {
1318 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001319 }
Per Åhgren46537a32017-06-07 10:08:10 +02001320 }
ivoc9f4a4a02016-10-28 05:39:16 -07001321
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001322 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001323 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001324 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001325 } else {
1326 capture_.stats.voice_detected = absl::nullopt;
1327 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001328
Per Åhgren3daedb62019-11-22 12:11:40 +01001329 if (constants_.use_experimental_agc &&
1330 submodules_.gain_control->is_enabled()) {
1331 submodules_.agc_manager->Process(capture_buffer);
1332
1333 absl::optional<int> new_digital_gain =
1334 submodules_.agc_manager->GetDigitalComressionGain();
1335 if (new_digital_gain) {
1336 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1337 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001338 }
Per Åhgren200feba2019-03-06 04:16:46 +01001339 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001340 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001341 capture_buffer, /*stream_has_echo*/ false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001342
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001343 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001344 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001345 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1346 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001347 }
1348
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001349 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001350 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001351 bool ec_active = ec ? ec->ActiveProcessing() : false;
1352 // Only update the fullband buffer if the multiband processing has changed
1353 // the signal. Keep the original signal otherwise.
1354 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1355 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1356 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001357 capture_buffer = capture_.capture_fullband_audio.get();
1358 }
1359
peah9e6a2902017-05-15 07:19:21 -07001360 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001361 RTC_DCHECK(submodules_.echo_detector);
1362 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1363 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001364 }
1365
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001366 // TODO(aluebs): Investigate if the transient suppression placement should be
1367 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001368 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001369 float voice_probability = submodules_.agc_manager.get()
1370 ? submodules_.agc_manager->voice_probability()
1371 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001372
saza1d600522019-10-18 13:29:43 +02001373 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001374 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001375 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001376 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001377 capture_buffer->num_frames_per_band(),
1378 capture_.keyboard_info.keyboard_data,
1379 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001380 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001381 }
1382
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001383 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001384 if (submodules_.capture_analyzer) {
1385 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001386 }
1387
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001388 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001389 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001390 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001391 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001392 }
1393
saza1d600522019-10-18 13:29:43 +02001394 if (submodules_.capture_post_processor) {
1395 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001396 }
1397
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001398 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001399 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001400 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1401 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001402 } else {
1403 capture_.stats.output_rms_dbfs = absl::nullopt;
1404 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001405
Per Åhgren928146f2019-08-20 09:19:21 +02001406 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001407 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001408 capture_nonlocked_.capture_processing_format.num_frames()));
1409 if (log_rms) {
1410 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1411 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1412 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1413 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1414 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1415 }
1416
Per Åhgren0e3198e2019-11-18 08:52:22 +01001417 if (submodules_.agc_manager) {
1418 int level = recommended_stream_analog_level();
1419 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1420 &level);
1421 }
1422
peahdf3efa82015-11-28 12:35:15 -08001423 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001424 return kNoError;
1425}
1426
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001427int AudioProcessingImpl::AnalyzeReverseStream(
1428 const float* const* data,
1429 const StreamConfig& reverse_config) {
1430 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1431 rtc::CritScope cs(&crit_render_);
1432 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1433}
1434
peahde65ddc2016-09-16 15:02:15 -07001435int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1436 const StreamConfig& input_config,
1437 const StreamConfig& output_config,
1438 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001439 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001440 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001441 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001442 if (submodule_states_.RenderMultiBandProcessingActive() ||
1443 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001444 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1445 dest);
peah2ace3f92016-09-10 04:42:27 -07001446 } else if (formats_.api_format.reverse_input_stream() !=
1447 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001448 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1449 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001450 } else {
peahde65ddc2016-09-16 15:02:15 -07001451 CopyAudioIfNeeded(src, input_config.num_frames(),
1452 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001453 }
1454
1455 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001456}
1457
peahdf3efa82015-11-28 12:35:15 -08001458int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001459 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001460 const StreamConfig& input_config,
1461 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001462 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001463 return kNullPointerError;
1464 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001465
peahde65ddc2016-09-16 15:02:15 -07001466 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001467 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001468 }
1469
peahdf3efa82015-11-28 12:35:15 -08001470 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001471 processing_config.reverse_input_stream() = input_config;
1472 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001473
peahdf3efa82015-11-28 12:35:15 -08001474 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001475 RTC_DCHECK_EQ(input_config.num_frames(),
1476 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001477
aleloi868f32f2017-05-23 07:20:05 -07001478 if (aec_dump_) {
1479 const size_t channel_size =
1480 formats_.api_format.reverse_input_stream().num_frames();
1481 const size_t num_channels =
1482 formats_.api_format.reverse_input_stream().num_channels();
1483 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001484 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001485 }
peahdf3efa82015-11-28 12:35:15 -08001486 render_.render_audio->CopyFrom(src,
1487 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001488 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001489}
1490
1491int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001492 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001493 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001494 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001495 return kNullPointerError;
1496 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001497 // Must be a native rate.
1498 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1499 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001500 frame->sample_rate_hz_ != kSampleRate32kHz &&
1501 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001502 return kBadSampleRateError;
1503 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001504
Michael Graczyk86c6d332015-07-23 11:41:39 -07001505 if (frame->num_channels_ <= 0) {
1506 return kBadNumberChannelsError;
1507 }
1508
peahdf3efa82015-11-28 12:35:15 -08001509 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001510 processing_config.reverse_input_stream().set_sample_rate_hz(
1511 frame->sample_rate_hz_);
1512 processing_config.reverse_input_stream().set_num_channels(
1513 frame->num_channels_);
1514 processing_config.reverse_output_stream().set_sample_rate_hz(
1515 frame->sample_rate_hz_);
1516 processing_config.reverse_output_stream().set_num_channels(
1517 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001518
peahdf3efa82015-11-28 12:35:15 -08001519 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001520 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001521 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001522 return kBadDataLengthError;
1523 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001524
aleloi868f32f2017-05-23 07:20:05 -07001525 if (aec_dump_) {
1526 aec_dump_->WriteRenderStreamMessage(*frame);
1527 }
1528
Per Åhgrend47941e2019-08-22 11:51:13 +02001529 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001530 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001531 if (submodule_states_.RenderMultiBandProcessingActive() ||
1532 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001533 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001534 }
aluebsb0319552016-03-17 20:39:53 -07001535 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001536}
niklase@google.com470e71d2011-07-07 08:21:25 +00001537
peahde65ddc2016-09-16 15:02:15 -07001538int AudioProcessingImpl::ProcessRenderStreamLocked() {
1539 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001540
Alex Loiko73ec0192018-05-15 10:52:28 +02001541 HandleRenderRuntimeSettings();
1542
saza1d600522019-10-18 13:29:43 +02001543 if (submodules_.render_pre_processor) {
1544 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001545 }
1546
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001547 QueueNonbandedRenderAudio(render_buffer);
1548
peah2ace3f92016-09-10 04:42:27 -07001549 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001550 SampleRateSupportsMultiBand(
1551 formats_.render_processing_format.sample_rate_hz())) {
1552 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001553 }
1554
peahce4d9152017-05-19 01:28:05 -07001555 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1556 QueueBandedRenderAudio(render_buffer);
1557 }
1558
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001559 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001560 if (submodules_.echo_controller) {
1561 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001562 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001563
peah2ace3f92016-09-10 04:42:27 -07001564 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001565 SampleRateSupportsMultiBand(
1566 formats_.render_processing_format.sample_rate_hz())) {
1567 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001568 }
1569
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001570 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001571}
1572
1573int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001574 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001575 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001576 capture_.was_stream_delay_set = true;
1577 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001578
niklase@google.com470e71d2011-07-07 08:21:25 +00001579 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001580 delay = 0;
1581 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001582 }
1583
1584 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1585 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001586 delay = 500;
1587 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001588 }
1589
peahdf3efa82015-11-28 12:35:15 -08001590 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001591 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001592}
1593
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001594bool AudioProcessingImpl::GetLinearAecOutput(
1595 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1596 rtc::CritScope cs(&crit_capture_);
1597 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1598
1599 RTC_DCHECK(linear_aec_buffer);
1600 if (linear_aec_buffer) {
1601 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1602 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1603
1604 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1605 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1606 rtc::ArrayView<const float> channel_view =
1607 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1608 linear_aec_buffer->num_frames());
1609 std::copy(channel_view.begin(), channel_view.end(),
1610 linear_output[ch].begin());
1611 }
1612 return true;
1613 }
1614 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1615 RTC_NOTREACHED();
1616 return false;
1617}
1618
niklase@google.com470e71d2011-07-07 08:21:25 +00001619int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001620 // Used as callback from submodules, hence locking is not allowed.
1621 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001622}
1623
1624bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001625 // Used as callback from submodules, hence locking is not allowed.
1626 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001627}
1628
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001629void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001630 rtc::CritScope cs(&crit_capture_);
1631 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001632}
1633
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001634void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001635 rtc::CritScope cs(&crit_capture_);
1636 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001637}
1638
1639int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001640 rtc::CritScope cs(&crit_capture_);
1641 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001642}
1643
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001644void AudioProcessingImpl::set_stream_analog_level(int level) {
1645 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001646
1647 if (submodules_.agc_manager) {
1648 submodules_.agc_manager->set_stream_analog_level(level);
1649 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1650 1, &level);
1651 } else {
1652 int error = submodules_.gain_control->set_stream_analog_level(level);
1653 RTC_DCHECK_EQ(kNoError, error);
1654 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001655}
1656
1657int AudioProcessingImpl::recommended_stream_analog_level() const {
1658 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001659 if (submodules_.agc_manager) {
1660 return submodules_.agc_manager->stream_analog_level();
1661 }
1662 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001663}
1664
aleloi868f32f2017-05-23 07:20:05 -07001665void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1666 RTC_DCHECK(aec_dump);
1667 rtc::CritScope cs_render(&crit_render_);
1668 rtc::CritScope cs_capture(&crit_capture_);
1669
1670 // The previously attached AecDump will be destroyed with the
1671 // 'aec_dump' parameter, which is after locks are released.
1672 aec_dump_.swap(aec_dump);
1673 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001674 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001675}
1676
1677void AudioProcessingImpl::DetachAecDump() {
1678 // The d-tor of a task-queue based AecDump blocks until all pending
1679 // tasks are done. This construction avoids blocking while holding
1680 // the render and capture locks.
1681 std::unique_ptr<AecDump> aec_dump = nullptr;
1682 {
1683 rtc::CritScope cs_render(&crit_render_);
1684 rtc::CritScope cs_capture(&crit_capture_);
1685 aec_dump = std::move(aec_dump_);
1686 }
1687}
1688
Sam Zackrisson4d364492018-03-02 16:03:21 +01001689void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1690 std::unique_ptr<AudioGenerator> audio_generator) {
1691 // TODO(bugs.webrtc.org/8882) Stub.
1692 // Reset internal audio generator with audio_generator.
1693}
1694
1695void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1696 // TODO(bugs.webrtc.org/8882) Stub.
1697 // Delete audio generator, if one is attached.
1698}
1699
Ivo Creusen56d46092017-11-24 17:29:59 +01001700AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001701 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001702 rtc::CritScope cs_capture(&crit_capture_);
1703 if (!has_remote_tracks) {
1704 return capture_.stats;
1705 }
1706 AudioProcessingStats stats = capture_.stats;
saza1d600522019-10-18 13:29:43 +02001707 if (submodules_.echo_controller) {
1708 auto ec_metrics = submodules_.echo_controller->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001709 stats.echo_return_loss = ec_metrics.echo_return_loss;
1710 stats.echo_return_loss_enhancement =
1711 ec_metrics.echo_return_loss_enhancement;
1712 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001713 }
1714 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001715 RTC_DCHECK(submodules_.echo_detector);
1716 auto ed_metrics = submodules_.echo_detector->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001717 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1718 stats.residual_echo_likelihood_recent_max =
1719 ed_metrics.echo_likelihood_recent_max;
1720 }
Ivo Creusenae026092017-11-20 13:07:16 +01001721 return stats;
1722}
1723
peah8271d042016-11-22 07:24:52 -08001724void AudioProcessingImpl::MutateConfig(
1725 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1726 rtc::CritScope cs_render(&crit_render_);
1727 rtc::CritScope cs_capture(&crit_capture_);
1728 mutator(&config_);
1729 ApplyConfig(config_);
1730}
1731
1732AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1733 rtc::CritScope cs_render(&crit_render_);
1734 rtc::CritScope cs_capture(&crit_capture_);
1735 return config_;
1736}
1737
peah2ace3f92016-09-10 04:42:27 -07001738bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1739 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001740 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
1741 config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001742 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
1743 submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled,
1744 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 11:46:11 +02001745 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001746}
1747
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001748void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001749 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001750 if (!submodules_.transient_suppressor.get()) {
1751 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001752 }
saza1d600522019-10-18 13:29:43 +02001753 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1754 capture_nonlocked_.split_rate,
1755 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001756 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001757}
1758
Per Åhgren4011de02019-12-03 11:48:48 +00001759void AudioProcessingImpl::InitializeHighPassFilter() {
Per Åhgrenb8106462019-12-04 08:34:12 +01001760 bool high_pass_filter_needed_by_aec =
1761 config_.echo_canceller.enabled &&
1762 config_.echo_canceller.enforce_high_pass_filtering &&
1763 !config_.echo_canceller.mobile_mode;
1764 if (submodule_states_.HighPassFilteringRequired() ||
1765 high_pass_filter_needed_by_aec) {
saza1d600522019-10-18 13:29:43 +02001766 submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001767 } else {
saza1d600522019-10-18 13:29:43 +02001768 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001769 }
1770}
alessiob3ec96df2017-05-22 06:57:06 -07001771
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001772void AudioProcessingImpl::InitializeVoiceDetector() {
1773 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001774 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001775 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1776 } else {
saza1d600522019-10-18 13:29:43 +02001777 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001778 }
1779}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001780void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001781 bool use_echo_controller =
1782 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001783 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001784
1785 if (use_echo_controller) {
1786 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001787 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001788 submodules_.echo_controller = echo_control_factory_->Create(
1789 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001790 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001791 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001792 EchoCanceller3Config config =
1793 use_setup_specific_default_aec3_config_
1794 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1795 num_proc_channels())
1796 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001797 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001798 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001799 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001800 }
1801
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001802 // Setup the storage for returning the linear AEC output.
1803 if (config_.echo_canceller.export_linear_aec_output) {
1804 constexpr int kLinearOutputRateHz = 16000;
1805 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1806 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1807 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1808 } else {
1809 capture_.linear_aec_output.reset();
1810 }
1811
Per Åhgren200feba2019-03-06 04:16:46 +01001812 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001813
saza1d600522019-10-18 13:29:43 +02001814 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001815 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001816 return;
peahe0eae3c2016-12-14 01:16:23 -08001817 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001818
saza1d600522019-10-18 13:29:43 +02001819 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001820 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001821 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001822
1823 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001824 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001825 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001826 return;
1827 }
1828
1829 if (config_.echo_canceller.mobile_mode) {
1830 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001831 size_t max_element_size =
1832 std::max(static_cast<size_t>(1),
1833 kMaxAllowedValuesOfSamplesPerBand *
1834 EchoControlMobileImpl::NumCancellersRequired(
1835 num_output_channels(), num_reverse_channels()));
1836
1837 std::vector<int16_t> template_queue_element(max_element_size);
1838
1839 aecm_render_signal_queue_.reset(
1840 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1841 kMaxNumFramesToBuffer, template_queue_element,
1842 RenderQueueItemVerifier<int16_t>(max_element_size)));
1843
1844 aecm_render_queue_buffer_.resize(max_element_size);
1845 aecm_capture_queue_buffer_.resize(max_element_size);
1846
saza1d600522019-10-18 13:29:43 +02001847 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001848
saza1d600522019-10-18 13:29:43 +02001849 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1850 num_reverse_channels(),
1851 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02001852 return;
1853 }
1854
saza1d600522019-10-18 13:29:43 +02001855 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001856 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08001857}
peah8271d042016-11-22 07:24:52 -08001858
alessiob3ec96df2017-05-22 06:57:06 -07001859void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001860 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001861 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001862 }
1863}
1864
saza0bad15f2019-10-16 11:46:11 +02001865void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001866 submodules_.legacy_noise_suppressor.reset();
1867 submodules_.noise_suppressor.reset();
1868
saza0bad15f2019-10-16 11:46:11 +02001869 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001870 const bool use_legacy_ns =
1871 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1872
1873 if (!use_legacy_ns) {
1874 auto map_level =
1875 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1876 using NoiseSuppresionConfig =
1877 AudioProcessing::Config::NoiseSuppression;
1878 switch (level) {
1879 case NoiseSuppresionConfig::kLow:
1880 return NsConfig::SuppressionLevel::k6dB;
1881 case NoiseSuppresionConfig::kModerate:
1882 return NsConfig::SuppressionLevel::k12dB;
1883 case NoiseSuppresionConfig::kHigh:
1884 return NsConfig::SuppressionLevel::k18dB;
1885 case NoiseSuppresionConfig::kVeryHigh:
1886 return NsConfig::SuppressionLevel::k21dB;
1887 default:
1888 RTC_NOTREACHED();
1889 }
1890 };
1891
1892 NsConfig cfg;
1893 cfg.target_level = map_level(config_.noise_suppression.level);
1894 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1895 cfg, proc_sample_rate_hz(), num_proc_channels());
1896 } else {
1897 auto ns_level =
1898 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1899 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1900 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1901 }
saza0bad15f2019-10-16 11:46:11 +02001902 }
1903}
1904
Alex Loikob5c9a792018-04-16 16:31:22 +02001905void AudioProcessingImpl::InitializePreAmplifier() {
1906 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001907 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001908 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1909 } else {
saza1d600522019-10-18 13:29:43 +02001910 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001911 }
1912}
1913
ivoc9f4a4a02016-10-28 05:39:16 -07001914void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001915 RTC_DCHECK(submodules_.echo_detector);
1916 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001917 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001918 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001919}
1920
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001921void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001922 if (submodules_.capture_analyzer) {
1923 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1924 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001925 }
1926}
1927
Sam Zackrisson0beac582017-09-25 12:04:02 +02001928void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001929 if (submodules_.capture_post_processor) {
1930 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001931 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001932 }
1933}
1934
Alex Loiko5825aa62017-12-18 16:02:40 +01001935void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02001936 if (submodules_.render_pre_processor) {
1937 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01001938 formats_.render_processing_format.sample_rate_hz(),
1939 formats_.render_processing_format.num_channels());
1940 }
1941}
1942
Per Åhgrenea4c5df2019-05-03 09:00:08 +02001943void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001944
aleloi868f32f2017-05-23 07:20:05 -07001945void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1946 if (!aec_dump_) {
1947 return;
1948 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001949
1950 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07001951 // TODO(peah): Add semicolon-separated concatenations of experiment
1952 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001953 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1954 experiments_description += "AgcClippingLevelExperiment;";
1955 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001956 if (capture_nonlocked_.echo_controller_enabled) {
1957 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001958 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001959 if (config_.gain_controller2.enabled) {
1960 experiments_description += "GainController2;";
1961 }
aleloi868f32f2017-05-23 07:20:05 -07001962
1963 InternalAPMConfig apm_config;
1964
Per Åhgren200feba2019-03-06 04:16:46 +01001965 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001966 apm_config.aec_delay_agnostic_enabled = false;
1967 apm_config.aec_extended_filter_enabled = false;
1968 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07001969
saza1d600522019-10-18 13:29:43 +02001970 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07001971 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02001972 submodules_.echo_control_mobile &&
1973 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001974 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02001975 submodules_.echo_control_mobile
1976 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001977 : 0;
aleloi868f32f2017-05-23 07:20:05 -07001978
saza1d600522019-10-18 13:29:43 +02001979 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
1980 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07001981 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02001982 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01001983 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07001984
1985 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1986
saza0bad15f2019-10-16 11:46:11 +02001987 apm_config.ns_enabled = config_.noise_suppression.enabled;
1988 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07001989
1990 apm_config.transient_suppression_enabled =
1991 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001992 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001993 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1994 apm_config.pre_amplifier_fixed_gain_factor =
1995 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001996
1997 if (!forced && apm_config == apm_config_for_aec_dump_) {
1998 return;
1999 }
2000 aec_dump_->WriteConfig(apm_config);
2001 apm_config_for_aec_dump_ = apm_config;
2002}
2003
2004void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2005 const float* const* src) {
2006 RTC_DCHECK(aec_dump_);
2007 WriteAecDumpConfigMessage(false);
2008
2009 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2010 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2011 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002012 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002013 RecordAudioProcessingState();
2014}
2015
2016void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2017 const AudioFrame& capture_frame) {
2018 RTC_DCHECK(aec_dump_);
2019 WriteAecDumpConfigMessage(false);
2020
2021 aec_dump_->AddCaptureStreamInput(capture_frame);
2022 RecordAudioProcessingState();
2023}
2024
2025void AudioProcessingImpl::RecordProcessedCaptureStream(
2026 const float* const* processed_capture_stream) {
2027 RTC_DCHECK(aec_dump_);
2028
2029 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2030 const size_t num_channels =
2031 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002032 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2033 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002034 aec_dump_->WriteCaptureStreamMessage();
2035}
2036
2037void AudioProcessingImpl::RecordProcessedCaptureStream(
2038 const AudioFrame& processed_capture_frame) {
2039 RTC_DCHECK(aec_dump_);
2040
2041 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2042 aec_dump_->WriteCaptureStreamMessage();
2043}
2044
2045void AudioProcessingImpl::RecordAudioProcessingState() {
2046 RTC_DCHECK(aec_dump_);
2047 AecDump::AudioProcessingState audio_proc_state;
2048 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002049 audio_proc_state.drift = 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002050 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002051 audio_proc_state.keypress = capture_.key_pressed;
2052 aec_dump_->AddAudioProcessingState(audio_proc_state);
2053}
2054
kwiberg83ffe452016-08-29 14:46:07 -07002055AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002056 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002057 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002058 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002059 output_will_be_muted(false),
2060 key_pressed(false),
2061 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002062 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002063 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002064 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002065 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002066 prev_pre_amp_gain(-1.f),
2067 playout_volume(-1),
2068 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002069
2070AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2071
Per Åhgrena1351272019-08-15 12:15:46 +02002072void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2073 const float* const* data,
2074 const StreamConfig& stream_config) {
2075 if (stream_config.has_keyboard()) {
2076 keyboard_data = data[stream_config.num_channels()];
2077 } else {
2078 keyboard_data = NULL;
2079 }
2080 num_keyboard_frames = stream_config.num_frames();
2081}
2082
kwiberg83ffe452016-08-29 14:46:07 -07002083AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2084
2085AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2086
niklase@google.com470e71d2011-07-07 08:21:25 +00002087} // namespace webrtc