blob: aaf372efd048bf1a028fbd9b570c24491abfa3a3 [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) {
485 submodules_.agc_manager.reset(new AgcManagerDirect(
486 num_proc_channels(), constants_.agc_startup_min_volume,
487 constants_.agc_clipped_level_min,
488 constants_.use_experimental_agc_agc2_level_estimation,
489 constants_.use_experimental_agc_agc2_digital_adaptive,
490 capture_nonlocked_.split_rate));
491 }
saza1d600522019-10-18 13:29:43 +0200492 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 12:11:40 +0100493 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 08:52:22 +0100494 submodules_.gain_control.get());
saza1d600522019-10-18 13:29:43 +0200495 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 15:02:15 -0700496 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200497 InitializeTransient();
Per Åhgren0aefbf02019-08-23 21:29:17 +0200498 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200499 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700500 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200501 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700502 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200503 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200504 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200505 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100506 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800507
aleloi868f32f2017-05-23 07:20:05 -0700508 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200509 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700510 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000511 return kNoError;
512}
513
Michael Graczyk86c6d332015-07-23 11:41:39 -0700514int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200515 UpdateActiveSubmoduleStates();
516
Michael Graczyk86c6d332015-07-23 11:41:39 -0700517 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700518 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
519 return kBadSampleRateError;
520 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000521 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700522
Peter Kasting69558702016-01-12 16:26:35 -0800523 const size_t num_in_channels = config.input_stream().num_channels();
524 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700525
526 // Need at least one input channel.
527 // Need either one output channel or as many outputs as there are inputs.
528 if (num_in_channels == 0 ||
529 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700530 return kBadNumberChannelsError;
531 }
532
peahdf3efa82015-11-28 12:35:15 -0800533 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000534
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200535 // Choose maximum rate to use for the split filtering.
536 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
537 config_.pipeline.maximum_internal_processing_rate == 32000);
538 int max_splitting_rate = 48000;
539 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
540 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
541 }
542
Per Åhgrenc8626b62019-08-23 15:49:51 +0200543 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700544 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700545 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200546 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700547 submodule_states_.CaptureMultiBandSubModulesActive() ||
548 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200549 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000550
peahde65ddc2016-09-16 15:02:15 -0700551 capture_nonlocked_.capture_processing_format =
552 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700553
peah2ce640f2017-04-07 03:57:48 -0700554 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200555 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200556 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700557 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
558 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200559 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700560 submodule_states_.CaptureMultiBandSubModulesActive() ||
561 submodule_states_.RenderMultiBandSubModulesActive());
562 } else {
563 render_processing_rate = capture_processing_rate;
564 }
565
peahde65ddc2016-09-16 15:02:15 -0700566 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700567 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700568 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
569 kSampleRate8kHz) {
570 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000571 } else {
peahde65ddc2016-09-16 15:02:15 -0700572 render_processing_rate =
573 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000574 }
575
Per Åhgrenc8626b62019-08-23 15:49:51 +0200576 RTC_DCHECK_NE(8000, render_processing_rate);
577
peahce4d9152017-05-19 01:28:05 -0700578 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200579 // By default, downmix the render stream to mono for analysis. This has been
580 // demonstrated to work well for AEC in most practical scenarios.
581 const bool experimental_multi_channel_render =
582 config_.pipeline.experimental_multi_channel &&
583 constants_.experimental_multi_channel_render_support;
584 int render_processing_num_channels =
585 experimental_multi_channel_render
586 ? formats_.api_format.reverse_input_stream().num_channels()
587 : 1;
588 formats_.render_processing_format =
589 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700590 } else {
591 formats_.render_processing_format = StreamConfig(
592 formats_.api_format.reverse_input_stream().sample_rate_hz(),
593 formats_.api_format.reverse_input_stream().num_channels());
594 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000595
peahde65ddc2016-09-16 15:02:15 -0700596 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
597 kSampleRate32kHz ||
598 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
599 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800600 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000601 } else {
peahdf3efa82015-11-28 12:35:15 -0800602 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700603 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000604 }
605
606 return InitializeLocked();
607}
608
peah88ac8532016-09-12 16:47:25 -0700609void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200610 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
611
peah88ac8532016-09-12 16:47:25 -0700612 // Run in a single-threaded manner when applying the settings.
613 rtc::CritScope cs_render(&crit_render_);
614 rtc::CritScope cs_capture(&crit_capture_);
615
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200616 const bool pipeline_config_changed =
617 config_.pipeline.experimental_multi_channel !=
618 config.pipeline.experimental_multi_channel;
619
Per Åhgren200feba2019-03-06 04:16:46 +0100620 const bool aec_config_changed =
621 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
622 config_.echo_canceller.use_legacy_aec !=
623 config.echo_canceller.use_legacy_aec ||
624 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
625 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
626 config_.echo_canceller.legacy_moderate_suppression_level !=
627 config.echo_canceller.legacy_moderate_suppression_level);
628
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100629 const bool agc1_config_changed =
630 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
631 config_.gain_controller1.mode != config.gain_controller1.mode ||
632 config_.gain_controller1.target_level_dbfs !=
633 config.gain_controller1.target_level_dbfs ||
634 config_.gain_controller1.compression_gain_db !=
635 config.gain_controller1.compression_gain_db ||
636 config_.gain_controller1.enable_limiter !=
637 config.gain_controller1.enable_limiter ||
638 config_.gain_controller1.analog_level_minimum !=
639 config.gain_controller1.analog_level_minimum ||
640 config_.gain_controller1.analog_level_maximum !=
641 config.gain_controller1.analog_level_maximum;
642
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200643 const bool voice_detection_config_changed =
644 config_.voice_detection.enabled != config.voice_detection.enabled;
645
saza0bad15f2019-10-16 11:46:11 +0200646 const bool ns_config_changed =
647 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
648 config_.noise_suppression.level != config.noise_suppression.level;
649
Yves Gerey499bc6c2018-10-10 18:29:07 +0200650 config_ = config;
651
Per Åhgren200feba2019-03-06 04:16:46 +0100652 if (aec_config_changed) {
653 InitializeEchoController();
654 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200655
saza0bad15f2019-10-16 11:46:11 +0200656 if (ns_config_changed) {
657 InitializeNoiseSuppressor();
658 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100659
Per Åhgren0aefbf02019-08-23 21:29:17 +0200660 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800661
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100662 if (agc1_config_changed) {
663 ApplyAgc1Config(config_.gain_controller1);
664 }
665
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100666 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700667 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100668 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
669 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100670 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100671 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700672 config_.gain_controller2 = AudioProcessing::Config::GainController2();
673 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200674 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200675 InitializePreAmplifier();
saza1d600522019-10-18 13:29:43 +0200676 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100677
saza1d600522019-10-18 13:29:43 +0200678 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
679 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100680 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100681
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200682 if (voice_detection_config_changed) {
683 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100684 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200685
686 // Reinitialization must happen after all submodule configuration to avoid
687 // additional reinitializations on the next capture / render processing call.
688 if (pipeline_config_changed) {
689 InitializeLocked(formats_.api_format);
690 }
peah88ac8532016-09-12 16:47:25 -0700691}
692
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100693void AudioProcessingImpl::ApplyAgc1Config(
694 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100695 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100696 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100697
Per Åhgren0e3198e2019-11-18 08:52:22 +0100698 if (!submodules_.agc_manager) {
699 error = submodules_.gain_control->set_mode(
700 Agc1ConfigModeToInterfaceMode(config.mode));
701 RTC_DCHECK_EQ(kNoError, error);
702 error = submodules_.gain_control->set_target_level_dbfs(
703 config.target_level_dbfs);
704 RTC_DCHECK_EQ(kNoError, error);
705 error = submodules_.gain_control->set_compression_gain_db(
706 config.compression_gain_db);
707 RTC_DCHECK_EQ(kNoError, error);
708 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
709 RTC_DCHECK_EQ(kNoError, error);
710 error = submodules_.gain_control->set_analog_level_limits(
711 config.analog_level_minimum, config.analog_level_maximum);
712 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100713 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100714}
715
peah88ac8532016-09-12 16:47:25 -0700716void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800717 // Run in a single-threaded manner when setting the extra options.
718 rtc::CritScope cs_render(&crit_render_);
719 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000720
Per Åhgrenf204faf2019-04-25 15:18:06 +0200721 capture_nonlocked_.use_aec2_extended_filter =
722 config.Get<ExtendedFilter>().enabled;
723 capture_nonlocked_.use_aec2_delay_agnostic =
724 config.Get<DelayAgnostic>().enabled;
725 capture_nonlocked_.use_aec2_refined_adaptive_filter =
726 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800727
peahdf3efa82015-11-28 12:35:15 -0800728 if (capture_.transient_suppressor_enabled !=
729 config.Get<ExperimentalNs>().enabled) {
730 capture_.transient_suppressor_enabled =
731 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000732 InitializeTransient();
733 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000734}
735
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000736int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800737 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700738 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000739}
740
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200741int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
742 return capture_.capture_fullband_audio
743 ? capture_.capture_fullband_audio->num_frames() * 100
744 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
745}
746
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000747int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800748 // Used as callback from submodules, hence locking is not allowed.
749 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000750}
751
Peter Kasting69558702016-01-12 16:26:35 -0800752size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800753 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700754 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000755}
756
Peter Kasting69558702016-01-12 16:26:35 -0800757size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800758 // Used as callback from submodules, hence locking is not allowed.
759 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000760}
761
Peter Kasting69558702016-01-12 16:26:35 -0800762size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800763 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200764 const bool experimental_multi_channel_capture =
765 config_.pipeline.experimental_multi_channel &&
766 constants_.experimental_multi_channel_capture_support;
767 if (capture_nonlocked_.echo_controller_enabled &&
768 !experimental_multi_channel_capture) {
769 return 1;
770 }
771 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800772}
773
Peter Kasting69558702016-01-12 16:26:35 -0800774size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800775 // Used as callback from submodules, hence locking is not allowed.
776 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000777}
778
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000779void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800780 rtc::CritScope cs(&crit_capture_);
781 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200782 if (submodules_.agc_manager.get()) {
783 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000784 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000785}
786
Alessio Bazzicac054e782018-04-16 12:10:09 +0200787void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200788 switch (setting.type()) {
789 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100790 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200791 render_runtime_settings_enqueuer_.Enqueue(setting);
792 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200793 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100794 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200795 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100796 capture_runtime_settings_enqueuer_.Enqueue(setting);
797 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200798 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200799 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100800 render_runtime_settings_enqueuer_.Enqueue(setting);
801 return;
802 case RuntimeSetting::Type::kNotSpecified:
803 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200804 return;
805 }
806 // The language allows the enum to have a non-enumerator
807 // value. Check that this doesn't happen.
808 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200809}
810
811AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
812 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200813 : runtime_settings_(*runtime_settings) {
814 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200815}
816
817AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
818 default;
819
820void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
821 RuntimeSetting setting) {
822 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200823 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200824 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200825 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200826 RTC_LOG(LS_ERROR)
827 << "The runtime settings queue is full. Oldest setting discarded.";
828 }
829 if (remaining_attempts == 0)
830 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
831}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000832
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000833int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700834 const StreamConfig& input_config,
835 const StreamConfig& output_config,
836 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800837 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800838 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700839 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800840 {
841 // Acquire the capture lock in order to safely call the function
842 // that retrieves the render side data. This function accesses apm
843 // getters that need the capture lock held when being called.
844 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700845 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800846
847 if (!src || !dest) {
848 return kNullPointerError;
849 }
850
851 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700852 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000853 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000854
Oskar Sundbom4b276482019-05-23 14:28:00 +0200855 if (processing_config.input_stream() != input_config) {
856 processing_config.input_stream() = input_config;
857 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800858 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200859
860 if (processing_config.output_stream() != output_config) {
861 processing_config.output_stream() = output_config;
862 reinitialization_required = true;
863 }
864
865 if (reinitialization_required) {
866 // Reinitialize.
867 rtc::CritScope cs_render(&crit_render_);
868 rtc::CritScope cs_capture(&crit_capture_);
869 RETURN_ON_ERR(InitializeLocked(processing_config));
870 }
871
peahdf3efa82015-11-28 12:35:15 -0800872 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700873 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
874 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000875
aleloi868f32f2017-05-23 07:20:05 -0700876 if (aec_dump_) {
877 RecordUnprocessedCaptureStream(src);
878 }
879
Per Åhgrena1351272019-08-15 12:15:46 +0200880 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800881 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200882 if (capture_.capture_fullband_audio) {
883 capture_.capture_fullband_audio->CopyFrom(
884 src, formats_.api_format.input_stream());
885 }
peahde65ddc2016-09-16 15:02:15 -0700886 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200887 if (capture_.capture_fullband_audio) {
888 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
889 dest);
890 } else {
891 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
892 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000893
aleloi868f32f2017-05-23 07:20:05 -0700894 if (aec_dump_) {
895 RecordProcessedCaptureStream(dest);
896 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000897 return kNoError;
898}
899
Alex Loiko73ec0192018-05-15 10:52:28 +0200900void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200901 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200902 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200903 if (aec_dump_) {
904 aec_dump_->WriteRuntimeSetting(setting);
905 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200906 switch (setting.type()) {
907 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200908 if (config_.pre_amplifier.enabled) {
909 float value;
910 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200911 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200912 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200913 }
914 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200915 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100916 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100917 if (!submodules_.agc_manager) {
918 float value;
919 setting.GetFloat(&value);
920 int int_value = static_cast<int>(value + .5f);
921 config_.gain_controller1.compression_gain_db = int_value;
922 int error =
923 submodules_.gain_control->set_compression_gain_db(int_value);
924 RTC_DCHECK_EQ(kNoError, error);
925 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100926 break;
927 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200928 case RuntimeSetting::Type::kCaptureFixedPostGain: {
929 if (config_.gain_controller2.enabled) {
930 float value;
931 setting.GetFloat(&value);
932 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200933 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200934 }
935 break;
936 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200937 case RuntimeSetting::Type::kPlayoutVolumeChange: {
938 int value;
939 setting.GetInt(&value);
940 capture_.playout_volume = value;
941 break;
942 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100943 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
944 RTC_NOTREACHED();
945 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200946 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
947 RTC_NOTREACHED();
948 break;
949 case RuntimeSetting::Type::kNotSpecified:
950 RTC_NOTREACHED();
951 break;
952 }
953 }
954}
955
956void AudioProcessingImpl::HandleRenderRuntimeSettings() {
957 RuntimeSetting setting;
958 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200959 if (aec_dump_) {
960 aec_dump_->WriteRuntimeSetting(setting);
961 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200962 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100963 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100964 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200965 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200966 if (submodules_.render_pre_processor) {
967 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200968 }
969 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100970 case RuntimeSetting::Type::kCapturePreGain: // fall-through
971 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200972 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200973 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200974 RTC_NOTREACHED();
975 break;
976 }
977 }
978}
979
peah9e6a2902017-05-15 07:19:21 -0700980void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800981 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700982
983 // Insert the samples into the queue.
saza1d600522019-10-18 13:29:43 +0200984 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +0200985 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +0200986 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
987 num_reverse_channels(),
988 &aec_render_queue_buffer_);
989
Per Åhgrenf204faf2019-04-25 15:18:06 +0200990 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
991 // The data queue is full and needs to be emptied.
992 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -0700993
Per Åhgrenf204faf2019-04-25 15:18:06 +0200994 // Retry the insert (should always work).
995 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
996 RTC_DCHECK(result);
997 }
peaha0624602016-10-25 04:45:24 -0700998 }
999
saza1d600522019-10-18 13:29:43 +02001000 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001001 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1002 num_reverse_channels(),
1003 &aecm_render_queue_buffer_);
1004 RTC_DCHECK(aecm_render_signal_queue_);
1005 // Insert the samples into the queue.
1006 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1007 // The data queue is full and needs to be emptied.
1008 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001009
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001010 // Retry the insert (should always work).
1011 bool result =
1012 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1013 RTC_DCHECK(result);
1014 }
peah764e3642016-10-22 05:04:30 -07001015 }
peah701d6282016-10-25 05:42:20 -07001016
Per Åhgren0e3198e2019-11-18 08:52:22 +01001017 if (!submodules_.agc_manager) {
peah701d6282016-10-25 05:42:20 -07001018 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
1019 // Insert the samples into the queue.
1020 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1021 // The data queue is full and needs to be emptied.
1022 EmptyQueuedRenderAudio();
1023
1024 // Retry the insert (should always work).
1025 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1026 RTC_DCHECK(result);
1027 }
1028 }
peah9e6a2902017-05-15 07:19:21 -07001029}
ivoc9f4a4a02016-10-28 05:39:16 -07001030
peah9e6a2902017-05-15 07:19:21 -07001031void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001032 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1033
1034 // Insert the samples into the queue.
1035 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1036 // The data queue is full and needs to be emptied.
1037 EmptyQueuedRenderAudio();
1038
1039 // Retry the insert (should always work).
1040 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1041 RTC_DCHECK(result);
1042 }
peah764e3642016-10-22 05:04:30 -07001043}
1044
1045void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001046 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001047 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001048
ivoc9f4a4a02016-10-28 05:39:16 -07001049 const size_t new_red_render_queue_element_max_size =
1050 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1051
peaha0624602016-10-25 04:45:24 -07001052 // Reallocate the queues if the queue item sizes are too small to fit the
1053 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001054
1055 if (agc_render_queue_element_max_size_ <
1056 new_agc_render_queue_element_max_size) {
1057 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1058
1059 std::vector<int16_t> template_queue_element(
1060 agc_render_queue_element_max_size_);
1061
1062 agc_render_signal_queue_.reset(
1063 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1064 kMaxNumFramesToBuffer, template_queue_element,
1065 RenderQueueItemVerifier<int16_t>(
1066 agc_render_queue_element_max_size_)));
1067
1068 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1069 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1070 } else {
1071 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001072 }
ivoc9f4a4a02016-10-28 05:39:16 -07001073
1074 if (red_render_queue_element_max_size_ <
1075 new_red_render_queue_element_max_size) {
1076 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1077
1078 std::vector<float> template_queue_element(
1079 red_render_queue_element_max_size_);
1080
1081 red_render_signal_queue_.reset(
1082 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1083 kMaxNumFramesToBuffer, template_queue_element,
1084 RenderQueueItemVerifier<float>(
1085 red_render_queue_element_max_size_)));
1086
1087 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1088 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1089 } else {
1090 red_render_signal_queue_->Clear();
1091 }
peah764e3642016-10-22 05:04:30 -07001092}
1093
1094void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1095 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001096 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02001097 RTC_DCHECK(aec_render_signal_queue_);
1098 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001099 submodules_.echo_cancellation->ProcessRenderAudio(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001100 aec_capture_queue_buffer_);
1101 }
peaha0624602016-10-25 04:45:24 -07001102 }
1103
saza1d600522019-10-18 13:29:43 +02001104 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001105 RTC_DCHECK(aecm_render_signal_queue_);
1106 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001107 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001108 aecm_capture_queue_buffer_);
1109 }
peah701d6282016-10-25 05:42:20 -07001110 }
1111
1112 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001113 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001114 }
ivoc9f4a4a02016-10-28 05:39:16 -07001115
1116 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001117 RTC_DCHECK(submodules_.echo_detector);
1118 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001119 }
peah764e3642016-10-22 05:04:30 -07001120}
1121
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001122int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001123 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001124 {
1125 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001126 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001127 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001128 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001129 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001130 }
peahfa6228e2015-11-16 16:27:42 -08001131
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001132 if (!frame) {
1133 return kNullPointerError;
1134 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001135 // Must be a native rate.
1136 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1137 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001138 frame->sample_rate_hz_ != kSampleRate32kHz &&
1139 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001140 return kBadSampleRateError;
1141 }
peah192164e2015-11-17 02:16:45 -08001142
peahdf3efa82015-11-28 12:35:15 -08001143 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001144 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001145 {
1146 // Aquire lock for the access of api_format.
1147 // The lock is released immediately due to the conditional
1148 // reinitialization.
1149 rtc::CritScope cs_capture(&crit_capture_);
1150 // TODO(ajm): The input and output rates and channels are currently
1151 // constrained to be identical in the int16 interface.
1152 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001153
1154 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001155 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001156
Oskar Sundbom4b276482019-05-23 14:28:00 +02001157 reinitialization_required =
1158 reinitialization_required ||
1159 processing_config.input_stream().sample_rate_hz() !=
1160 frame->sample_rate_hz_ ||
1161 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1162 processing_config.output_stream().sample_rate_hz() !=
1163 frame->sample_rate_hz_ ||
1164 processing_config.output_stream().num_channels() != frame->num_channels_;
1165
1166 if (reinitialization_required) {
1167 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1168 processing_config.input_stream().set_num_channels(frame->num_channels_);
1169 processing_config.output_stream().set_sample_rate_hz(
1170 frame->sample_rate_hz_);
1171 processing_config.output_stream().set_num_channels(frame->num_channels_);
1172
1173 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001174 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001175 rtc::CritScope cs_capture(&crit_capture_);
1176 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001177 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001178
peahdf3efa82015-11-28 12:35:15 -08001179 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001180 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001181 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001182 return kBadDataLengthError;
1183 }
1184
aleloi868f32f2017-05-23 07:20:05 -07001185 if (aec_dump_) {
1186 RecordUnprocessedCaptureStream(*frame);
1187 }
1188
Per Åhgrend47941e2019-08-22 11:51:13 +02001189 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001190 if (capture_.capture_fullband_audio) {
1191 capture_.capture_fullband_audio->CopyFrom(frame);
1192 }
peahde65ddc2016-09-16 15:02:15 -07001193 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001194 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001195 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001196 if (capture_.capture_fullband_audio) {
1197 capture_.capture_fullband_audio->CopyTo(frame);
1198 } else {
1199 capture_.capture_audio->CopyTo(frame);
1200 }
Per Åhgrena1351272019-08-15 12:15:46 +02001201 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001202 if (capture_.stats.voice_detected) {
1203 frame->vad_activity_ = *capture_.stats.voice_detected
1204 ? AudioFrame::kVadActive
1205 : AudioFrame::kVadPassive;
1206 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001207
aleloi868f32f2017-05-23 07:20:05 -07001208 if (aec_dump_) {
1209 RecordProcessedCaptureStream(*frame);
1210 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001211
1212 return kNoError;
1213}
1214
peahde65ddc2016-09-16 15:02:15 -07001215int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001216 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001217
peahb58a1582016-03-15 09:34:24 -07001218 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001219 // TODO(peah): Simplify once the public API Enable functions for these
1220 // are moved to APM.
saza1d600522019-10-18 13:29:43 +02001221 RTC_DCHECK_LE(!!submodules_.echo_controller +
1222 !!submodules_.echo_cancellation +
1223 !!submodules_.echo_control_mobile,
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001224 1);
peahb58a1582016-03-15 09:34:24 -07001225
peahde65ddc2016-09-16 15:02:15 -07001226 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001227
saza1d600522019-10-18 13:29:43 +02001228 if (submodules_.pre_amplifier) {
1229 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001230 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001231 capture_buffer->num_frames()));
1232 }
1233
Per Åhgren928146f2019-08-20 09:19:21 +02001234 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001235 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001236 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001237 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1238 if (log_rms) {
1239 capture_rms_interval_counter_ = 0;
1240 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001241 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1242 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1243 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1244 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001245 }
1246
saza1d600522019-10-18 13:29:43 +02001247 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001248 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001249 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001250 capture_.echo_path_gain_change =
1251 capture_.prev_analog_mic_level != analog_mic_level &&
1252 capture_.prev_analog_mic_level != -1;
1253 capture_.prev_analog_mic_level = analog_mic_level;
1254
Per Åhgrend2650d12018-10-02 17:00:59 +02001255 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001256 if (submodules_.pre_amplifier) {
1257 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001258 capture_.echo_path_gain_change =
1259 capture_.echo_path_gain_change ||
1260 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001261 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001262 capture_.prev_pre_amp_gain = pre_amp_gain;
1263 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001264
1265 // Detect volume change.
1266 capture_.echo_path_gain_change =
1267 capture_.echo_path_gain_change ||
1268 (capture_.prev_playout_volume != capture_.playout_volume &&
1269 capture_.prev_playout_volume >= 0);
1270 capture_.prev_playout_volume = capture_.playout_volume;
1271
saza1d600522019-10-18 13:29:43 +02001272 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001273 }
1274
Per Åhgren3daedb62019-11-22 12:11:40 +01001275 if (constants_.use_experimental_agc &&
1276 submodules_.gain_control->is_enabled()) {
1277 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001278 }
1279
peah2ace3f92016-09-10 04:42:27 -07001280 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1281 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001282 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1283 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001284 }
1285
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001286 const bool experimental_multi_channel_capture =
1287 config_.pipeline.experimental_multi_channel &&
1288 constants_.experimental_multi_channel_capture_support;
saza1d600522019-10-18 13:29:43 +02001289 if (submodules_.echo_controller && !experimental_multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001290 // Force down-mixing of the number of channels after the detection of
1291 // capture signal saturation.
1292 // TODO(peah): Look into ensuring that this kind of tampering with the
1293 // AudioBuffer functionality should not be needed.
1294 capture_buffer->set_num_channels(1);
1295 }
1296
saza1d600522019-10-18 13:29:43 +02001297 if (submodules_.high_pass_filter) {
1298 submodules_.high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001299 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001300
saza1d600522019-10-18 13:29:43 +02001301 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001302 RTC_DCHECK(
1303 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
saza1d600522019-10-18 13:29:43 +02001304 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001305 submodules_.noise_suppressor->Analyze(*capture_buffer);
1306 } else if (submodules_.legacy_noise_suppressor) {
1307 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001308 }
peahb58a1582016-03-15 09:34:24 -07001309
saza1d600522019-10-18 13:29:43 +02001310 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001311 // Ensure that the stream delay was set before the call to the
1312 // AECM ProcessCaptureAudio function.
1313 if (!was_stream_delay_set()) {
1314 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001315 }
1316
saza1d600522019-10-18 13:29:43 +02001317 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001318 submodules_.noise_suppressor->Process(capture_buffer);
1319 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001320 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001321 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001322 }
peahe0eae3c2016-12-14 01:16:23 -08001323
saza1d600522019-10-18 13:29:43 +02001324 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001325 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001326 } else {
saza1d600522019-10-18 13:29:43 +02001327 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001328 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1329
1330 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001331 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001332 }
1333
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001334 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
saza1d600522019-10-18 13:29:43 +02001335 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001336 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
saza1d600522019-10-18 13:29:43 +02001337 } else if (submodules_.echo_cancellation) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001338 // Ensure that the stream delay was set before the call to the
1339 // AEC ProcessCaptureAudio function.
1340 if (!was_stream_delay_set()) {
1341 return AudioProcessing::kStreamParameterNotSetError;
1342 }
1343
saza1d600522019-10-18 13:29:43 +02001344 RETURN_ON_ERR(submodules_.echo_cancellation->ProcessCaptureAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001345 capture_buffer, stream_delay_ms()));
1346 }
1347
saza1d600522019-10-18 13:29:43 +02001348 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001349 submodules_.noise_suppressor->Process(capture_buffer);
1350 } else if (submodules_.legacy_noise_suppressor) {
1351 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001352 }
Per Åhgren46537a32017-06-07 10:08:10 +02001353 }
ivoc9f4a4a02016-10-28 05:39:16 -07001354
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001355 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001356 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001357 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001358 } else {
1359 capture_.stats.voice_detected = absl::nullopt;
1360 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001361
Per Åhgren3daedb62019-11-22 12:11:40 +01001362 if (constants_.use_experimental_agc &&
1363 submodules_.gain_control->is_enabled()) {
1364 submodules_.agc_manager->Process(capture_buffer);
1365
1366 absl::optional<int> new_digital_gain =
1367 submodules_.agc_manager->GetDigitalComressionGain();
1368 if (new_digital_gain) {
1369 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1370 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001371 }
Per Åhgren200feba2019-03-06 04:16:46 +01001372 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001373 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1374 capture_buffer, submodules_.echo_cancellation &&
1375 submodules_.echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001376
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001377 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001378 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001379 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1380 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001381 }
1382
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001383 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001384 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001385 bool ec_active = ec ? ec->ActiveProcessing() : false;
1386 // Only update the fullband buffer if the multiband processing has changed
1387 // the signal. Keep the original signal otherwise.
1388 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1389 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1390 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001391 capture_buffer = capture_.capture_fullband_audio.get();
1392 }
1393
peah9e6a2902017-05-15 07:19:21 -07001394 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001395 RTC_DCHECK(submodules_.echo_detector);
1396 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1397 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001398 }
1399
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001400 // TODO(aluebs): Investigate if the transient suppression placement should be
1401 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001402 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001403 float voice_probability = submodules_.agc_manager.get()
1404 ? submodules_.agc_manager->voice_probability()
1405 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001406
saza1d600522019-10-18 13:29:43 +02001407 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001408 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001409 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001410 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001411 capture_buffer->num_frames_per_band(),
1412 capture_.keyboard_info.keyboard_data,
1413 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001414 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001415 }
1416
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001417 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001418 if (submodules_.capture_analyzer) {
1419 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001420 }
1421
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001422 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001423 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001424 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001425 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001426 }
1427
saza1d600522019-10-18 13:29:43 +02001428 if (submodules_.capture_post_processor) {
1429 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001430 }
1431
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001432 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001433 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001434 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1435 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001436 } else {
1437 capture_.stats.output_rms_dbfs = absl::nullopt;
1438 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001439
Per Åhgren928146f2019-08-20 09:19:21 +02001440 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001441 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001442 capture_nonlocked_.capture_processing_format.num_frames()));
1443 if (log_rms) {
1444 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1445 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1446 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1447 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1448 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1449 }
1450
Per Åhgren0e3198e2019-11-18 08:52:22 +01001451 if (submodules_.agc_manager) {
1452 int level = recommended_stream_analog_level();
1453 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1454 &level);
1455 }
1456
peahdf3efa82015-11-28 12:35:15 -08001457 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001458 return kNoError;
1459}
1460
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001461int AudioProcessingImpl::AnalyzeReverseStream(
1462 const float* const* data,
1463 const StreamConfig& reverse_config) {
1464 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1465 rtc::CritScope cs(&crit_render_);
1466 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1467}
1468
peahde65ddc2016-09-16 15:02:15 -07001469int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1470 const StreamConfig& input_config,
1471 const StreamConfig& output_config,
1472 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001473 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001474 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001475 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001476 if (submodule_states_.RenderMultiBandProcessingActive() ||
1477 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001478 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1479 dest);
peah2ace3f92016-09-10 04:42:27 -07001480 } else if (formats_.api_format.reverse_input_stream() !=
1481 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001482 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1483 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001484 } else {
peahde65ddc2016-09-16 15:02:15 -07001485 CopyAudioIfNeeded(src, input_config.num_frames(),
1486 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001487 }
1488
1489 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001490}
1491
peahdf3efa82015-11-28 12:35:15 -08001492int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001493 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001494 const StreamConfig& input_config,
1495 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001496 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001497 return kNullPointerError;
1498 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001499
peahde65ddc2016-09-16 15:02:15 -07001500 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001501 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001502 }
1503
peahdf3efa82015-11-28 12:35:15 -08001504 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001505 processing_config.reverse_input_stream() = input_config;
1506 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001507
peahdf3efa82015-11-28 12:35:15 -08001508 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001509 RTC_DCHECK_EQ(input_config.num_frames(),
1510 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001511
aleloi868f32f2017-05-23 07:20:05 -07001512 if (aec_dump_) {
1513 const size_t channel_size =
1514 formats_.api_format.reverse_input_stream().num_frames();
1515 const size_t num_channels =
1516 formats_.api_format.reverse_input_stream().num_channels();
1517 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001518 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001519 }
peahdf3efa82015-11-28 12:35:15 -08001520 render_.render_audio->CopyFrom(src,
1521 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001522 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001523}
1524
1525int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001526 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001527 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001528 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001529 return kNullPointerError;
1530 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001531 // Must be a native rate.
1532 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1533 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001534 frame->sample_rate_hz_ != kSampleRate32kHz &&
1535 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001536 return kBadSampleRateError;
1537 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001538
Michael Graczyk86c6d332015-07-23 11:41:39 -07001539 if (frame->num_channels_ <= 0) {
1540 return kBadNumberChannelsError;
1541 }
1542
peahdf3efa82015-11-28 12:35:15 -08001543 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001544 processing_config.reverse_input_stream().set_sample_rate_hz(
1545 frame->sample_rate_hz_);
1546 processing_config.reverse_input_stream().set_num_channels(
1547 frame->num_channels_);
1548 processing_config.reverse_output_stream().set_sample_rate_hz(
1549 frame->sample_rate_hz_);
1550 processing_config.reverse_output_stream().set_num_channels(
1551 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001552
peahdf3efa82015-11-28 12:35:15 -08001553 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001554 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001555 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001556 return kBadDataLengthError;
1557 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001558
aleloi868f32f2017-05-23 07:20:05 -07001559 if (aec_dump_) {
1560 aec_dump_->WriteRenderStreamMessage(*frame);
1561 }
1562
Per Åhgrend47941e2019-08-22 11:51:13 +02001563 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001564 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001565 if (submodule_states_.RenderMultiBandProcessingActive() ||
1566 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001567 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001568 }
aluebsb0319552016-03-17 20:39:53 -07001569 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001570}
niklase@google.com470e71d2011-07-07 08:21:25 +00001571
peahde65ddc2016-09-16 15:02:15 -07001572int AudioProcessingImpl::ProcessRenderStreamLocked() {
1573 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001574
Alex Loiko73ec0192018-05-15 10:52:28 +02001575 HandleRenderRuntimeSettings();
1576
saza1d600522019-10-18 13:29:43 +02001577 if (submodules_.render_pre_processor) {
1578 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001579 }
1580
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001581 QueueNonbandedRenderAudio(render_buffer);
1582
peah2ace3f92016-09-10 04:42:27 -07001583 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001584 SampleRateSupportsMultiBand(
1585 formats_.render_processing_format.sample_rate_hz())) {
1586 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001587 }
1588
peahce4d9152017-05-19 01:28:05 -07001589 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1590 QueueBandedRenderAudio(render_buffer);
1591 }
1592
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001593 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001594 if (submodules_.echo_controller) {
1595 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001596 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001597
peah2ace3f92016-09-10 04:42:27 -07001598 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001599 SampleRateSupportsMultiBand(
1600 formats_.render_processing_format.sample_rate_hz())) {
1601 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001602 }
1603
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001604 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001605}
1606
1607int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001608 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001609 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001610 capture_.was_stream_delay_set = true;
1611 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001612
niklase@google.com470e71d2011-07-07 08:21:25 +00001613 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001614 delay = 0;
1615 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001616 }
1617
1618 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1619 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001620 delay = 500;
1621 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001622 }
1623
peahdf3efa82015-11-28 12:35:15 -08001624 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001625 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001626}
1627
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001628bool AudioProcessingImpl::GetLinearAecOutput(
1629 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1630 rtc::CritScope cs(&crit_capture_);
1631 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1632
1633 RTC_DCHECK(linear_aec_buffer);
1634 if (linear_aec_buffer) {
1635 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1636 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1637
1638 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1639 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1640 rtc::ArrayView<const float> channel_view =
1641 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1642 linear_aec_buffer->num_frames());
1643 std::copy(channel_view.begin(), channel_view.end(),
1644 linear_output[ch].begin());
1645 }
1646 return true;
1647 }
1648 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1649 RTC_NOTREACHED();
1650 return false;
1651}
1652
niklase@google.com470e71d2011-07-07 08:21:25 +00001653int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001654 // Used as callback from submodules, hence locking is not allowed.
1655 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001656}
1657
1658bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001659 // Used as callback from submodules, hence locking is not allowed.
1660 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001661}
1662
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001663void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001664 rtc::CritScope cs(&crit_capture_);
1665 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001666}
1667
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001668void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001669 rtc::CritScope cs(&crit_capture_);
1670 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001671}
1672
1673int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001674 rtc::CritScope cs(&crit_capture_);
1675 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001676}
1677
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001678void AudioProcessingImpl::set_stream_analog_level(int level) {
1679 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001680
1681 if (submodules_.agc_manager) {
1682 submodules_.agc_manager->set_stream_analog_level(level);
1683 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1684 1, &level);
1685 } else {
1686 int error = submodules_.gain_control->set_stream_analog_level(level);
1687 RTC_DCHECK_EQ(kNoError, error);
1688 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001689}
1690
1691int AudioProcessingImpl::recommended_stream_analog_level() const {
1692 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001693 if (submodules_.agc_manager) {
1694 return submodules_.agc_manager->stream_analog_level();
1695 }
1696 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001697}
1698
aleloi868f32f2017-05-23 07:20:05 -07001699void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1700 RTC_DCHECK(aec_dump);
1701 rtc::CritScope cs_render(&crit_render_);
1702 rtc::CritScope cs_capture(&crit_capture_);
1703
1704 // The previously attached AecDump will be destroyed with the
1705 // 'aec_dump' parameter, which is after locks are released.
1706 aec_dump_.swap(aec_dump);
1707 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001708 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001709}
1710
1711void AudioProcessingImpl::DetachAecDump() {
1712 // The d-tor of a task-queue based AecDump blocks until all pending
1713 // tasks are done. This construction avoids blocking while holding
1714 // the render and capture locks.
1715 std::unique_ptr<AecDump> aec_dump = nullptr;
1716 {
1717 rtc::CritScope cs_render(&crit_render_);
1718 rtc::CritScope cs_capture(&crit_capture_);
1719 aec_dump = std::move(aec_dump_);
1720 }
1721}
1722
Sam Zackrisson4d364492018-03-02 16:03:21 +01001723void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1724 std::unique_ptr<AudioGenerator> audio_generator) {
1725 // TODO(bugs.webrtc.org/8882) Stub.
1726 // Reset internal audio generator with audio_generator.
1727}
1728
1729void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1730 // TODO(bugs.webrtc.org/8882) Stub.
1731 // Delete audio generator, if one is attached.
1732}
1733
Ivo Creusen56d46092017-11-24 17:29:59 +01001734AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001735 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001736 rtc::CritScope cs_capture(&crit_capture_);
1737 if (!has_remote_tracks) {
1738 return capture_.stats;
1739 }
1740 AudioProcessingStats stats = capture_.stats;
1741 EchoCancellationImpl::Metrics metrics;
saza1d600522019-10-18 13:29:43 +02001742 if (submodules_.echo_controller) {
1743 auto ec_metrics = submodules_.echo_controller->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001744 stats.echo_return_loss = ec_metrics.echo_return_loss;
1745 stats.echo_return_loss_enhancement =
1746 ec_metrics.echo_return_loss_enhancement;
1747 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001748 }
1749 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001750 RTC_DCHECK(submodules_.echo_detector);
1751 auto ed_metrics = submodules_.echo_detector->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001752 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1753 stats.residual_echo_likelihood_recent_max =
1754 ed_metrics.echo_likelihood_recent_max;
1755 }
Ivo Creusenae026092017-11-20 13:07:16 +01001756 return stats;
1757}
1758
peah8271d042016-11-22 07:24:52 -08001759void AudioProcessingImpl::MutateConfig(
1760 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1761 rtc::CritScope cs_render(&crit_render_);
1762 rtc::CritScope cs_capture(&crit_capture_);
1763 mutator(&config_);
1764 ApplyConfig(config_);
1765}
1766
1767AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1768 rtc::CritScope cs_render(&crit_render_);
1769 rtc::CritScope cs_capture(&crit_capture_);
1770 return config_;
1771}
1772
peah2ace3f92016-09-10 04:42:27 -07001773bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1774 return submodule_states_.Update(
saza1d600522019-10-18 13:29:43 +02001775 config_.high_pass_filter.enabled, !!submodules_.echo_cancellation,
1776 !!submodules_.echo_control_mobile, config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001777 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
1778 submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled,
1779 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 11:46:11 +02001780 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001781}
1782
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001783void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001784 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001785 if (!submodules_.transient_suppressor.get()) {
1786 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001787 }
saza1d600522019-10-18 13:29:43 +02001788 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1789 capture_nonlocked_.split_rate,
1790 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001791 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001792}
1793
Per Åhgren0aefbf02019-08-23 21:29:17 +02001794void AudioProcessingImpl::InitializeHighPassFilter() {
1795 if (submodule_states_.HighPassFilteringRequired()) {
saza1d600522019-10-18 13:29:43 +02001796 submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001797 } else {
saza1d600522019-10-18 13:29:43 +02001798 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001799 }
1800}
alessiob3ec96df2017-05-22 06:57:06 -07001801
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001802void AudioProcessingImpl::InitializeVoiceDetector() {
1803 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001804 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001805 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1806 } else {
saza1d600522019-10-18 13:29:43 +02001807 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001808 }
1809}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001810void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001811 bool use_echo_controller =
1812 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001813 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001814 !config_.echo_canceller.use_legacy_aec);
1815
1816 if (use_echo_controller) {
1817 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001818 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001819 submodules_.echo_controller = echo_control_factory_->Create(
1820 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001821 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001822 } else {
saza1d600522019-10-18 13:29:43 +02001823 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001824 EchoCanceller3Config(), proc_sample_rate_hz(), num_reverse_channels(),
1825 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001826 }
1827
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001828 // Setup the storage for returning the linear AEC output.
1829 if (config_.echo_canceller.export_linear_aec_output) {
1830 constexpr int kLinearOutputRateHz = 16000;
1831 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1832 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1833 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1834 } else {
1835 capture_.linear_aec_output.reset();
1836 }
1837
Per Åhgren200feba2019-03-06 04:16:46 +01001838 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001839
saza1d600522019-10-18 13:29:43 +02001840 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001841 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001842 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001843 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001844 return;
peahe0eae3c2016-12-14 01:16:23 -08001845 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001846
saza1d600522019-10-18 13:29:43 +02001847 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001848 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001849 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001850
1851 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001852 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001853 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001854 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001855 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001856 return;
1857 }
1858
1859 if (config_.echo_canceller.mobile_mode) {
1860 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001861 size_t max_element_size =
1862 std::max(static_cast<size_t>(1),
1863 kMaxAllowedValuesOfSamplesPerBand *
1864 EchoControlMobileImpl::NumCancellersRequired(
1865 num_output_channels(), num_reverse_channels()));
1866
1867 std::vector<int16_t> template_queue_element(max_element_size);
1868
1869 aecm_render_signal_queue_.reset(
1870 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1871 kMaxNumFramesToBuffer, template_queue_element,
1872 RenderQueueItemVerifier<int16_t>(max_element_size)));
1873
1874 aecm_render_queue_buffer_.resize(max_element_size);
1875 aecm_capture_queue_buffer_.resize(max_element_size);
1876
saza1d600522019-10-18 13:29:43 +02001877 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001878
saza1d600522019-10-18 13:29:43 +02001879 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1880 num_reverse_channels(),
1881 num_output_channels());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001882
saza1d600522019-10-18 13:29:43 +02001883 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001884 aec_render_signal_queue_.reset();
1885 return;
1886 }
1887
saza1d600522019-10-18 13:29:43 +02001888 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001889 aecm_render_signal_queue_.reset();
1890
Per Åhgrenf204faf2019-04-25 15:18:06 +02001891 // Create and activate AEC2.
saza1d600522019-10-18 13:29:43 +02001892 submodules_.echo_cancellation.reset(new EchoCancellationImpl());
1893 submodules_.echo_cancellation->SetExtraOptions(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001894 capture_nonlocked_.use_aec2_extended_filter,
1895 capture_nonlocked_.use_aec2_delay_agnostic,
1896 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1897
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001898 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001899 std::max(static_cast<size_t>(1),
1900 kMaxAllowedValuesOfSamplesPerBand *
1901 EchoCancellationImpl::NumCancellersRequired(
1902 num_output_channels(), num_reverse_channels()));
1903
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001904 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001905
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001906 aec_render_signal_queue_.reset(
1907 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1908 kMaxNumFramesToBuffer, template_queue_element,
1909 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001910
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001911 aec_render_queue_buffer_.resize(element_max_size);
1912 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001913
saza1d600522019-10-18 13:29:43 +02001914 submodules_.echo_cancellation->Initialize(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001915 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1916 num_proc_channels());
1917
saza1d600522019-10-18 13:29:43 +02001918 submodules_.echo_cancellation->set_suppression_level(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001919 config_.echo_canceller.legacy_moderate_suppression_level
1920 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1921 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001922}
peah8271d042016-11-22 07:24:52 -08001923
alessiob3ec96df2017-05-22 06:57:06 -07001924void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001925 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001926 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001927 }
1928}
1929
saza0bad15f2019-10-16 11:46:11 +02001930void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001931 submodules_.legacy_noise_suppressor.reset();
1932 submodules_.noise_suppressor.reset();
1933
saza0bad15f2019-10-16 11:46:11 +02001934 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001935 const bool use_legacy_ns =
1936 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1937
1938 if (!use_legacy_ns) {
1939 auto map_level =
1940 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1941 using NoiseSuppresionConfig =
1942 AudioProcessing::Config::NoiseSuppression;
1943 switch (level) {
1944 case NoiseSuppresionConfig::kLow:
1945 return NsConfig::SuppressionLevel::k6dB;
1946 case NoiseSuppresionConfig::kModerate:
1947 return NsConfig::SuppressionLevel::k12dB;
1948 case NoiseSuppresionConfig::kHigh:
1949 return NsConfig::SuppressionLevel::k18dB;
1950 case NoiseSuppresionConfig::kVeryHigh:
1951 return NsConfig::SuppressionLevel::k21dB;
1952 default:
1953 RTC_NOTREACHED();
1954 }
1955 };
1956
1957 NsConfig cfg;
1958 cfg.target_level = map_level(config_.noise_suppression.level);
1959 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1960 cfg, proc_sample_rate_hz(), num_proc_channels());
1961 } else {
1962 auto ns_level =
1963 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1964 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1965 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1966 }
saza0bad15f2019-10-16 11:46:11 +02001967 }
1968}
1969
Alex Loikob5c9a792018-04-16 16:31:22 +02001970void AudioProcessingImpl::InitializePreAmplifier() {
1971 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001972 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001973 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1974 } else {
saza1d600522019-10-18 13:29:43 +02001975 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001976 }
1977}
1978
ivoc9f4a4a02016-10-28 05:39:16 -07001979void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02001980 RTC_DCHECK(submodules_.echo_detector);
1981 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001982 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02001983 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001984}
1985
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001986void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02001987 if (submodules_.capture_analyzer) {
1988 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
1989 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001990 }
1991}
1992
Sam Zackrisson0beac582017-09-25 12:04:02 +02001993void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02001994 if (submodules_.capture_post_processor) {
1995 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001996 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02001997 }
1998}
1999
Alex Loiko5825aa62017-12-18 16:02:40 +01002000void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002001 if (submodules_.render_pre_processor) {
2002 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002003 formats_.render_processing_format.sample_rate_hz(),
2004 formats_.render_processing_format.num_channels());
2005 }
2006}
2007
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002008void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002009
aleloi868f32f2017-05-23 07:20:05 -07002010void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2011 if (!aec_dump_) {
2012 return;
2013 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002014
2015 std::string experiments_description = "";
saza1d600522019-10-18 13:29:43 +02002016 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02002017 experiments_description +=
saza1d600522019-10-18 13:29:43 +02002018 submodules_.echo_cancellation->GetExperimentsDescription();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002019 }
aleloi868f32f2017-05-23 07:20:05 -07002020 // TODO(peah): Add semicolon-separated concatenations of experiment
2021 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002022 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2023 experiments_description += "AgcClippingLevelExperiment;";
2024 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002025 if (capture_nonlocked_.echo_controller_enabled) {
2026 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002027 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002028 if (config_.gain_controller2.enabled) {
2029 experiments_description += "GainController2;";
2030 }
aleloi868f32f2017-05-23 07:20:05 -07002031
2032 InternalAPMConfig apm_config;
2033
Per Åhgren200feba2019-03-06 04:16:46 +01002034 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002035 apm_config.aec_delay_agnostic_enabled =
saza1d600522019-10-18 13:29:43 +02002036 submodules_.echo_cancellation &&
2037 submodules_.echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002038 apm_config.aec_drift_compensation_enabled =
saza1d600522019-10-18 13:29:43 +02002039 submodules_.echo_cancellation &&
2040 submodules_.echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002041 apm_config.aec_extended_filter_enabled =
saza1d600522019-10-18 13:29:43 +02002042 submodules_.echo_cancellation &&
2043 submodules_.echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002044 apm_config.aec_suppression_level =
saza1d600522019-10-18 13:29:43 +02002045 submodules_.echo_cancellation
2046 ? static_cast<int>(submodules_.echo_cancellation->suppression_level())
Per Åhgrenf204faf2019-04-25 15:18:06 +02002047 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002048
saza1d600522019-10-18 13:29:43 +02002049 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002050 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002051 submodules_.echo_control_mobile &&
2052 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002053 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002054 submodules_.echo_control_mobile
2055 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002056 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002057
saza1d600522019-10-18 13:29:43 +02002058 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
2059 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07002060 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02002061 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01002062 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002063
2064 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2065
saza0bad15f2019-10-16 11:46:11 +02002066 apm_config.ns_enabled = config_.noise_suppression.enabled;
2067 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002068
2069 apm_config.transient_suppression_enabled =
2070 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002071 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002072 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2073 apm_config.pre_amplifier_fixed_gain_factor =
2074 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002075
2076 if (!forced && apm_config == apm_config_for_aec_dump_) {
2077 return;
2078 }
2079 aec_dump_->WriteConfig(apm_config);
2080 apm_config_for_aec_dump_ = apm_config;
2081}
2082
2083void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2084 const float* const* src) {
2085 RTC_DCHECK(aec_dump_);
2086 WriteAecDumpConfigMessage(false);
2087
2088 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2089 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2090 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002091 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002092 RecordAudioProcessingState();
2093}
2094
2095void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2096 const AudioFrame& capture_frame) {
2097 RTC_DCHECK(aec_dump_);
2098 WriteAecDumpConfigMessage(false);
2099
2100 aec_dump_->AddCaptureStreamInput(capture_frame);
2101 RecordAudioProcessingState();
2102}
2103
2104void AudioProcessingImpl::RecordProcessedCaptureStream(
2105 const float* const* processed_capture_stream) {
2106 RTC_DCHECK(aec_dump_);
2107
2108 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2109 const size_t num_channels =
2110 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002111 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2112 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002113 aec_dump_->WriteCaptureStreamMessage();
2114}
2115
2116void AudioProcessingImpl::RecordProcessedCaptureStream(
2117 const AudioFrame& processed_capture_frame) {
2118 RTC_DCHECK(aec_dump_);
2119
2120 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2121 aec_dump_->WriteCaptureStreamMessage();
2122}
2123
2124void AudioProcessingImpl::RecordAudioProcessingState() {
2125 RTC_DCHECK(aec_dump_);
2126 AecDump::AudioProcessingState audio_proc_state;
2127 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2128 audio_proc_state.drift =
saza1d600522019-10-18 13:29:43 +02002129 submodules_.echo_cancellation
2130 ? submodules_.echo_cancellation->stream_drift_samples()
Per Åhgrenf204faf2019-04-25 15:18:06 +02002131 : 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002132 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002133 audio_proc_state.keypress = capture_.key_pressed;
2134 aec_dump_->AddAudioProcessingState(audio_proc_state);
2135}
2136
kwiberg83ffe452016-08-29 14:46:07 -07002137AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002138 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002139 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002140 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002141 output_will_be_muted(false),
2142 key_pressed(false),
2143 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002144 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002145 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002146 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002147 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002148 prev_pre_amp_gain(-1.f),
2149 playout_volume(-1),
2150 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002151
2152AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2153
Per Åhgrena1351272019-08-15 12:15:46 +02002154void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2155 const float* const* data,
2156 const StreamConfig& stream_config) {
2157 if (stream_config.has_keyboard()) {
2158 keyboard_data = data[stream_config.num_channels()];
2159 } else {
2160 keyboard_data = NULL;
2161 }
2162 num_keyboard_frames = stream_config.num_frames();
2163}
2164
kwiberg83ffe452016-08-29 14:46:07 -07002165AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2166
2167AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2168
niklase@google.com470e71d2011-07-07 08:21:25 +00002169} // namespace webrtc