blob: b6e79beb78456b576d13f58498597051cd8cc765 [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 Åhgrenc8626b62019-08-23 15:49:51 +020078// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020079int SuitableProcessRate(int minimum_rate,
80 int max_splitting_rate,
81 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020082 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020083 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020084 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070085 if (rate >= uppermost_native_rate) {
86 return uppermost_native_rate;
87 }
88 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070089 return rate;
90 }
91 }
peah2ace3f92016-09-10 04:42:27 -070092 RTC_NOTREACHED();
93 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -070094}
95
Sam Zackrisson23513132019-01-11 15:10:32 +010096NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
97 AudioProcessing::Config::NoiseSuppression::Level level) {
98 using NsConfig = AudioProcessing::Config::NoiseSuppression;
99 switch (level) {
100 case NsConfig::kLow:
saza0bad15f2019-10-16 11:46:11 +0200101 return NoiseSuppression::Level::kLow;
Sam Zackrisson23513132019-01-11 15:10:32 +0100102 case NsConfig::kModerate:
saza0bad15f2019-10-16 11:46:11 +0200103 return NoiseSuppression::Level::kModerate;
Sam Zackrisson23513132019-01-11 15:10:32 +0100104 case NsConfig::kHigh:
saza0bad15f2019-10-16 11:46:11 +0200105 return NoiseSuppression::Level::kHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100106 case NsConfig::kVeryHigh:
saza0bad15f2019-10-16 11:46:11 +0200107 return NoiseSuppression::Level::kVeryHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100108 default:
109 RTC_NOTREACHED();
110 }
111}
112
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100113GainControl::Mode Agc1ConfigModeToInterfaceMode(
114 AudioProcessing::Config::GainController1::Mode mode) {
115 using Agc1Config = AudioProcessing::Config::GainController1;
116 switch (mode) {
117 case Agc1Config::kAdaptiveAnalog:
118 return GainControl::kAdaptiveAnalog;
119 case Agc1Config::kAdaptiveDigital:
120 return GainControl::kAdaptiveDigital;
121 case Agc1Config::kFixedDigital:
122 return GainControl::kFixedDigital;
123 }
124}
125
peah9e6a2902017-05-15 07:19:21 -0700126// Maximum lengths that frame of samples being passed from the render side to
127// the capture side can have (does not apply to AEC3).
128static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
129static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
130
peah764e3642016-10-22 05:04:30 -0700131// Maximum number of frames to buffer in the render queue.
132// TODO(peah): Decrease this once we properly handle hugely unbalanced
133// reverse and forward call numbers.
134static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700135} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000136
137// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000138static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000139
saza1d600522019-10-18 13:29:43 +0200140AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100141 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200142 bool render_pre_processor_enabled,
143 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100144 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200145 render_pre_processor_enabled_(render_pre_processor_enabled),
146 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700147
saza1d600522019-10-18 13:29:43 +0200148bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200149 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700150 bool echo_canceller_enabled,
151 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700152 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700153 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700154 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700155 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200156 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200157 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200158 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700159 bool transient_suppressor_enabled) {
160 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200161 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700162 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
163 changed |=
164 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700165 changed |=
166 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700167 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
168 changed |=
peah2ace3f92016-09-10 04:42:27 -0700169 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200170 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200171 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200172 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200173 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700174 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
175 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200176 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700177 echo_canceller_enabled_ = echo_canceller_enabled;
178 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700179 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700180 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700181 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700182 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200183 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200184 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200185 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700186 transient_suppressor_enabled_ = transient_suppressor_enabled;
187 }
188
189 changed |= first_update_;
190 first_update_ = false;
191 return changed;
192}
193
saza1d600522019-10-18 13:29:43 +0200194bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700195 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200196 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700197}
198
saza1d600522019-10-18 13:29:43 +0200199bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
200 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200201 // If echo controller is present, assume it performs active processing.
202 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
203}
204
saza1d600522019-10-18 13:29:43 +0200205bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200206 bool ec_processing_active) const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200207 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700208 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200209 adaptive_gain_controller_enabled_ ||
210 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700211}
212
saza1d600522019-10-18 13:29:43 +0200213bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700214 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200215 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
216 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700217}
218
saza1d600522019-10-18 13:29:43 +0200219bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200220 return capture_analyzer_enabled_;
221}
222
saza1d600522019-10-18 13:29:43 +0200223bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700224 const {
225 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800226 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200227 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700228}
229
saza1d600522019-10-18 13:29:43 +0200230bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100231 const {
232 return render_pre_processor_enabled_;
233}
234
saza1d600522019-10-18 13:29:43 +0200235bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700236 const {
peah2ace3f92016-09-10 04:42:27 -0700237 return false;
peah2ace3f92016-09-10 04:42:27 -0700238}
239
saza1d600522019-10-18 13:29:43 +0200240bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200241 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
242 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
243}
244
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100245AudioProcessingBuilder::AudioProcessingBuilder() = default;
246AudioProcessingBuilder::~AudioProcessingBuilder() = default;
247
248AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
249 std::unique_ptr<CustomProcessing> capture_post_processing) {
250 capture_post_processing_ = std::move(capture_post_processing);
251 return *this;
252}
253
254AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
255 std::unique_ptr<CustomProcessing> render_pre_processing) {
256 render_pre_processing_ = std::move(render_pre_processing);
257 return *this;
258}
259
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200260AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
261 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
262 capture_analyzer_ = std::move(capture_analyzer);
263 return *this;
264}
265
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100266AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
267 std::unique_ptr<EchoControlFactory> echo_control_factory) {
268 echo_control_factory_ = std::move(echo_control_factory);
269 return *this;
270}
271
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100272AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200273 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100274 echo_detector_ = std::move(echo_detector);
275 return *this;
276}
277
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100278AudioProcessing* AudioProcessingBuilder::Create() {
279 webrtc::Config config;
280 return Create(config);
281}
282
283AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100284 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
285 config, std::move(capture_post_processing_),
286 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200287 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100288 if (apm->Initialize() != AudioProcessing::kNoError) {
289 delete apm;
290 apm = nullptr;
291 }
292 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100293}
294
peah88ac8532016-09-12 16:47:25 -0700295AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200296 : AudioProcessingImpl(config,
297 /*capture_post_processor=*/nullptr,
298 /*render_pre_processor=*/nullptr,
299 /*echo_control_factory=*/nullptr,
300 /*echo_detector=*/nullptr,
301 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000302
Per Åhgren13735822018-02-12 21:42:56 +0100303int AudioProcessingImpl::instance_count_ = 0;
304
Sam Zackrisson0beac582017-09-25 12:04:02 +0200305AudioProcessingImpl::AudioProcessingImpl(
306 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100307 std::unique_ptr<CustomProcessing> capture_post_processor,
308 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200309 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200310 rtc::scoped_refptr<EchoDetector> echo_detector,
311 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100312 : data_dumper_(
313 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgren0cbb58e2019-10-29 22:59:44 +0100314 enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200315 capture_runtime_settings_(kRuntimeSettingQueueSize),
316 render_runtime_settings_(kRuntimeSettingQueueSize),
317 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
318 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200319 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200320 submodule_states_(!!capture_post_processor,
321 !!render_pre_processor,
322 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200323 submodules_(std::move(capture_post_processor),
324 std::move(render_pre_processor),
325 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100326 std::move(capture_analyzer)),
327 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
328 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000329#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Per Åhgren3daedb62019-11-22 12:11:40 +0100330 /* enabled= */ false,
331 /* enabled_agc2_level_estimator= */ false,
332 /* digital_adaptive_disabled= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000333#else
Per Åhgren3daedb62019-11-22 12:11:40 +0100334 config.Get<ExperimentalAgc>().enabled,
335 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
336 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000337#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200338 !field_trial::IsEnabled(
339 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
340 !field_trial::IsEnabled(
341 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700342#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200343 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700344#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200345 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700346#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200347 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200348 RTC_LOG(LS_INFO) << "Injected APM submodules:"
349 << "\nEcho control factory: " << !!echo_control_factory_
350 << "\nEcho detector: " << !!submodules_.echo_detector
351 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
352 << "\nCapture post processor: "
353 << !!submodules_.capture_post_processor
354 << "\nRender pre processor: "
355 << !!submodules_.render_pre_processor;
356
Sam Zackrisson421c8592019-02-11 13:39:46 +0100357 // Mark Echo Controller enabled if a factory is injected.
358 capture_nonlocked_.echo_controller_enabled =
359 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000360
saza1d600522019-10-18 13:29:43 +0200361 submodules_.gain_control.reset(new GainControlImpl());
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200362
Sam Zackrisson421c8592019-02-11 13:39:46 +0100363 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200364 if (!submodules_.echo_detector) {
365 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100366 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800367 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000368
Sam Zackrisson421c8592019-02-11 13:39:46 +0100369 // TODO(alessiob): Move the injected gain controller once injection is
370 // implemented.
saza1d600522019-10-18 13:29:43 +0200371 submodules_.gain_controller2.reset(new GainController2());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100372
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000373 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000374}
375
Per Åhgren0e3198e2019-11-18 08:52:22 +0100376AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000377
niklase@google.com470e71d2011-07-07 08:21:25 +0000378int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800379 // Run in a single-threaded manner during initialization.
380 rtc::CritScope cs_render(&crit_render_);
381 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000382 return InitializeLocked();
383}
384
peahde65ddc2016-09-16 15:02:15 -0700385int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
386 int capture_output_sample_rate_hz,
387 int render_input_sample_rate_hz,
388 ChannelLayout capture_input_layout,
389 ChannelLayout capture_output_layout,
390 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700391 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700392 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
393 LayoutHasKeyboard(capture_input_layout)},
394 {capture_output_sample_rate_hz,
395 ChannelsFromLayout(capture_output_layout),
396 LayoutHasKeyboard(capture_output_layout)},
397 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
398 LayoutHasKeyboard(render_input_layout)},
399 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
400 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700401
402 return Initialize(processing_config);
403}
404
405int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800406 // Run in a single-threaded manner during initialization.
407 rtc::CritScope cs_render(&crit_render_);
408 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700409 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000410}
411
peahdf3efa82015-11-28 12:35:15 -0800412int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800413 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800414 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200415 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800416 return kNoError;
417 }
peahdf3efa82015-11-28 12:35:15 -0800418
419 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800420 return InitializeLocked(processing_config);
421}
422
niklase@google.com470e71d2011-07-07 08:21:25 +0000423int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200424 UpdateActiveSubmoduleStates();
425
Per Åhgrend47941e2019-08-22 11:51:13 +0200426 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800427 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200428 ? formats_.render_processing_format.sample_rate_hz()
429 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800430 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
431 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200432 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800433 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200434 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700435 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200436 render_audiobuffer_sample_rate_hz,
437 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700438 if (formats_.api_format.reverse_input_stream() !=
439 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800440 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800441 formats_.api_format.reverse_input_stream().num_channels(),
442 formats_.api_format.reverse_input_stream().num_frames(),
443 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800444 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700445 } else {
peahdf3efa82015-11-28 12:35:15 -0800446 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700447 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700448 } else {
peahdf3efa82015-11-28 12:35:15 -0800449 render_.render_audio.reset(nullptr);
450 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700451 }
peahce4d9152017-05-19 01:28:05 -0700452
Per Åhgrend47941e2019-08-22 11:51:13 +0200453 capture_.capture_audio.reset(new AudioBuffer(
454 formats_.api_format.input_stream().sample_rate_hz(),
455 formats_.api_format.input_stream().num_channels(),
456 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
457 formats_.api_format.output_stream().num_channels(),
458 formats_.api_format.output_stream().sample_rate_hz(),
459 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000460
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200461 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
462 formats_.api_format.output_stream().sample_rate_hz() &&
463 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
464 capture_.capture_fullband_audio.reset(
465 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
466 formats_.api_format.input_stream().num_channels(),
467 formats_.api_format.output_stream().sample_rate_hz(),
468 formats_.api_format.output_stream().num_channels(),
469 formats_.api_format.output_stream().sample_rate_hz(),
470 formats_.api_format.output_stream().num_channels()));
471 } else {
472 capture_.capture_fullband_audio.reset();
473 }
474
peah764e3642016-10-22 05:04:30 -0700475 AllocateRenderQueue();
476
saza1d600522019-10-18 13:29:43 +0200477 submodules_.gain_control->Initialize(num_proc_channels(),
478 proc_sample_rate_hz());
Per Åhgren3daedb62019-11-22 12:11:40 +0100479 if (constants_.use_experimental_agc) {
480 if (!submodules_.agc_manager.get() ||
481 submodules_.agc_manager->num_channels() !=
482 static_cast<int>(num_proc_channels()) ||
483 submodules_.agc_manager->sample_rate_hz() !=
484 capture_nonlocked_.split_rate) {
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100485 int stream_analog_level = -1;
486 const bool re_creation = !!submodules_.agc_manager;
487 if (re_creation) {
488 stream_analog_level = submodules_.agc_manager->stream_analog_level();
489 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100490 submodules_.agc_manager.reset(new AgcManagerDirect(
491 num_proc_channels(), constants_.agc_startup_min_volume,
492 constants_.agc_clipped_level_min,
493 constants_.use_experimental_agc_agc2_level_estimation,
494 constants_.use_experimental_agc_agc2_digital_adaptive,
495 capture_nonlocked_.split_rate));
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100496 if (re_creation) {
497 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
498 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100499 }
saza1d600522019-10-18 13:29:43 +0200500 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 12:11:40 +0100501 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 08:52:22 +0100502 submodules_.gain_control.get());
saza1d600522019-10-18 13:29:43 +0200503 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 15:02:15 -0700504 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200505 InitializeTransient();
Per Åhgren0aefbf02019-08-23 21:29:17 +0200506 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200507 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700508 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200509 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700510 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200511 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200512 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200513 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100514 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800515
aleloi868f32f2017-05-23 07:20:05 -0700516 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200517 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700518 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000519 return kNoError;
520}
521
Michael Graczyk86c6d332015-07-23 11:41:39 -0700522int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200523 UpdateActiveSubmoduleStates();
524
Michael Graczyk86c6d332015-07-23 11:41:39 -0700525 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700526 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
527 return kBadSampleRateError;
528 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000529 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700530
Peter Kasting69558702016-01-12 16:26:35 -0800531 const size_t num_in_channels = config.input_stream().num_channels();
532 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700533
534 // Need at least one input channel.
535 // Need either one output channel or as many outputs as there are inputs.
536 if (num_in_channels == 0 ||
537 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700538 return kBadNumberChannelsError;
539 }
540
peahdf3efa82015-11-28 12:35:15 -0800541 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000542
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200543 // Choose maximum rate to use for the split filtering.
544 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
545 config_.pipeline.maximum_internal_processing_rate == 32000);
546 int max_splitting_rate = 48000;
547 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
548 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
549 }
550
Per Åhgrenc8626b62019-08-23 15:49:51 +0200551 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700552 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700553 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200554 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700555 submodule_states_.CaptureMultiBandSubModulesActive() ||
556 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200557 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000558
peahde65ddc2016-09-16 15:02:15 -0700559 capture_nonlocked_.capture_processing_format =
560 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700561
peah2ce640f2017-04-07 03:57:48 -0700562 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200563 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200564 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700565 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
566 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200567 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700568 submodule_states_.CaptureMultiBandSubModulesActive() ||
569 submodule_states_.RenderMultiBandSubModulesActive());
570 } else {
571 render_processing_rate = capture_processing_rate;
572 }
573
peahde65ddc2016-09-16 15:02:15 -0700574 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700575 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700576 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
577 kSampleRate8kHz) {
578 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000579 } else {
peahde65ddc2016-09-16 15:02:15 -0700580 render_processing_rate =
581 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000582 }
583
Per Åhgrenc8626b62019-08-23 15:49:51 +0200584 RTC_DCHECK_NE(8000, render_processing_rate);
585
peahce4d9152017-05-19 01:28:05 -0700586 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200587 // By default, downmix the render stream to mono for analysis. This has been
588 // demonstrated to work well for AEC in most practical scenarios.
589 const bool experimental_multi_channel_render =
590 config_.pipeline.experimental_multi_channel &&
591 constants_.experimental_multi_channel_render_support;
592 int render_processing_num_channels =
593 experimental_multi_channel_render
594 ? formats_.api_format.reverse_input_stream().num_channels()
595 : 1;
596 formats_.render_processing_format =
597 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700598 } else {
599 formats_.render_processing_format = StreamConfig(
600 formats_.api_format.reverse_input_stream().sample_rate_hz(),
601 formats_.api_format.reverse_input_stream().num_channels());
602 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000603
peahde65ddc2016-09-16 15:02:15 -0700604 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
605 kSampleRate32kHz ||
606 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
607 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800608 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000609 } else {
peahdf3efa82015-11-28 12:35:15 -0800610 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700611 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000612 }
613
614 return InitializeLocked();
615}
616
peah88ac8532016-09-12 16:47:25 -0700617void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200618 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
619
peah88ac8532016-09-12 16:47:25 -0700620 // Run in a single-threaded manner when applying the settings.
621 rtc::CritScope cs_render(&crit_render_);
622 rtc::CritScope cs_capture(&crit_capture_);
623
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200624 const bool pipeline_config_changed =
625 config_.pipeline.experimental_multi_channel !=
626 config.pipeline.experimental_multi_channel;
627
Per Åhgren200feba2019-03-06 04:16:46 +0100628 const bool aec_config_changed =
629 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
630 config_.echo_canceller.use_legacy_aec !=
631 config.echo_canceller.use_legacy_aec ||
632 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
633 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
634 config_.echo_canceller.legacy_moderate_suppression_level !=
635 config.echo_canceller.legacy_moderate_suppression_level);
636
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100637 const bool agc1_config_changed =
638 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
639 config_.gain_controller1.mode != config.gain_controller1.mode ||
640 config_.gain_controller1.target_level_dbfs !=
641 config.gain_controller1.target_level_dbfs ||
642 config_.gain_controller1.compression_gain_db !=
643 config.gain_controller1.compression_gain_db ||
644 config_.gain_controller1.enable_limiter !=
645 config.gain_controller1.enable_limiter ||
646 config_.gain_controller1.analog_level_minimum !=
647 config.gain_controller1.analog_level_minimum ||
648 config_.gain_controller1.analog_level_maximum !=
649 config.gain_controller1.analog_level_maximum;
650
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200651 const bool voice_detection_config_changed =
652 config_.voice_detection.enabled != config.voice_detection.enabled;
653
saza0bad15f2019-10-16 11:46:11 +0200654 const bool ns_config_changed =
655 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
656 config_.noise_suppression.level != config.noise_suppression.level;
657
Yves Gerey499bc6c2018-10-10 18:29:07 +0200658 config_ = config;
659
Per Åhgren200feba2019-03-06 04:16:46 +0100660 if (aec_config_changed) {
661 InitializeEchoController();
662 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200663
saza0bad15f2019-10-16 11:46:11 +0200664 if (ns_config_changed) {
665 InitializeNoiseSuppressor();
666 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100667
Per Åhgren0aefbf02019-08-23 21:29:17 +0200668 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800669
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100670 if (agc1_config_changed) {
671 ApplyAgc1Config(config_.gain_controller1);
672 }
673
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100674 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700675 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100676 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
677 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100678 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100679 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700680 config_.gain_controller2 = AudioProcessing::Config::GainController2();
681 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200682 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200683 InitializePreAmplifier();
saza1d600522019-10-18 13:29:43 +0200684 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100685
saza1d600522019-10-18 13:29:43 +0200686 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
687 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100688 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100689
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200690 if (voice_detection_config_changed) {
691 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100692 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200693
694 // Reinitialization must happen after all submodule configuration to avoid
695 // additional reinitializations on the next capture / render processing call.
696 if (pipeline_config_changed) {
697 InitializeLocked(formats_.api_format);
698 }
peah88ac8532016-09-12 16:47:25 -0700699}
700
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100701void AudioProcessingImpl::ApplyAgc1Config(
702 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100703 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100704 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100705
Per Åhgren0e3198e2019-11-18 08:52:22 +0100706 if (!submodules_.agc_manager) {
707 error = submodules_.gain_control->set_mode(
708 Agc1ConfigModeToInterfaceMode(config.mode));
709 RTC_DCHECK_EQ(kNoError, error);
710 error = submodules_.gain_control->set_target_level_dbfs(
711 config.target_level_dbfs);
712 RTC_DCHECK_EQ(kNoError, error);
713 error = submodules_.gain_control->set_compression_gain_db(
714 config.compression_gain_db);
715 RTC_DCHECK_EQ(kNoError, error);
716 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
717 RTC_DCHECK_EQ(kNoError, error);
718 error = submodules_.gain_control->set_analog_level_limits(
719 config.analog_level_minimum, config.analog_level_maximum);
720 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100721 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100722}
723
peah88ac8532016-09-12 16:47:25 -0700724void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800725 // Run in a single-threaded manner when setting the extra options.
726 rtc::CritScope cs_render(&crit_render_);
727 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000728
Per Åhgrenf204faf2019-04-25 15:18:06 +0200729 capture_nonlocked_.use_aec2_extended_filter =
730 config.Get<ExtendedFilter>().enabled;
731 capture_nonlocked_.use_aec2_delay_agnostic =
732 config.Get<DelayAgnostic>().enabled;
733 capture_nonlocked_.use_aec2_refined_adaptive_filter =
734 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800735
peahdf3efa82015-11-28 12:35:15 -0800736 if (capture_.transient_suppressor_enabled !=
737 config.Get<ExperimentalNs>().enabled) {
738 capture_.transient_suppressor_enabled =
739 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000740 InitializeTransient();
741 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000742}
743
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000744int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800745 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700746 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000747}
748
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200749int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
750 return capture_.capture_fullband_audio
751 ? capture_.capture_fullband_audio->num_frames() * 100
752 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
753}
754
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000755int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800756 // Used as callback from submodules, hence locking is not allowed.
757 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000758}
759
Peter Kasting69558702016-01-12 16:26:35 -0800760size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800761 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700762 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000763}
764
Peter Kasting69558702016-01-12 16:26:35 -0800765size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800766 // Used as callback from submodules, hence locking is not allowed.
767 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000768}
769
Peter Kasting69558702016-01-12 16:26:35 -0800770size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800771 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200772 const bool experimental_multi_channel_capture =
773 config_.pipeline.experimental_multi_channel &&
774 constants_.experimental_multi_channel_capture_support;
775 if (capture_nonlocked_.echo_controller_enabled &&
776 !experimental_multi_channel_capture) {
777 return 1;
778 }
779 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800780}
781
Peter Kasting69558702016-01-12 16:26:35 -0800782size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800783 // Used as callback from submodules, hence locking is not allowed.
784 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000785}
786
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000787void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800788 rtc::CritScope cs(&crit_capture_);
789 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200790 if (submodules_.agc_manager.get()) {
791 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000792 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000793}
794
Alessio Bazzicac054e782018-04-16 12:10:09 +0200795void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200796 switch (setting.type()) {
797 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100798 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200799 render_runtime_settings_enqueuer_.Enqueue(setting);
800 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200801 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100802 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200803 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100804 capture_runtime_settings_enqueuer_.Enqueue(setting);
805 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200806 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200807 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100808 render_runtime_settings_enqueuer_.Enqueue(setting);
809 return;
810 case RuntimeSetting::Type::kNotSpecified:
811 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200812 return;
813 }
814 // The language allows the enum to have a non-enumerator
815 // value. Check that this doesn't happen.
816 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200817}
818
819AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
820 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200821 : runtime_settings_(*runtime_settings) {
822 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200823}
824
825AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
826 default;
827
828void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
829 RuntimeSetting setting) {
830 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200831 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200832 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200833 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200834 RTC_LOG(LS_ERROR)
835 << "The runtime settings queue is full. Oldest setting discarded.";
836 }
837 if (remaining_attempts == 0)
838 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
839}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000840
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000841int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700842 const StreamConfig& input_config,
843 const StreamConfig& output_config,
844 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800845 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800846 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700847 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800848 {
849 // Acquire the capture lock in order to safely call the function
850 // that retrieves the render side data. This function accesses apm
851 // getters that need the capture lock held when being called.
852 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700853 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800854
855 if (!src || !dest) {
856 return kNullPointerError;
857 }
858
859 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700860 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000861 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000862
Oskar Sundbom4b276482019-05-23 14:28:00 +0200863 if (processing_config.input_stream() != input_config) {
864 processing_config.input_stream() = input_config;
865 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800866 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200867
868 if (processing_config.output_stream() != output_config) {
869 processing_config.output_stream() = output_config;
870 reinitialization_required = true;
871 }
872
873 if (reinitialization_required) {
874 // Reinitialize.
875 rtc::CritScope cs_render(&crit_render_);
876 rtc::CritScope cs_capture(&crit_capture_);
877 RETURN_ON_ERR(InitializeLocked(processing_config));
878 }
879
peahdf3efa82015-11-28 12:35:15 -0800880 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700881 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
882 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000883
aleloi868f32f2017-05-23 07:20:05 -0700884 if (aec_dump_) {
885 RecordUnprocessedCaptureStream(src);
886 }
887
Per Åhgrena1351272019-08-15 12:15:46 +0200888 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800889 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200890 if (capture_.capture_fullband_audio) {
891 capture_.capture_fullband_audio->CopyFrom(
892 src, formats_.api_format.input_stream());
893 }
peahde65ddc2016-09-16 15:02:15 -0700894 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200895 if (capture_.capture_fullband_audio) {
896 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
897 dest);
898 } else {
899 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
900 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000901
aleloi868f32f2017-05-23 07:20:05 -0700902 if (aec_dump_) {
903 RecordProcessedCaptureStream(dest);
904 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000905 return kNoError;
906}
907
Alex Loiko73ec0192018-05-15 10:52:28 +0200908void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200909 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200910 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200911 if (aec_dump_) {
912 aec_dump_->WriteRuntimeSetting(setting);
913 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200914 switch (setting.type()) {
915 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200916 if (config_.pre_amplifier.enabled) {
917 float value;
918 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200919 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200920 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200921 }
922 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200923 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100924 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100925 if (!submodules_.agc_manager) {
926 float value;
927 setting.GetFloat(&value);
928 int int_value = static_cast<int>(value + .5f);
929 config_.gain_controller1.compression_gain_db = int_value;
930 int error =
931 submodules_.gain_control->set_compression_gain_db(int_value);
932 RTC_DCHECK_EQ(kNoError, error);
933 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100934 break;
935 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200936 case RuntimeSetting::Type::kCaptureFixedPostGain: {
937 if (config_.gain_controller2.enabled) {
938 float value;
939 setting.GetFloat(&value);
940 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200941 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200942 }
943 break;
944 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200945 case RuntimeSetting::Type::kPlayoutVolumeChange: {
946 int value;
947 setting.GetInt(&value);
948 capture_.playout_volume = value;
949 break;
950 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100951 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
952 RTC_NOTREACHED();
953 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200954 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
955 RTC_NOTREACHED();
956 break;
957 case RuntimeSetting::Type::kNotSpecified:
958 RTC_NOTREACHED();
959 break;
960 }
961 }
962}
963
964void AudioProcessingImpl::HandleRenderRuntimeSettings() {
965 RuntimeSetting setting;
966 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200967 if (aec_dump_) {
968 aec_dump_->WriteRuntimeSetting(setting);
969 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200970 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100971 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100972 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200973 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200974 if (submodules_.render_pre_processor) {
975 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200976 }
977 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100978 case RuntimeSetting::Type::kCapturePreGain: // fall-through
979 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200980 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200981 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200982 RTC_NOTREACHED();
983 break;
984 }
985 }
986}
987
peah9e6a2902017-05-15 07:19:21 -0700988void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800989 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700990
991 // Insert the samples into the queue.
saza1d600522019-10-18 13:29:43 +0200992 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +0200993 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200994 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
995 num_reverse_channels(),
996 &aec_render_queue_buffer_);
997
Per Åhgrenf204faf2019-04-25 15:18:06 +0200998 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
999 // The data queue is full and needs to be emptied.
1000 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001001
Per Åhgrenf204faf2019-04-25 15:18:06 +02001002 // Retry the insert (should always work).
1003 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1004 RTC_DCHECK(result);
1005 }
peaha0624602016-10-25 04:45:24 -07001006 }
1007
saza1d600522019-10-18 13:29:43 +02001008 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001009 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1010 num_reverse_channels(),
1011 &aecm_render_queue_buffer_);
1012 RTC_DCHECK(aecm_render_signal_queue_);
1013 // Insert the samples into the queue.
1014 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1015 // The data queue is full and needs to be emptied.
1016 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001017
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001018 // Retry the insert (should always work).
1019 bool result =
1020 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1021 RTC_DCHECK(result);
1022 }
peah764e3642016-10-22 05:04:30 -07001023 }
peah701d6282016-10-25 05:42:20 -07001024
Per Åhgren0e3198e2019-11-18 08:52:22 +01001025 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001026 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001027 // Insert the samples into the queue.
1028 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1029 // The data queue is full and needs to be emptied.
1030 EmptyQueuedRenderAudio();
1031
1032 // Retry the insert (should always work).
1033 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1034 RTC_DCHECK(result);
1035 }
1036 }
peah9e6a2902017-05-15 07:19:21 -07001037}
ivoc9f4a4a02016-10-28 05:39:16 -07001038
peah9e6a2902017-05-15 07:19:21 -07001039void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001040 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1041
1042 // Insert the samples into the queue.
1043 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1044 // The data queue is full and needs to be emptied.
1045 EmptyQueuedRenderAudio();
1046
1047 // Retry the insert (should always work).
1048 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1049 RTC_DCHECK(result);
1050 }
peah764e3642016-10-22 05:04:30 -07001051}
1052
1053void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001054 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001055 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001056
ivoc9f4a4a02016-10-28 05:39:16 -07001057 const size_t new_red_render_queue_element_max_size =
1058 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1059
peaha0624602016-10-25 04:45:24 -07001060 // Reallocate the queues if the queue item sizes are too small to fit the
1061 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001062
1063 if (agc_render_queue_element_max_size_ <
1064 new_agc_render_queue_element_max_size) {
1065 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1066
1067 std::vector<int16_t> template_queue_element(
1068 agc_render_queue_element_max_size_);
1069
1070 agc_render_signal_queue_.reset(
1071 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1072 kMaxNumFramesToBuffer, template_queue_element,
1073 RenderQueueItemVerifier<int16_t>(
1074 agc_render_queue_element_max_size_)));
1075
1076 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1077 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1078 } else {
1079 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001080 }
ivoc9f4a4a02016-10-28 05:39:16 -07001081
1082 if (red_render_queue_element_max_size_ <
1083 new_red_render_queue_element_max_size) {
1084 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1085
1086 std::vector<float> template_queue_element(
1087 red_render_queue_element_max_size_);
1088
1089 red_render_signal_queue_.reset(
1090 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1091 kMaxNumFramesToBuffer, template_queue_element,
1092 RenderQueueItemVerifier<float>(
1093 red_render_queue_element_max_size_)));
1094
1095 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1096 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1097 } else {
1098 red_render_signal_queue_->Clear();
1099 }
peah764e3642016-10-22 05:04:30 -07001100}
1101
1102void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1103 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001104 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02001105 RTC_DCHECK(aec_render_signal_queue_);
1106 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001107 submodules_.echo_cancellation->ProcessRenderAudio(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001108 aec_capture_queue_buffer_);
1109 }
peaha0624602016-10-25 04:45:24 -07001110 }
1111
saza1d600522019-10-18 13:29:43 +02001112 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001113 RTC_DCHECK(aecm_render_signal_queue_);
1114 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001115 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001116 aecm_capture_queue_buffer_);
1117 }
peah701d6282016-10-25 05:42:20 -07001118 }
1119
1120 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001121 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001122 }
ivoc9f4a4a02016-10-28 05:39:16 -07001123
1124 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001125 RTC_DCHECK(submodules_.echo_detector);
1126 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001127 }
peah764e3642016-10-22 05:04:30 -07001128}
1129
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001130int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001131 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001132 {
1133 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001134 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001135 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001136 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001137 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001138 }
peahfa6228e2015-11-16 16:27:42 -08001139
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001140 if (!frame) {
1141 return kNullPointerError;
1142 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001143 // Must be a native rate.
1144 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1145 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001146 frame->sample_rate_hz_ != kSampleRate32kHz &&
1147 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001148 return kBadSampleRateError;
1149 }
peah192164e2015-11-17 02:16:45 -08001150
peahdf3efa82015-11-28 12:35:15 -08001151 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001152 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001153 {
1154 // Aquire lock for the access of api_format.
1155 // The lock is released immediately due to the conditional
1156 // reinitialization.
1157 rtc::CritScope cs_capture(&crit_capture_);
1158 // TODO(ajm): The input and output rates and channels are currently
1159 // constrained to be identical in the int16 interface.
1160 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001161
1162 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001163 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001164
Oskar Sundbom4b276482019-05-23 14:28:00 +02001165 reinitialization_required =
1166 reinitialization_required ||
1167 processing_config.input_stream().sample_rate_hz() !=
1168 frame->sample_rate_hz_ ||
1169 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1170 processing_config.output_stream().sample_rate_hz() !=
1171 frame->sample_rate_hz_ ||
1172 processing_config.output_stream().num_channels() != frame->num_channels_;
1173
1174 if (reinitialization_required) {
1175 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1176 processing_config.input_stream().set_num_channels(frame->num_channels_);
1177 processing_config.output_stream().set_sample_rate_hz(
1178 frame->sample_rate_hz_);
1179 processing_config.output_stream().set_num_channels(frame->num_channels_);
1180
1181 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001182 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001183 rtc::CritScope cs_capture(&crit_capture_);
1184 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001185 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001186
peahdf3efa82015-11-28 12:35:15 -08001187 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001188 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001189 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001190 return kBadDataLengthError;
1191 }
1192
aleloi868f32f2017-05-23 07:20:05 -07001193 if (aec_dump_) {
1194 RecordUnprocessedCaptureStream(*frame);
1195 }
1196
Per Åhgrend47941e2019-08-22 11:51:13 +02001197 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001198 if (capture_.capture_fullband_audio) {
1199 capture_.capture_fullband_audio->CopyFrom(frame);
1200 }
peahde65ddc2016-09-16 15:02:15 -07001201 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001202 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001203 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001204 if (capture_.capture_fullband_audio) {
1205 capture_.capture_fullband_audio->CopyTo(frame);
1206 } else {
1207 capture_.capture_audio->CopyTo(frame);
1208 }
Per Åhgrena1351272019-08-15 12:15:46 +02001209 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001210 if (capture_.stats.voice_detected) {
1211 frame->vad_activity_ = *capture_.stats.voice_detected
1212 ? AudioFrame::kVadActive
1213 : AudioFrame::kVadPassive;
1214 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001215
aleloi868f32f2017-05-23 07:20:05 -07001216 if (aec_dump_) {
1217 RecordProcessedCaptureStream(*frame);
1218 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001219
1220 return kNoError;
1221}
1222
peahde65ddc2016-09-16 15:02:15 -07001223int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001224 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001225
peahb58a1582016-03-15 09:34:24 -07001226 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001227 // TODO(peah): Simplify once the public API Enable functions for these
1228 // are moved to APM.
saza1d600522019-10-18 13:29:43 +02001229 RTC_DCHECK_LE(!!submodules_.echo_controller +
1230 !!submodules_.echo_cancellation +
1231 !!submodules_.echo_control_mobile,
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001232 1);
peahb58a1582016-03-15 09:34:24 -07001233
peahde65ddc2016-09-16 15:02:15 -07001234 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001235
saza1d600522019-10-18 13:29:43 +02001236 if (submodules_.pre_amplifier) {
1237 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001238 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001239 capture_buffer->num_frames()));
1240 }
1241
Per Åhgren928146f2019-08-20 09:19:21 +02001242 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001243 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001244 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001245 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1246 if (log_rms) {
1247 capture_rms_interval_counter_ = 0;
1248 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001249 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1250 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1251 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1252 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001253 }
1254
saza1d600522019-10-18 13:29:43 +02001255 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001256 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001257 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001258 capture_.echo_path_gain_change =
1259 capture_.prev_analog_mic_level != analog_mic_level &&
1260 capture_.prev_analog_mic_level != -1;
1261 capture_.prev_analog_mic_level = analog_mic_level;
1262
Per Åhgrend2650d12018-10-02 17:00:59 +02001263 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001264 if (submodules_.pre_amplifier) {
1265 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001266 capture_.echo_path_gain_change =
1267 capture_.echo_path_gain_change ||
1268 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001269 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001270 capture_.prev_pre_amp_gain = pre_amp_gain;
1271 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001272
1273 // Detect volume change.
1274 capture_.echo_path_gain_change =
1275 capture_.echo_path_gain_change ||
1276 (capture_.prev_playout_volume != capture_.playout_volume &&
1277 capture_.prev_playout_volume >= 0);
1278 capture_.prev_playout_volume = capture_.playout_volume;
1279
saza1d600522019-10-18 13:29:43 +02001280 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001281 }
1282
Per Åhgren3daedb62019-11-22 12:11:40 +01001283 if (constants_.use_experimental_agc &&
1284 submodules_.gain_control->is_enabled()) {
1285 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001286 }
1287
peah2ace3f92016-09-10 04:42:27 -07001288 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1289 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001290 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1291 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001292 }
1293
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001294 const bool experimental_multi_channel_capture =
1295 config_.pipeline.experimental_multi_channel &&
1296 constants_.experimental_multi_channel_capture_support;
saza1d600522019-10-18 13:29:43 +02001297 if (submodules_.echo_controller && !experimental_multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001298 // Force down-mixing of the number of channels after the detection of
1299 // capture signal saturation.
1300 // TODO(peah): Look into ensuring that this kind of tampering with the
1301 // AudioBuffer functionality should not be needed.
1302 capture_buffer->set_num_channels(1);
1303 }
1304
saza1d600522019-10-18 13:29:43 +02001305 if (submodules_.high_pass_filter) {
1306 submodules_.high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001307 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001308
Per Åhgrene35b32c2019-11-22 18:22:04 +01001309 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001310 RTC_DCHECK(
1311 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
saza1d600522019-10-18 13:29:43 +02001312 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001313 submodules_.noise_suppressor->Analyze(*capture_buffer);
1314 } else if (submodules_.legacy_noise_suppressor) {
1315 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001316 }
peahb58a1582016-03-15 09:34:24 -07001317
saza1d600522019-10-18 13:29:43 +02001318 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001319 // Ensure that the stream delay was set before the call to the
1320 // AECM ProcessCaptureAudio function.
1321 if (!was_stream_delay_set()) {
1322 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001323 }
1324
saza1d600522019-10-18 13:29:43 +02001325 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001326 submodules_.noise_suppressor->Process(capture_buffer);
1327 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001328 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001329 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001330 }
peahe0eae3c2016-12-14 01:16:23 -08001331
saza1d600522019-10-18 13:29:43 +02001332 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001333 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001334 } else {
saza1d600522019-10-18 13:29:43 +02001335 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001336 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1337
1338 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001339 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001340 }
1341
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001342 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
saza1d600522019-10-18 13:29:43 +02001343 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001344 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
saza1d600522019-10-18 13:29:43 +02001345 } else if (submodules_.echo_cancellation) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001346 // Ensure that the stream delay was set before the call to the
1347 // AEC ProcessCaptureAudio function.
1348 if (!was_stream_delay_set()) {
1349 return AudioProcessing::kStreamParameterNotSetError;
1350 }
1351
saza1d600522019-10-18 13:29:43 +02001352 RETURN_ON_ERR(submodules_.echo_cancellation->ProcessCaptureAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001353 capture_buffer, stream_delay_ms()));
1354 }
1355
saza1d600522019-10-18 13:29:43 +02001356 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001357 submodules_.noise_suppressor->Process(capture_buffer);
1358 } else if (submodules_.legacy_noise_suppressor) {
1359 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001360 }
Per Åhgren46537a32017-06-07 10:08:10 +02001361 }
ivoc9f4a4a02016-10-28 05:39:16 -07001362
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001363 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001364 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001365 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001366 } else {
1367 capture_.stats.voice_detected = absl::nullopt;
1368 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001369
Per Åhgren3daedb62019-11-22 12:11:40 +01001370 if (constants_.use_experimental_agc &&
1371 submodules_.gain_control->is_enabled()) {
1372 submodules_.agc_manager->Process(capture_buffer);
1373
1374 absl::optional<int> new_digital_gain =
1375 submodules_.agc_manager->GetDigitalComressionGain();
1376 if (new_digital_gain) {
1377 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1378 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001379 }
Per Åhgren200feba2019-03-06 04:16:46 +01001380 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001381 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1382 capture_buffer, submodules_.echo_cancellation &&
1383 submodules_.echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001384
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001385 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001386 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001387 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1388 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001389 }
1390
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001391 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001392 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001393 bool ec_active = ec ? ec->ActiveProcessing() : false;
1394 // Only update the fullband buffer if the multiband processing has changed
1395 // the signal. Keep the original signal otherwise.
1396 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1397 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1398 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001399 capture_buffer = capture_.capture_fullband_audio.get();
1400 }
1401
peah9e6a2902017-05-15 07:19:21 -07001402 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001403 RTC_DCHECK(submodules_.echo_detector);
1404 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1405 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001406 }
1407
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001408 // TODO(aluebs): Investigate if the transient suppression placement should be
1409 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001410 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001411 float voice_probability = submodules_.agc_manager.get()
1412 ? submodules_.agc_manager->voice_probability()
1413 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001414
saza1d600522019-10-18 13:29:43 +02001415 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001416 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001417 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001418 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001419 capture_buffer->num_frames_per_band(),
1420 capture_.keyboard_info.keyboard_data,
1421 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001422 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001423 }
1424
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001425 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001426 if (submodules_.capture_analyzer) {
1427 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001428 }
1429
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001430 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001431 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001432 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001433 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001434 }
1435
saza1d600522019-10-18 13:29:43 +02001436 if (submodules_.capture_post_processor) {
1437 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001438 }
1439
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001440 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001441 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001442 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1443 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001444 } else {
1445 capture_.stats.output_rms_dbfs = absl::nullopt;
1446 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001447
Per Åhgren928146f2019-08-20 09:19:21 +02001448 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001449 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001450 capture_nonlocked_.capture_processing_format.num_frames()));
1451 if (log_rms) {
1452 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1453 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1454 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1455 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1456 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1457 }
1458
Per Åhgren0e3198e2019-11-18 08:52:22 +01001459 if (submodules_.agc_manager) {
1460 int level = recommended_stream_analog_level();
1461 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1462 &level);
1463 }
1464
peahdf3efa82015-11-28 12:35:15 -08001465 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466 return kNoError;
1467}
1468
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001469int AudioProcessingImpl::AnalyzeReverseStream(
1470 const float* const* data,
1471 const StreamConfig& reverse_config) {
1472 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1473 rtc::CritScope cs(&crit_render_);
1474 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1475}
1476
peahde65ddc2016-09-16 15:02:15 -07001477int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1478 const StreamConfig& input_config,
1479 const StreamConfig& output_config,
1480 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001481 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001482 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001483 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001484 if (submodule_states_.RenderMultiBandProcessingActive() ||
1485 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001486 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1487 dest);
peah2ace3f92016-09-10 04:42:27 -07001488 } else if (formats_.api_format.reverse_input_stream() !=
1489 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001490 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1491 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001492 } else {
peahde65ddc2016-09-16 15:02:15 -07001493 CopyAudioIfNeeded(src, input_config.num_frames(),
1494 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001495 }
1496
1497 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001498}
1499
peahdf3efa82015-11-28 12:35:15 -08001500int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001501 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001502 const StreamConfig& input_config,
1503 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001504 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001505 return kNullPointerError;
1506 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001507
peahde65ddc2016-09-16 15:02:15 -07001508 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001509 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001510 }
1511
peahdf3efa82015-11-28 12:35:15 -08001512 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001513 processing_config.reverse_input_stream() = input_config;
1514 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001515
peahdf3efa82015-11-28 12:35:15 -08001516 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001517 RTC_DCHECK_EQ(input_config.num_frames(),
1518 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001519
aleloi868f32f2017-05-23 07:20:05 -07001520 if (aec_dump_) {
1521 const size_t channel_size =
1522 formats_.api_format.reverse_input_stream().num_frames();
1523 const size_t num_channels =
1524 formats_.api_format.reverse_input_stream().num_channels();
1525 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001526 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001527 }
peahdf3efa82015-11-28 12:35:15 -08001528 render_.render_audio->CopyFrom(src,
1529 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001530 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001531}
1532
1533int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001534 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001535 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001536 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001537 return kNullPointerError;
1538 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001539 // Must be a native rate.
1540 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1541 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001542 frame->sample_rate_hz_ != kSampleRate32kHz &&
1543 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001544 return kBadSampleRateError;
1545 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001546
Michael Graczyk86c6d332015-07-23 11:41:39 -07001547 if (frame->num_channels_ <= 0) {
1548 return kBadNumberChannelsError;
1549 }
1550
peahdf3efa82015-11-28 12:35:15 -08001551 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001552 processing_config.reverse_input_stream().set_sample_rate_hz(
1553 frame->sample_rate_hz_);
1554 processing_config.reverse_input_stream().set_num_channels(
1555 frame->num_channels_);
1556 processing_config.reverse_output_stream().set_sample_rate_hz(
1557 frame->sample_rate_hz_);
1558 processing_config.reverse_output_stream().set_num_channels(
1559 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001560
peahdf3efa82015-11-28 12:35:15 -08001561 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001562 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001563 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001564 return kBadDataLengthError;
1565 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001566
aleloi868f32f2017-05-23 07:20:05 -07001567 if (aec_dump_) {
1568 aec_dump_->WriteRenderStreamMessage(*frame);
1569 }
1570
Per Åhgrend47941e2019-08-22 11:51:13 +02001571 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001572 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001573 if (submodule_states_.RenderMultiBandProcessingActive() ||
1574 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001575 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001576 }
aluebsb0319552016-03-17 20:39:53 -07001577 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001578}
niklase@google.com470e71d2011-07-07 08:21:25 +00001579
peahde65ddc2016-09-16 15:02:15 -07001580int AudioProcessingImpl::ProcessRenderStreamLocked() {
1581 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001582
Alex Loiko73ec0192018-05-15 10:52:28 +02001583 HandleRenderRuntimeSettings();
1584
saza1d600522019-10-18 13:29:43 +02001585 if (submodules_.render_pre_processor) {
1586 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001587 }
1588
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001589 QueueNonbandedRenderAudio(render_buffer);
1590
peah2ace3f92016-09-10 04:42:27 -07001591 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001592 SampleRateSupportsMultiBand(
1593 formats_.render_processing_format.sample_rate_hz())) {
1594 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001595 }
1596
peahce4d9152017-05-19 01:28:05 -07001597 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1598 QueueBandedRenderAudio(render_buffer);
1599 }
1600
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001601 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001602 if (submodules_.echo_controller) {
1603 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001604 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001605
peah2ace3f92016-09-10 04:42:27 -07001606 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001607 SampleRateSupportsMultiBand(
1608 formats_.render_processing_format.sample_rate_hz())) {
1609 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001610 }
1611
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001612 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001613}
1614
1615int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001616 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001617 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001618 capture_.was_stream_delay_set = true;
1619 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001620
niklase@google.com470e71d2011-07-07 08:21:25 +00001621 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001622 delay = 0;
1623 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001624 }
1625
1626 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1627 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001628 delay = 500;
1629 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001630 }
1631
peahdf3efa82015-11-28 12:35:15 -08001632 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001633 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001634}
1635
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001636bool AudioProcessingImpl::GetLinearAecOutput(
1637 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1638 rtc::CritScope cs(&crit_capture_);
1639 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1640
1641 RTC_DCHECK(linear_aec_buffer);
1642 if (linear_aec_buffer) {
1643 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1644 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1645
1646 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1647 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1648 rtc::ArrayView<const float> channel_view =
1649 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1650 linear_aec_buffer->num_frames());
1651 std::copy(channel_view.begin(), channel_view.end(),
1652 linear_output[ch].begin());
1653 }
1654 return true;
1655 }
1656 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1657 RTC_NOTREACHED();
1658 return false;
1659}
1660
niklase@google.com470e71d2011-07-07 08:21:25 +00001661int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001662 // Used as callback from submodules, hence locking is not allowed.
1663 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001664}
1665
1666bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001667 // Used as callback from submodules, hence locking is not allowed.
1668 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001669}
1670
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001671void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001672 rtc::CritScope cs(&crit_capture_);
1673 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001674}
1675
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001676void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001677 rtc::CritScope cs(&crit_capture_);
1678 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001679}
1680
1681int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001682 rtc::CritScope cs(&crit_capture_);
1683 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001684}
1685
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001686void AudioProcessingImpl::set_stream_analog_level(int level) {
1687 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001688
1689 if (submodules_.agc_manager) {
1690 submodules_.agc_manager->set_stream_analog_level(level);
1691 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1692 1, &level);
1693 } else {
1694 int error = submodules_.gain_control->set_stream_analog_level(level);
1695 RTC_DCHECK_EQ(kNoError, error);
1696 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001697}
1698
1699int AudioProcessingImpl::recommended_stream_analog_level() const {
1700 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001701 if (submodules_.agc_manager) {
1702 return submodules_.agc_manager->stream_analog_level();
1703 }
1704 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001705}
1706
aleloi868f32f2017-05-23 07:20:05 -07001707void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1708 RTC_DCHECK(aec_dump);
1709 rtc::CritScope cs_render(&crit_render_);
1710 rtc::CritScope cs_capture(&crit_capture_);
1711
1712 // The previously attached AecDump will be destroyed with the
1713 // 'aec_dump' parameter, which is after locks are released.
1714 aec_dump_.swap(aec_dump);
1715 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001716 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001717}
1718
1719void AudioProcessingImpl::DetachAecDump() {
1720 // The d-tor of a task-queue based AecDump blocks until all pending
1721 // tasks are done. This construction avoids blocking while holding
1722 // the render and capture locks.
1723 std::unique_ptr<AecDump> aec_dump = nullptr;
1724 {
1725 rtc::CritScope cs_render(&crit_render_);
1726 rtc::CritScope cs_capture(&crit_capture_);
1727 aec_dump = std::move(aec_dump_);
1728 }
1729}
1730
Sam Zackrisson4d364492018-03-02 16:03:21 +01001731void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1732 std::unique_ptr<AudioGenerator> audio_generator) {
1733 // TODO(bugs.webrtc.org/8882) Stub.
1734 // Reset internal audio generator with audio_generator.
1735}
1736
1737void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1738 // TODO(bugs.webrtc.org/8882) Stub.
1739 // Delete audio generator, if one is attached.
1740}
1741
Ivo Creusen56d46092017-11-24 17:29:59 +01001742AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001743 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001744 rtc::CritScope cs_capture(&crit_capture_);
1745 if (!has_remote_tracks) {
1746 return capture_.stats;
1747 }
1748 AudioProcessingStats stats = capture_.stats;
1749 EchoCancellationImpl::Metrics metrics;
saza1d600522019-10-18 13:29:43 +02001750 if (submodules_.echo_controller) {
1751 auto ec_metrics = submodules_.echo_controller->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001752 stats.echo_return_loss = ec_metrics.echo_return_loss;
1753 stats.echo_return_loss_enhancement =
1754 ec_metrics.echo_return_loss_enhancement;
1755 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001756 }
1757 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001758 RTC_DCHECK(submodules_.echo_detector);
1759 auto ed_metrics = submodules_.echo_detector->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001760 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1761 stats.residual_echo_likelihood_recent_max =
1762 ed_metrics.echo_likelihood_recent_max;
1763 }
Ivo Creusenae026092017-11-20 13:07:16 +01001764 return stats;
1765}
1766
peah8271d042016-11-22 07:24:52 -08001767void AudioProcessingImpl::MutateConfig(
1768 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1769 rtc::CritScope cs_render(&crit_render_);
1770 rtc::CritScope cs_capture(&crit_capture_);
1771 mutator(&config_);
1772 ApplyConfig(config_);
1773}
1774
1775AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1776 rtc::CritScope cs_render(&crit_render_);
1777 rtc::CritScope cs_capture(&crit_capture_);
1778 return config_;
1779}
1780
peah2ace3f92016-09-10 04:42:27 -07001781bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1782 return submodule_states_.Update(
saza1d600522019-10-18 13:29:43 +02001783 config_.high_pass_filter.enabled, !!submodules_.echo_cancellation,
1784 !!submodules_.echo_control_mobile, config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001785 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
1786 submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled,
1787 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 11:46:11 +02001788 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001789}
1790
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001791void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001792 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001793 if (!submodules_.transient_suppressor.get()) {
1794 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001795 }
saza1d600522019-10-18 13:29:43 +02001796 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1797 capture_nonlocked_.split_rate,
1798 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001799 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001800}
1801
Per Åhgren0aefbf02019-08-23 21:29:17 +02001802void AudioProcessingImpl::InitializeHighPassFilter() {
1803 if (submodule_states_.HighPassFilteringRequired()) {
saza1d600522019-10-18 13:29:43 +02001804 submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001805 } else {
saza1d600522019-10-18 13:29:43 +02001806 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001807 }
1808}
alessiob3ec96df2017-05-22 06:57:06 -07001809
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001810void AudioProcessingImpl::InitializeVoiceDetector() {
1811 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001812 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001813 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1814 } else {
saza1d600522019-10-18 13:29:43 +02001815 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001816 }
1817}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001818void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001819 bool use_echo_controller =
1820 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001821 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001822 !config_.echo_canceller.use_legacy_aec);
1823
1824 if (use_echo_controller) {
1825 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001826 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001827 submodules_.echo_controller = echo_control_factory_->Create(
1828 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001829 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001830 } else {
saza1d600522019-10-18 13:29:43 +02001831 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001832 EchoCanceller3Config(), proc_sample_rate_hz(), num_reverse_channels(),
1833 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001834 }
1835
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001836 // Setup the storage for returning the linear AEC output.
1837 if (config_.echo_canceller.export_linear_aec_output) {
1838 constexpr int kLinearOutputRateHz = 16000;
1839 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1840 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1841 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1842 } else {
1843 capture_.linear_aec_output.reset();
1844 }
1845
Per Åhgren200feba2019-03-06 04:16:46 +01001846 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001847
saza1d600522019-10-18 13:29:43 +02001848 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001849 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001850 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001851 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001852 return;
peahe0eae3c2016-12-14 01:16:23 -08001853 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001854
saza1d600522019-10-18 13:29:43 +02001855 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001856 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001857 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001858
1859 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001860 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001861 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001862 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001863 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001864 return;
1865 }
1866
1867 if (config_.echo_canceller.mobile_mode) {
1868 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001869 size_t max_element_size =
1870 std::max(static_cast<size_t>(1),
1871 kMaxAllowedValuesOfSamplesPerBand *
1872 EchoControlMobileImpl::NumCancellersRequired(
1873 num_output_channels(), num_reverse_channels()));
1874
1875 std::vector<int16_t> template_queue_element(max_element_size);
1876
1877 aecm_render_signal_queue_.reset(
1878 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1879 kMaxNumFramesToBuffer, template_queue_element,
1880 RenderQueueItemVerifier<int16_t>(max_element_size)));
1881
1882 aecm_render_queue_buffer_.resize(max_element_size);
1883 aecm_capture_queue_buffer_.resize(max_element_size);
1884
saza1d600522019-10-18 13:29:43 +02001885 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001886
saza1d600522019-10-18 13:29:43 +02001887 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1888 num_reverse_channels(),
1889 num_output_channels());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001890
saza1d600522019-10-18 13:29:43 +02001891 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001892 aec_render_signal_queue_.reset();
1893 return;
1894 }
1895
saza1d600522019-10-18 13:29:43 +02001896 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001897 aecm_render_signal_queue_.reset();
1898
Per Åhgrenf204faf2019-04-25 15:18:06 +02001899 // Create and activate AEC2.
saza1d600522019-10-18 13:29:43 +02001900 submodules_.echo_cancellation.reset(new EchoCancellationImpl());
1901 submodules_.echo_cancellation->SetExtraOptions(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001902 capture_nonlocked_.use_aec2_extended_filter,
1903 capture_nonlocked_.use_aec2_delay_agnostic,
1904 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1905
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001906 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001907 std::max(static_cast<size_t>(1),
1908 kMaxAllowedValuesOfSamplesPerBand *
1909 EchoCancellationImpl::NumCancellersRequired(
1910 num_output_channels(), num_reverse_channels()));
1911
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001912 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001913
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001914 aec_render_signal_queue_.reset(
1915 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1916 kMaxNumFramesToBuffer, template_queue_element,
1917 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001918
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001919 aec_render_queue_buffer_.resize(element_max_size);
1920 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001921
saza1d600522019-10-18 13:29:43 +02001922 submodules_.echo_cancellation->Initialize(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001923 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1924 num_proc_channels());
1925
saza1d600522019-10-18 13:29:43 +02001926 submodules_.echo_cancellation->set_suppression_level(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001927 config_.echo_canceller.legacy_moderate_suppression_level
1928 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1929 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001930}
peah8271d042016-11-22 07:24:52 -08001931
alessiob3ec96df2017-05-22 06:57:06 -07001932void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001933 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001934 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001935 }
1936}
1937
saza0bad15f2019-10-16 11:46:11 +02001938void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001939 submodules_.legacy_noise_suppressor.reset();
1940 submodules_.noise_suppressor.reset();
1941
saza0bad15f2019-10-16 11:46:11 +02001942 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001943 const bool use_legacy_ns =
1944 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1945
1946 if (!use_legacy_ns) {
1947 auto map_level =
1948 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1949 using NoiseSuppresionConfig =
1950 AudioProcessing::Config::NoiseSuppression;
1951 switch (level) {
1952 case NoiseSuppresionConfig::kLow:
1953 return NsConfig::SuppressionLevel::k6dB;
1954 case NoiseSuppresionConfig::kModerate:
1955 return NsConfig::SuppressionLevel::k12dB;
1956 case NoiseSuppresionConfig::kHigh:
1957 return NsConfig::SuppressionLevel::k18dB;
1958 case NoiseSuppresionConfig::kVeryHigh:
1959 return NsConfig::SuppressionLevel::k21dB;
1960 default:
1961 RTC_NOTREACHED();
1962 }
1963 };
1964
1965 NsConfig cfg;
1966 cfg.target_level = map_level(config_.noise_suppression.level);
1967 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1968 cfg, proc_sample_rate_hz(), num_proc_channels());
1969 } else {
1970 auto ns_level =
1971 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1972 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1973 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1974 }
saza0bad15f2019-10-16 11:46:11 +02001975 }
1976}
1977
Alex Loikob5c9a792018-04-16 16:31:22 +02001978void AudioProcessingImpl::InitializePreAmplifier() {
1979 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001980 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001981 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1982 } else {
saza1d600522019-10-18 13:29:43 +02001983 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001984 }
1985}
1986
ivoc9f4a4a02016-10-28 05:39:16 -07001987void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001988 RTC_DCHECK(submodules_.echo_detector);
1989 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001990 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001991 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001992}
1993
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001994void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001995 if (submodules_.capture_analyzer) {
1996 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1997 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001998 }
1999}
2000
Sam Zackrisson0beac582017-09-25 12:04:02 +02002001void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002002 if (submodules_.capture_post_processor) {
2003 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002004 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002005 }
2006}
2007
Alex Loiko5825aa62017-12-18 16:02:40 +01002008void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002009 if (submodules_.render_pre_processor) {
2010 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002011 formats_.render_processing_format.sample_rate_hz(),
2012 formats_.render_processing_format.num_channels());
2013 }
2014}
2015
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002016void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002017
aleloi868f32f2017-05-23 07:20:05 -07002018void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2019 if (!aec_dump_) {
2020 return;
2021 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002022
2023 std::string experiments_description = "";
saza1d600522019-10-18 13:29:43 +02002024 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02002025 experiments_description +=
saza1d600522019-10-18 13:29:43 +02002026 submodules_.echo_cancellation->GetExperimentsDescription();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002027 }
aleloi868f32f2017-05-23 07:20:05 -07002028 // TODO(peah): Add semicolon-separated concatenations of experiment
2029 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002030 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2031 experiments_description += "AgcClippingLevelExperiment;";
2032 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002033 if (capture_nonlocked_.echo_controller_enabled) {
2034 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002035 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002036 if (config_.gain_controller2.enabled) {
2037 experiments_description += "GainController2;";
2038 }
aleloi868f32f2017-05-23 07:20:05 -07002039
2040 InternalAPMConfig apm_config;
2041
Per Åhgren200feba2019-03-06 04:16:46 +01002042 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002043 apm_config.aec_delay_agnostic_enabled =
saza1d600522019-10-18 13:29:43 +02002044 submodules_.echo_cancellation &&
2045 submodules_.echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002046 apm_config.aec_drift_compensation_enabled =
saza1d600522019-10-18 13:29:43 +02002047 submodules_.echo_cancellation &&
2048 submodules_.echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002049 apm_config.aec_extended_filter_enabled =
saza1d600522019-10-18 13:29:43 +02002050 submodules_.echo_cancellation &&
2051 submodules_.echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002052 apm_config.aec_suppression_level =
saza1d600522019-10-18 13:29:43 +02002053 submodules_.echo_cancellation
2054 ? static_cast<int>(submodules_.echo_cancellation->suppression_level())
Per Åhgrenf204faf2019-04-25 15:18:06 +02002055 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002056
saza1d600522019-10-18 13:29:43 +02002057 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002058 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002059 submodules_.echo_control_mobile &&
2060 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002061 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002062 submodules_.echo_control_mobile
2063 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002064 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002065
saza1d600522019-10-18 13:29:43 +02002066 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
2067 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07002068 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02002069 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01002070 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002071
2072 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2073
saza0bad15f2019-10-16 11:46:11 +02002074 apm_config.ns_enabled = config_.noise_suppression.enabled;
2075 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002076
2077 apm_config.transient_suppression_enabled =
2078 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002079 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002080 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2081 apm_config.pre_amplifier_fixed_gain_factor =
2082 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002083
2084 if (!forced && apm_config == apm_config_for_aec_dump_) {
2085 return;
2086 }
2087 aec_dump_->WriteConfig(apm_config);
2088 apm_config_for_aec_dump_ = apm_config;
2089}
2090
2091void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2092 const float* const* src) {
2093 RTC_DCHECK(aec_dump_);
2094 WriteAecDumpConfigMessage(false);
2095
2096 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2097 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2098 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002099 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002100 RecordAudioProcessingState();
2101}
2102
2103void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2104 const AudioFrame& capture_frame) {
2105 RTC_DCHECK(aec_dump_);
2106 WriteAecDumpConfigMessage(false);
2107
2108 aec_dump_->AddCaptureStreamInput(capture_frame);
2109 RecordAudioProcessingState();
2110}
2111
2112void AudioProcessingImpl::RecordProcessedCaptureStream(
2113 const float* const* processed_capture_stream) {
2114 RTC_DCHECK(aec_dump_);
2115
2116 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2117 const size_t num_channels =
2118 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002119 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2120 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002121 aec_dump_->WriteCaptureStreamMessage();
2122}
2123
2124void AudioProcessingImpl::RecordProcessedCaptureStream(
2125 const AudioFrame& processed_capture_frame) {
2126 RTC_DCHECK(aec_dump_);
2127
2128 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2129 aec_dump_->WriteCaptureStreamMessage();
2130}
2131
2132void AudioProcessingImpl::RecordAudioProcessingState() {
2133 RTC_DCHECK(aec_dump_);
2134 AecDump::AudioProcessingState audio_proc_state;
2135 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2136 audio_proc_state.drift =
saza1d600522019-10-18 13:29:43 +02002137 submodules_.echo_cancellation
2138 ? submodules_.echo_cancellation->stream_drift_samples()
Per Åhgrenf204faf2019-04-25 15:18:06 +02002139 : 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002140 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002141 audio_proc_state.keypress = capture_.key_pressed;
2142 aec_dump_->AddAudioProcessingState(audio_proc_state);
2143}
2144
kwiberg83ffe452016-08-29 14:46:07 -07002145AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002146 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002147 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002148 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002149 output_will_be_muted(false),
2150 key_pressed(false),
2151 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002152 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002153 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002154 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002155 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002156 prev_pre_amp_gain(-1.f),
2157 playout_volume(-1),
2158 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002159
2160AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2161
Per Åhgrena1351272019-08-15 12:15:46 +02002162void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2163 const float* const* data,
2164 const StreamConfig& stream_config) {
2165 if (stream_config.has_keyboard()) {
2166 keyboard_data = data[stream_config.num_channels()];
2167 } else {
2168 keyboard_data = NULL;
2169 }
2170 num_keyboard_frames = stream_config.num_frames();
2171}
2172
kwiberg83ffe452016-08-29 14:46:07 -07002173AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2174
2175AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2176
niklase@google.com470e71d2011-07-07 08:21:25 +00002177} // namespace webrtc