blob: 3e49c0cb76ed16b1bad5a2ed6a3c9e4cae235c80 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
alessiob3ec96df2017-05-22 06:57:06 -070016#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020017#include <type_traits>
18#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Yves Gerey988cc082018-10-23 12:03:01 +020020#include "absl/types/optional.h"
21#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/include/audio_util.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020024#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/common.h"
Yves Gerey988cc082018-10-23 12:03:01 +020027#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 21:42:56 +010028#include "modules/audio_processing/logging/apm_data_dumper.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/ref_counted_object.h"
34#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020036#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000038
Michael Graczyk86c6d332015-07-23 11:41:39 -070039#define RETURN_ON_ERR(expr) \
40 do { \
41 int err = (expr); \
42 if (err != kNoError) { \
43 return err; \
44 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000045 } while (0)
46
niklase@google.com470e71d2011-07-07 08:21:25 +000047namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070048
kwibergd59d3bb2016-09-13 07:49:33 -070049constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020050constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070051
Michael Graczyk86c6d332015-07-23 11:41:39 -070052namespace {
53
54static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
55 switch (layout) {
56 case AudioProcessing::kMono:
57 case AudioProcessing::kStereo:
58 return false;
59 case AudioProcessing::kMonoAndKeyboard:
60 case AudioProcessing::kStereoAndKeyboard:
61 return true;
62 }
63
kwiberg9e2be5f2016-09-14 05:23:22 -070064 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070065 return false;
66}
aluebsdf6416a2016-03-16 18:26:35 -070067
peah2ace3f92016-09-10 04:42:27 -070068bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070069 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
70 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
71}
72
Per Åhgren0cbb58e2019-10-29 22:59:44 +010073// Checks whether the legacy ns functionality should be enforced.
74bool DetectLegacyNsEnforcement() {
75 return field_trial::IsEnabled("WebRTC-NewNoiseSuppressionKillSwitch");
76}
77
Per Åhgrenb2b58d82019-12-02 14:59:40 +010078// Checks whether AEC3 should be allowed to decide what the default
79// configuration should be based on the render and capture channel configuration
80// at hand.
81bool UseSetupSpecificDefaultAec3Congfig() {
82 return !field_trial::IsEnabled(
83 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
84}
85
Per Åhgrenc8626b62019-08-23 15:49:51 +020086// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020087int SuitableProcessRate(int minimum_rate,
88 int max_splitting_rate,
89 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020090 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020091 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020092 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070093 if (rate >= uppermost_native_rate) {
94 return uppermost_native_rate;
95 }
96 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070097 return rate;
98 }
99 }
peah2ace3f92016-09-10 04:42:27 -0700100 RTC_NOTREACHED();
101 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700102}
103
Sam Zackrisson23513132019-01-11 15:10:32 +0100104NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
105 AudioProcessing::Config::NoiseSuppression::Level level) {
106 using NsConfig = AudioProcessing::Config::NoiseSuppression;
107 switch (level) {
108 case NsConfig::kLow:
saza0bad15f2019-10-16 11:46:11 +0200109 return NoiseSuppression::Level::kLow;
Sam Zackrisson23513132019-01-11 15:10:32 +0100110 case NsConfig::kModerate:
saza0bad15f2019-10-16 11:46:11 +0200111 return NoiseSuppression::Level::kModerate;
Sam Zackrisson23513132019-01-11 15:10:32 +0100112 case NsConfig::kHigh:
saza0bad15f2019-10-16 11:46:11 +0200113 return NoiseSuppression::Level::kHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100114 case NsConfig::kVeryHigh:
saza0bad15f2019-10-16 11:46:11 +0200115 return NoiseSuppression::Level::kVeryHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100116 default:
117 RTC_NOTREACHED();
118 }
119}
120
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100121GainControl::Mode Agc1ConfigModeToInterfaceMode(
122 AudioProcessing::Config::GainController1::Mode mode) {
123 using Agc1Config = AudioProcessing::Config::GainController1;
124 switch (mode) {
125 case Agc1Config::kAdaptiveAnalog:
126 return GainControl::kAdaptiveAnalog;
127 case Agc1Config::kAdaptiveDigital:
128 return GainControl::kAdaptiveDigital;
129 case Agc1Config::kFixedDigital:
130 return GainControl::kFixedDigital;
131 }
132}
133
peah9e6a2902017-05-15 07:19:21 -0700134// Maximum lengths that frame of samples being passed from the render side to
135// the capture side can have (does not apply to AEC3).
136static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
137static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
138
peah764e3642016-10-22 05:04:30 -0700139// Maximum number of frames to buffer in the render queue.
140// TODO(peah): Decrease this once we properly handle hugely unbalanced
141// reverse and forward call numbers.
142static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700143} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000144
145// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000146static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000147
saza1d600522019-10-18 13:29:43 +0200148AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100149 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200150 bool render_pre_processor_enabled,
151 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100152 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200153 render_pre_processor_enabled_(render_pre_processor_enabled),
154 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700155
saza1d600522019-10-18 13:29:43 +0200156bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200157 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700158 bool echo_canceller_enabled,
159 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700160 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700161 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700162 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700163 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200164 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200165 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200166 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700167 bool transient_suppressor_enabled) {
168 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200169 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700170 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
171 changed |=
172 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700173 changed |=
174 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700175 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
176 changed |=
peah2ace3f92016-09-10 04:42:27 -0700177 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200178 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200179 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200180 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200181 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700182 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
183 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200184 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700185 echo_canceller_enabled_ = echo_canceller_enabled;
186 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700187 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700188 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700189 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700190 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200191 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200192 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200193 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700194 transient_suppressor_enabled_ = transient_suppressor_enabled;
195 }
196
197 changed |= first_update_;
198 first_update_ = false;
199 return changed;
200}
201
saza1d600522019-10-18 13:29:43 +0200202bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700203 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200204 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700205}
206
saza1d600522019-10-18 13:29:43 +0200207bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
208 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200209 // If echo controller is present, assume it performs active processing.
210 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
211}
212
saza1d600522019-10-18 13:29:43 +0200213bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200214 bool ec_processing_active) const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200215 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700216 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200217 adaptive_gain_controller_enabled_ ||
218 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700219}
220
saza1d600522019-10-18 13:29:43 +0200221bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700222 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200223 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
224 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700225}
226
saza1d600522019-10-18 13:29:43 +0200227bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200228 return capture_analyzer_enabled_;
229}
230
saza1d600522019-10-18 13:29:43 +0200231bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700232 const {
233 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800234 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200235 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700236}
237
saza1d600522019-10-18 13:29:43 +0200238bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100239 const {
240 return render_pre_processor_enabled_;
241}
242
saza1d600522019-10-18 13:29:43 +0200243bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700244 const {
peah2ace3f92016-09-10 04:42:27 -0700245 return false;
peah2ace3f92016-09-10 04:42:27 -0700246}
247
saza1d600522019-10-18 13:29:43 +0200248bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200249 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
250 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
251}
252
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100253AudioProcessingBuilder::AudioProcessingBuilder() = default;
254AudioProcessingBuilder::~AudioProcessingBuilder() = default;
255
256AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
257 std::unique_ptr<CustomProcessing> capture_post_processing) {
258 capture_post_processing_ = std::move(capture_post_processing);
259 return *this;
260}
261
262AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
263 std::unique_ptr<CustomProcessing> render_pre_processing) {
264 render_pre_processing_ = std::move(render_pre_processing);
265 return *this;
266}
267
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200268AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
269 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
270 capture_analyzer_ = std::move(capture_analyzer);
271 return *this;
272}
273
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100274AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
275 std::unique_ptr<EchoControlFactory> echo_control_factory) {
276 echo_control_factory_ = std::move(echo_control_factory);
277 return *this;
278}
279
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100280AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200281 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100282 echo_detector_ = std::move(echo_detector);
283 return *this;
284}
285
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100286AudioProcessing* AudioProcessingBuilder::Create() {
287 webrtc::Config config;
288 return Create(config);
289}
290
291AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100292 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
293 config, std::move(capture_post_processing_),
294 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200295 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100296 if (apm->Initialize() != AudioProcessing::kNoError) {
297 delete apm;
298 apm = nullptr;
299 }
300 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100301}
302
peah88ac8532016-09-12 16:47:25 -0700303AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200304 : AudioProcessingImpl(config,
305 /*capture_post_processor=*/nullptr,
306 /*render_pre_processor=*/nullptr,
307 /*echo_control_factory=*/nullptr,
308 /*echo_detector=*/nullptr,
309 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000310
Per Åhgren13735822018-02-12 21:42:56 +0100311int AudioProcessingImpl::instance_count_ = 0;
312
Sam Zackrisson0beac582017-09-25 12:04:02 +0200313AudioProcessingImpl::AudioProcessingImpl(
314 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100315 std::unique_ptr<CustomProcessing> capture_post_processor,
316 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200317 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200318 rtc::scoped_refptr<EchoDetector> echo_detector,
319 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100320 : data_dumper_(
321 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgren0cbb58e2019-10-29 22:59:44 +0100322 enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100323 use_setup_specific_default_aec3_config_(
324 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200325 capture_runtime_settings_(kRuntimeSettingQueueSize),
326 render_runtime_settings_(kRuntimeSettingQueueSize),
327 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
328 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200329 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200330 submodule_states_(!!capture_post_processor,
331 !!render_pre_processor,
332 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200333 submodules_(std::move(capture_post_processor),
334 std::move(render_pre_processor),
335 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100336 std::move(capture_analyzer)),
337 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
338 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000339#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Per Åhgren3daedb62019-11-22 12:11:40 +0100340 /* enabled= */ false,
341 /* enabled_agc2_level_estimator= */ false,
342 /* digital_adaptive_disabled= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000343#else
Per Åhgren3daedb62019-11-22 12:11:40 +0100344 config.Get<ExperimentalAgc>().enabled,
345 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
346 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000347#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200348 !field_trial::IsEnabled(
349 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
350 !field_trial::IsEnabled(
351 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700352#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200353 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700354#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200355 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700356#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200357 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200358 RTC_LOG(LS_INFO) << "Injected APM submodules:"
359 << "\nEcho control factory: " << !!echo_control_factory_
360 << "\nEcho detector: " << !!submodules_.echo_detector
361 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
362 << "\nCapture post processor: "
363 << !!submodules_.capture_post_processor
364 << "\nRender pre processor: "
365 << !!submodules_.render_pre_processor;
366
Sam Zackrisson421c8592019-02-11 13:39:46 +0100367 // Mark Echo Controller enabled if a factory is injected.
368 capture_nonlocked_.echo_controller_enabled =
369 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000370
saza1d600522019-10-18 13:29:43 +0200371 submodules_.gain_control.reset(new GainControlImpl());
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200372
Sam Zackrisson421c8592019-02-11 13:39:46 +0100373 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200374 if (!submodules_.echo_detector) {
375 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100376 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800377 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000378
Sam Zackrisson421c8592019-02-11 13:39:46 +0100379 // TODO(alessiob): Move the injected gain controller once injection is
380 // implemented.
saza1d600522019-10-18 13:29:43 +0200381 submodules_.gain_controller2.reset(new GainController2());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100382
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000383 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000384}
385
Per Åhgren0e3198e2019-11-18 08:52:22 +0100386AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000387
niklase@google.com470e71d2011-07-07 08:21:25 +0000388int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800389 // Run in a single-threaded manner during initialization.
390 rtc::CritScope cs_render(&crit_render_);
391 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000392 return InitializeLocked();
393}
394
peahde65ddc2016-09-16 15:02:15 -0700395int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
396 int capture_output_sample_rate_hz,
397 int render_input_sample_rate_hz,
398 ChannelLayout capture_input_layout,
399 ChannelLayout capture_output_layout,
400 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700401 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700402 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
403 LayoutHasKeyboard(capture_input_layout)},
404 {capture_output_sample_rate_hz,
405 ChannelsFromLayout(capture_output_layout),
406 LayoutHasKeyboard(capture_output_layout)},
407 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
408 LayoutHasKeyboard(render_input_layout)},
409 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
410 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700411
412 return Initialize(processing_config);
413}
414
415int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800416 // Run in a single-threaded manner during initialization.
417 rtc::CritScope cs_render(&crit_render_);
418 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700419 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000420}
421
peahdf3efa82015-11-28 12:35:15 -0800422int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800423 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800424 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200425 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800426 return kNoError;
427 }
peahdf3efa82015-11-28 12:35:15 -0800428
429 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800430 return InitializeLocked(processing_config);
431}
432
niklase@google.com470e71d2011-07-07 08:21:25 +0000433int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200434 UpdateActiveSubmoduleStates();
435
Per Åhgrend47941e2019-08-22 11:51:13 +0200436 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800437 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200438 ? formats_.render_processing_format.sample_rate_hz()
439 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800440 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
441 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200442 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800443 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200444 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700445 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200446 render_audiobuffer_sample_rate_hz,
447 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700448 if (formats_.api_format.reverse_input_stream() !=
449 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800450 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800451 formats_.api_format.reverse_input_stream().num_channels(),
452 formats_.api_format.reverse_input_stream().num_frames(),
453 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800454 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700455 } else {
peahdf3efa82015-11-28 12:35:15 -0800456 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700457 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700458 } else {
peahdf3efa82015-11-28 12:35:15 -0800459 render_.render_audio.reset(nullptr);
460 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700461 }
peahce4d9152017-05-19 01:28:05 -0700462
Per Åhgrend47941e2019-08-22 11:51:13 +0200463 capture_.capture_audio.reset(new AudioBuffer(
464 formats_.api_format.input_stream().sample_rate_hz(),
465 formats_.api_format.input_stream().num_channels(),
466 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
467 formats_.api_format.output_stream().num_channels(),
468 formats_.api_format.output_stream().sample_rate_hz(),
469 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000470
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200471 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
472 formats_.api_format.output_stream().sample_rate_hz() &&
473 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
474 capture_.capture_fullband_audio.reset(
475 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
476 formats_.api_format.input_stream().num_channels(),
477 formats_.api_format.output_stream().sample_rate_hz(),
478 formats_.api_format.output_stream().num_channels(),
479 formats_.api_format.output_stream().sample_rate_hz(),
480 formats_.api_format.output_stream().num_channels()));
481 } else {
482 capture_.capture_fullband_audio.reset();
483 }
484
peah764e3642016-10-22 05:04:30 -0700485 AllocateRenderQueue();
486
saza1d600522019-10-18 13:29:43 +0200487 submodules_.gain_control->Initialize(num_proc_channels(),
488 proc_sample_rate_hz());
Per Åhgren3daedb62019-11-22 12:11:40 +0100489 if (constants_.use_experimental_agc) {
490 if (!submodules_.agc_manager.get() ||
491 submodules_.agc_manager->num_channels() !=
492 static_cast<int>(num_proc_channels()) ||
493 submodules_.agc_manager->sample_rate_hz() !=
494 capture_nonlocked_.split_rate) {
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100495 int stream_analog_level = -1;
496 const bool re_creation = !!submodules_.agc_manager;
497 if (re_creation) {
498 stream_analog_level = submodules_.agc_manager->stream_analog_level();
499 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100500 submodules_.agc_manager.reset(new AgcManagerDirect(
501 num_proc_channels(), constants_.agc_startup_min_volume,
502 constants_.agc_clipped_level_min,
503 constants_.use_experimental_agc_agc2_level_estimation,
504 constants_.use_experimental_agc_agc2_digital_adaptive,
505 capture_nonlocked_.split_rate));
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100506 if (re_creation) {
507 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
508 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100509 }
saza1d600522019-10-18 13:29:43 +0200510 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 12:11:40 +0100511 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 08:52:22 +0100512 submodules_.gain_control.get());
saza1d600522019-10-18 13:29:43 +0200513 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 15:02:15 -0700514 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200515 InitializeTransient();
Per Åhgren0aefbf02019-08-23 21:29:17 +0200516 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200517 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700518 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200519 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700520 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200521 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200522 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200523 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100524 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800525
aleloi868f32f2017-05-23 07:20:05 -0700526 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200527 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700528 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000529 return kNoError;
530}
531
Michael Graczyk86c6d332015-07-23 11:41:39 -0700532int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200533 UpdateActiveSubmoduleStates();
534
Michael Graczyk86c6d332015-07-23 11:41:39 -0700535 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700536 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
537 return kBadSampleRateError;
538 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000539 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700540
Peter Kasting69558702016-01-12 16:26:35 -0800541 const size_t num_in_channels = config.input_stream().num_channels();
542 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700543
544 // Need at least one input channel.
545 // Need either one output channel or as many outputs as there are inputs.
546 if (num_in_channels == 0 ||
547 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700548 return kBadNumberChannelsError;
549 }
550
peahdf3efa82015-11-28 12:35:15 -0800551 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000552
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200553 // Choose maximum rate to use for the split filtering.
554 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
555 config_.pipeline.maximum_internal_processing_rate == 32000);
556 int max_splitting_rate = 48000;
557 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
558 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
559 }
560
Per Åhgrenc8626b62019-08-23 15:49:51 +0200561 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700562 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700563 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200564 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700565 submodule_states_.CaptureMultiBandSubModulesActive() ||
566 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200567 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000568
peahde65ddc2016-09-16 15:02:15 -0700569 capture_nonlocked_.capture_processing_format =
570 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700571
peah2ce640f2017-04-07 03:57:48 -0700572 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200573 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200574 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700575 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
576 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200577 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700578 submodule_states_.CaptureMultiBandSubModulesActive() ||
579 submodule_states_.RenderMultiBandSubModulesActive());
580 } else {
581 render_processing_rate = capture_processing_rate;
582 }
583
peahde65ddc2016-09-16 15:02:15 -0700584 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700585 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700586 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
587 kSampleRate8kHz) {
588 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000589 } else {
peahde65ddc2016-09-16 15:02:15 -0700590 render_processing_rate =
591 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000592 }
593
Per Åhgrenc8626b62019-08-23 15:49:51 +0200594 RTC_DCHECK_NE(8000, render_processing_rate);
595
peahce4d9152017-05-19 01:28:05 -0700596 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200597 // By default, downmix the render stream to mono for analysis. This has been
598 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100599 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
600 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200601 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100602 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200603 ? formats_.api_format.reverse_input_stream().num_channels()
604 : 1;
605 formats_.render_processing_format =
606 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700607 } else {
608 formats_.render_processing_format = StreamConfig(
609 formats_.api_format.reverse_input_stream().sample_rate_hz(),
610 formats_.api_format.reverse_input_stream().num_channels());
611 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000612
peahde65ddc2016-09-16 15:02:15 -0700613 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
614 kSampleRate32kHz ||
615 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
616 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800617 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000618 } else {
peahdf3efa82015-11-28 12:35:15 -0800619 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700620 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000621 }
622
623 return InitializeLocked();
624}
625
peah88ac8532016-09-12 16:47:25 -0700626void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200627 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
628
peah88ac8532016-09-12 16:47:25 -0700629 // Run in a single-threaded manner when applying the settings.
630 rtc::CritScope cs_render(&crit_render_);
631 rtc::CritScope cs_capture(&crit_capture_);
632
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200633 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100634 config_.pipeline.multi_channel_render !=
635 config.pipeline.multi_channel_render ||
636 config_.pipeline.multi_channel_capture !=
637 config.pipeline.multi_channel_capture;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200638
Per Åhgren200feba2019-03-06 04:16:46 +0100639 const bool aec_config_changed =
640 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
641 config_.echo_canceller.use_legacy_aec !=
642 config.echo_canceller.use_legacy_aec ||
643 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
644 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
645 config_.echo_canceller.legacy_moderate_suppression_level !=
646 config.echo_canceller.legacy_moderate_suppression_level);
647
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100648 const bool agc1_config_changed =
649 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
650 config_.gain_controller1.mode != config.gain_controller1.mode ||
651 config_.gain_controller1.target_level_dbfs !=
652 config.gain_controller1.target_level_dbfs ||
653 config_.gain_controller1.compression_gain_db !=
654 config.gain_controller1.compression_gain_db ||
655 config_.gain_controller1.enable_limiter !=
656 config.gain_controller1.enable_limiter ||
657 config_.gain_controller1.analog_level_minimum !=
658 config.gain_controller1.analog_level_minimum ||
659 config_.gain_controller1.analog_level_maximum !=
660 config.gain_controller1.analog_level_maximum;
661
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200662 const bool voice_detection_config_changed =
663 config_.voice_detection.enabled != config.voice_detection.enabled;
664
saza0bad15f2019-10-16 11:46:11 +0200665 const bool ns_config_changed =
666 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
667 config_.noise_suppression.level != config.noise_suppression.level;
668
Yves Gerey499bc6c2018-10-10 18:29:07 +0200669 config_ = config;
670
Per Åhgren200feba2019-03-06 04:16:46 +0100671 if (aec_config_changed) {
672 InitializeEchoController();
673 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200674
saza0bad15f2019-10-16 11:46:11 +0200675 if (ns_config_changed) {
676 InitializeNoiseSuppressor();
677 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100678
Per Åhgren0aefbf02019-08-23 21:29:17 +0200679 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800680
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100681 if (agc1_config_changed) {
682 ApplyAgc1Config(config_.gain_controller1);
683 }
684
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100685 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700686 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100687 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
688 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100689 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100690 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700691 config_.gain_controller2 = AudioProcessing::Config::GainController2();
692 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200693 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200694 InitializePreAmplifier();
saza1d600522019-10-18 13:29:43 +0200695 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100696
saza1d600522019-10-18 13:29:43 +0200697 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
698 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100699 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100700
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200701 if (voice_detection_config_changed) {
702 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100703 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200704
705 // Reinitialization must happen after all submodule configuration to avoid
706 // additional reinitializations on the next capture / render processing call.
707 if (pipeline_config_changed) {
708 InitializeLocked(formats_.api_format);
709 }
peah88ac8532016-09-12 16:47:25 -0700710}
711
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100712void AudioProcessingImpl::ApplyAgc1Config(
713 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100714 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100715 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100716
Per Åhgren0e3198e2019-11-18 08:52:22 +0100717 if (!submodules_.agc_manager) {
718 error = submodules_.gain_control->set_mode(
719 Agc1ConfigModeToInterfaceMode(config.mode));
720 RTC_DCHECK_EQ(kNoError, error);
721 error = submodules_.gain_control->set_target_level_dbfs(
722 config.target_level_dbfs);
723 RTC_DCHECK_EQ(kNoError, error);
724 error = submodules_.gain_control->set_compression_gain_db(
725 config.compression_gain_db);
726 RTC_DCHECK_EQ(kNoError, error);
727 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
728 RTC_DCHECK_EQ(kNoError, error);
729 error = submodules_.gain_control->set_analog_level_limits(
730 config.analog_level_minimum, config.analog_level_maximum);
731 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100732 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100733}
734
peah88ac8532016-09-12 16:47:25 -0700735void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800736 // Run in a single-threaded manner when setting the extra options.
737 rtc::CritScope cs_render(&crit_render_);
738 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000739
Per Åhgrenf204faf2019-04-25 15:18:06 +0200740 capture_nonlocked_.use_aec2_extended_filter =
741 config.Get<ExtendedFilter>().enabled;
742 capture_nonlocked_.use_aec2_delay_agnostic =
743 config.Get<DelayAgnostic>().enabled;
744 capture_nonlocked_.use_aec2_refined_adaptive_filter =
745 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800746
peahdf3efa82015-11-28 12:35:15 -0800747 if (capture_.transient_suppressor_enabled !=
748 config.Get<ExperimentalNs>().enabled) {
749 capture_.transient_suppressor_enabled =
750 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000751 InitializeTransient();
752 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000753}
754
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000755int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800756 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700757 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000758}
759
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200760int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
761 return capture_.capture_fullband_audio
762 ? capture_.capture_fullband_audio->num_frames() * 100
763 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
764}
765
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000766int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800767 // Used as callback from submodules, hence locking is not allowed.
768 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000769}
770
Peter Kasting69558702016-01-12 16:26:35 -0800771size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800772 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700773 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000774}
775
Peter Kasting69558702016-01-12 16:26:35 -0800776size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800777 // Used as callback from submodules, hence locking is not allowed.
778 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000779}
780
Peter Kasting69558702016-01-12 16:26:35 -0800781size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800782 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100783 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
784 constants_.multi_channel_capture_support;
785 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200786 return 1;
787 }
788 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800789}
790
Peter Kasting69558702016-01-12 16:26:35 -0800791size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800792 // Used as callback from submodules, hence locking is not allowed.
793 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000794}
795
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000796void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800797 rtc::CritScope cs(&crit_capture_);
798 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200799 if (submodules_.agc_manager.get()) {
800 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000801 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000802}
803
Alessio Bazzicac054e782018-04-16 12:10:09 +0200804void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200805 switch (setting.type()) {
806 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100807 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200808 render_runtime_settings_enqueuer_.Enqueue(setting);
809 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200810 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100811 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200812 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100813 capture_runtime_settings_enqueuer_.Enqueue(setting);
814 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200815 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200816 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100817 render_runtime_settings_enqueuer_.Enqueue(setting);
818 return;
819 case RuntimeSetting::Type::kNotSpecified:
820 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200821 return;
822 }
823 // The language allows the enum to have a non-enumerator
824 // value. Check that this doesn't happen.
825 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200826}
827
828AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
829 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200830 : runtime_settings_(*runtime_settings) {
831 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200832}
833
834AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
835 default;
836
837void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
838 RuntimeSetting setting) {
839 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200840 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200841 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200842 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200843 RTC_LOG(LS_ERROR)
844 << "The runtime settings queue is full. Oldest setting discarded.";
845 }
846 if (remaining_attempts == 0)
847 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
848}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000849
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000850int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700851 const StreamConfig& input_config,
852 const StreamConfig& output_config,
853 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800854 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800855 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700856 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800857 {
858 // Acquire the capture lock in order to safely call the function
859 // that retrieves the render side data. This function accesses apm
860 // getters that need the capture lock held when being called.
861 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700862 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800863
864 if (!src || !dest) {
865 return kNullPointerError;
866 }
867
868 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700869 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000870 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000871
Oskar Sundbom4b276482019-05-23 14:28:00 +0200872 if (processing_config.input_stream() != input_config) {
873 processing_config.input_stream() = input_config;
874 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800875 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200876
877 if (processing_config.output_stream() != output_config) {
878 processing_config.output_stream() = output_config;
879 reinitialization_required = true;
880 }
881
882 if (reinitialization_required) {
883 // Reinitialize.
884 rtc::CritScope cs_render(&crit_render_);
885 rtc::CritScope cs_capture(&crit_capture_);
886 RETURN_ON_ERR(InitializeLocked(processing_config));
887 }
888
peahdf3efa82015-11-28 12:35:15 -0800889 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700890 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
891 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000892
aleloi868f32f2017-05-23 07:20:05 -0700893 if (aec_dump_) {
894 RecordUnprocessedCaptureStream(src);
895 }
896
Per Åhgrena1351272019-08-15 12:15:46 +0200897 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800898 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200899 if (capture_.capture_fullband_audio) {
900 capture_.capture_fullband_audio->CopyFrom(
901 src, formats_.api_format.input_stream());
902 }
peahde65ddc2016-09-16 15:02:15 -0700903 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200904 if (capture_.capture_fullband_audio) {
905 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
906 dest);
907 } else {
908 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
909 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000910
aleloi868f32f2017-05-23 07:20:05 -0700911 if (aec_dump_) {
912 RecordProcessedCaptureStream(dest);
913 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000914 return kNoError;
915}
916
Alex Loiko73ec0192018-05-15 10:52:28 +0200917void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200918 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200919 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200920 if (aec_dump_) {
921 aec_dump_->WriteRuntimeSetting(setting);
922 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200923 switch (setting.type()) {
924 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200925 if (config_.pre_amplifier.enabled) {
926 float value;
927 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200928 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200929 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200930 }
931 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200932 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100933 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100934 if (!submodules_.agc_manager) {
935 float value;
936 setting.GetFloat(&value);
937 int int_value = static_cast<int>(value + .5f);
938 config_.gain_controller1.compression_gain_db = int_value;
939 int error =
940 submodules_.gain_control->set_compression_gain_db(int_value);
941 RTC_DCHECK_EQ(kNoError, error);
942 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100943 break;
944 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200945 case RuntimeSetting::Type::kCaptureFixedPostGain: {
946 if (config_.gain_controller2.enabled) {
947 float value;
948 setting.GetFloat(&value);
949 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200950 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200951 }
952 break;
953 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200954 case RuntimeSetting::Type::kPlayoutVolumeChange: {
955 int value;
956 setting.GetInt(&value);
957 capture_.playout_volume = value;
958 break;
959 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100960 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
961 RTC_NOTREACHED();
962 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200963 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
964 RTC_NOTREACHED();
965 break;
966 case RuntimeSetting::Type::kNotSpecified:
967 RTC_NOTREACHED();
968 break;
969 }
970 }
971}
972
973void AudioProcessingImpl::HandleRenderRuntimeSettings() {
974 RuntimeSetting setting;
975 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200976 if (aec_dump_) {
977 aec_dump_->WriteRuntimeSetting(setting);
978 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200979 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100980 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100981 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200982 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200983 if (submodules_.render_pre_processor) {
984 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200985 }
986 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100987 case RuntimeSetting::Type::kCapturePreGain: // fall-through
988 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200989 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200990 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200991 RTC_NOTREACHED();
992 break;
993 }
994 }
995}
996
peah9e6a2902017-05-15 07:19:21 -0700997void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -0800998 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700999
1000 // Insert the samples into the queue.
saza1d600522019-10-18 13:29:43 +02001001 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02001002 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001003 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1004 num_reverse_channels(),
1005 &aec_render_queue_buffer_);
1006
Per Åhgrenf204faf2019-04-25 15:18:06 +02001007 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1008 // The data queue is full and needs to be emptied.
1009 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001010
Per Åhgrenf204faf2019-04-25 15:18:06 +02001011 // Retry the insert (should always work).
1012 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1013 RTC_DCHECK(result);
1014 }
peaha0624602016-10-25 04:45:24 -07001015 }
1016
saza1d600522019-10-18 13:29:43 +02001017 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001018 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1019 num_reverse_channels(),
1020 &aecm_render_queue_buffer_);
1021 RTC_DCHECK(aecm_render_signal_queue_);
1022 // Insert the samples into the queue.
1023 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1024 // The data queue is full and needs to be emptied.
1025 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001026
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001027 // Retry the insert (should always work).
1028 bool result =
1029 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1030 RTC_DCHECK(result);
1031 }
peah764e3642016-10-22 05:04:30 -07001032 }
peah701d6282016-10-25 05:42:20 -07001033
Per Åhgren0e3198e2019-11-18 08:52:22 +01001034 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001035 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001036 // Insert the samples into the queue.
1037 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1038 // The data queue is full and needs to be emptied.
1039 EmptyQueuedRenderAudio();
1040
1041 // Retry the insert (should always work).
1042 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1043 RTC_DCHECK(result);
1044 }
1045 }
peah9e6a2902017-05-15 07:19:21 -07001046}
ivoc9f4a4a02016-10-28 05:39:16 -07001047
peah9e6a2902017-05-15 07:19:21 -07001048void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001049 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1050
1051 // Insert the samples into the queue.
1052 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1053 // The data queue is full and needs to be emptied.
1054 EmptyQueuedRenderAudio();
1055
1056 // Retry the insert (should always work).
1057 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1058 RTC_DCHECK(result);
1059 }
peah764e3642016-10-22 05:04:30 -07001060}
1061
1062void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001063 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001064 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001065
ivoc9f4a4a02016-10-28 05:39:16 -07001066 const size_t new_red_render_queue_element_max_size =
1067 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1068
peaha0624602016-10-25 04:45:24 -07001069 // Reallocate the queues if the queue item sizes are too small to fit the
1070 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001071
1072 if (agc_render_queue_element_max_size_ <
1073 new_agc_render_queue_element_max_size) {
1074 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1075
1076 std::vector<int16_t> template_queue_element(
1077 agc_render_queue_element_max_size_);
1078
1079 agc_render_signal_queue_.reset(
1080 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1081 kMaxNumFramesToBuffer, template_queue_element,
1082 RenderQueueItemVerifier<int16_t>(
1083 agc_render_queue_element_max_size_)));
1084
1085 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1086 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1087 } else {
1088 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001089 }
ivoc9f4a4a02016-10-28 05:39:16 -07001090
1091 if (red_render_queue_element_max_size_ <
1092 new_red_render_queue_element_max_size) {
1093 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1094
1095 std::vector<float> template_queue_element(
1096 red_render_queue_element_max_size_);
1097
1098 red_render_signal_queue_.reset(
1099 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1100 kMaxNumFramesToBuffer, template_queue_element,
1101 RenderQueueItemVerifier<float>(
1102 red_render_queue_element_max_size_)));
1103
1104 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1105 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1106 } else {
1107 red_render_signal_queue_->Clear();
1108 }
peah764e3642016-10-22 05:04:30 -07001109}
1110
1111void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1112 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001113 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02001114 RTC_DCHECK(aec_render_signal_queue_);
1115 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001116 submodules_.echo_cancellation->ProcessRenderAudio(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001117 aec_capture_queue_buffer_);
1118 }
peaha0624602016-10-25 04:45:24 -07001119 }
1120
saza1d600522019-10-18 13:29:43 +02001121 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001122 RTC_DCHECK(aecm_render_signal_queue_);
1123 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001124 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001125 aecm_capture_queue_buffer_);
1126 }
peah701d6282016-10-25 05:42:20 -07001127 }
1128
1129 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001130 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001131 }
ivoc9f4a4a02016-10-28 05:39:16 -07001132
1133 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001134 RTC_DCHECK(submodules_.echo_detector);
1135 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001136 }
peah764e3642016-10-22 05:04:30 -07001137}
1138
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001139int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001140 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001141 {
1142 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001143 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001144 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001145 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001146 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001147 }
peahfa6228e2015-11-16 16:27:42 -08001148
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001149 if (!frame) {
1150 return kNullPointerError;
1151 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001152 // Must be a native rate.
1153 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1154 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001155 frame->sample_rate_hz_ != kSampleRate32kHz &&
1156 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001157 return kBadSampleRateError;
1158 }
peah192164e2015-11-17 02:16:45 -08001159
peahdf3efa82015-11-28 12:35:15 -08001160 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001161 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001162 {
1163 // Aquire lock for the access of api_format.
1164 // The lock is released immediately due to the conditional
1165 // reinitialization.
1166 rtc::CritScope cs_capture(&crit_capture_);
1167 // TODO(ajm): The input and output rates and channels are currently
1168 // constrained to be identical in the int16 interface.
1169 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001170
1171 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001172 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001173
Oskar Sundbom4b276482019-05-23 14:28:00 +02001174 reinitialization_required =
1175 reinitialization_required ||
1176 processing_config.input_stream().sample_rate_hz() !=
1177 frame->sample_rate_hz_ ||
1178 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1179 processing_config.output_stream().sample_rate_hz() !=
1180 frame->sample_rate_hz_ ||
1181 processing_config.output_stream().num_channels() != frame->num_channels_;
1182
1183 if (reinitialization_required) {
1184 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1185 processing_config.input_stream().set_num_channels(frame->num_channels_);
1186 processing_config.output_stream().set_sample_rate_hz(
1187 frame->sample_rate_hz_);
1188 processing_config.output_stream().set_num_channels(frame->num_channels_);
1189
1190 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001191 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001192 rtc::CritScope cs_capture(&crit_capture_);
1193 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001194 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001195
peahdf3efa82015-11-28 12:35:15 -08001196 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001197 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001198 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001199 return kBadDataLengthError;
1200 }
1201
aleloi868f32f2017-05-23 07:20:05 -07001202 if (aec_dump_) {
1203 RecordUnprocessedCaptureStream(*frame);
1204 }
1205
Per Åhgrend47941e2019-08-22 11:51:13 +02001206 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001207 if (capture_.capture_fullband_audio) {
1208 capture_.capture_fullband_audio->CopyFrom(frame);
1209 }
peahde65ddc2016-09-16 15:02:15 -07001210 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001211 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001212 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001213 if (capture_.capture_fullband_audio) {
1214 capture_.capture_fullband_audio->CopyTo(frame);
1215 } else {
1216 capture_.capture_audio->CopyTo(frame);
1217 }
Per Åhgrena1351272019-08-15 12:15:46 +02001218 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001219 if (capture_.stats.voice_detected) {
1220 frame->vad_activity_ = *capture_.stats.voice_detected
1221 ? AudioFrame::kVadActive
1222 : AudioFrame::kVadPassive;
1223 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001224
aleloi868f32f2017-05-23 07:20:05 -07001225 if (aec_dump_) {
1226 RecordProcessedCaptureStream(*frame);
1227 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001228
1229 return kNoError;
1230}
1231
peahde65ddc2016-09-16 15:02:15 -07001232int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001233 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001234
peahb58a1582016-03-15 09:34:24 -07001235 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001236 // TODO(peah): Simplify once the public API Enable functions for these
1237 // are moved to APM.
saza1d600522019-10-18 13:29:43 +02001238 RTC_DCHECK_LE(!!submodules_.echo_controller +
1239 !!submodules_.echo_cancellation +
1240 !!submodules_.echo_control_mobile,
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001241 1);
peahb58a1582016-03-15 09:34:24 -07001242
peahde65ddc2016-09-16 15:02:15 -07001243 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001244
saza1d600522019-10-18 13:29:43 +02001245 if (submodules_.pre_amplifier) {
1246 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001247 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001248 capture_buffer->num_frames()));
1249 }
1250
Per Åhgren928146f2019-08-20 09:19:21 +02001251 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001252 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001253 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001254 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1255 if (log_rms) {
1256 capture_rms_interval_counter_ = 0;
1257 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001258 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1259 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1260 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1261 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001262 }
1263
saza1d600522019-10-18 13:29:43 +02001264 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001265 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001266 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001267 capture_.echo_path_gain_change =
1268 capture_.prev_analog_mic_level != analog_mic_level &&
1269 capture_.prev_analog_mic_level != -1;
1270 capture_.prev_analog_mic_level = analog_mic_level;
1271
Per Åhgrend2650d12018-10-02 17:00:59 +02001272 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001273 if (submodules_.pre_amplifier) {
1274 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001275 capture_.echo_path_gain_change =
1276 capture_.echo_path_gain_change ||
1277 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001278 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001279 capture_.prev_pre_amp_gain = pre_amp_gain;
1280 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001281
1282 // Detect volume change.
1283 capture_.echo_path_gain_change =
1284 capture_.echo_path_gain_change ||
1285 (capture_.prev_playout_volume != capture_.playout_volume &&
1286 capture_.prev_playout_volume >= 0);
1287 capture_.prev_playout_volume = capture_.playout_volume;
1288
saza1d600522019-10-18 13:29:43 +02001289 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001290 }
1291
Per Åhgren3daedb62019-11-22 12:11:40 +01001292 if (constants_.use_experimental_agc &&
1293 submodules_.gain_control->is_enabled()) {
1294 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001295 }
1296
peah2ace3f92016-09-10 04:42:27 -07001297 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1298 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001299 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1300 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001301 }
1302
Per Åhgrene14cb992019-11-27 09:34:22 +01001303 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1304 constants_.multi_channel_capture_support;
1305 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001306 // Force down-mixing of the number of channels after the detection of
1307 // capture signal saturation.
1308 // TODO(peah): Look into ensuring that this kind of tampering with the
1309 // AudioBuffer functionality should not be needed.
1310 capture_buffer->set_num_channels(1);
1311 }
1312
saza1d600522019-10-18 13:29:43 +02001313 if (submodules_.high_pass_filter) {
1314 submodules_.high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001315 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001316
Per Åhgrene35b32c2019-11-22 18:22:04 +01001317 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001318 RTC_DCHECK(
1319 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
saza1d600522019-10-18 13:29:43 +02001320 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001321 submodules_.noise_suppressor->Analyze(*capture_buffer);
1322 } else if (submodules_.legacy_noise_suppressor) {
1323 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001324 }
peahb58a1582016-03-15 09:34:24 -07001325
saza1d600522019-10-18 13:29:43 +02001326 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001327 // Ensure that the stream delay was set before the call to the
1328 // AECM ProcessCaptureAudio function.
1329 if (!was_stream_delay_set()) {
1330 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001331 }
1332
saza1d600522019-10-18 13:29:43 +02001333 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001334 submodules_.noise_suppressor->Process(capture_buffer);
1335 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001336 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001337 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001338 }
peahe0eae3c2016-12-14 01:16:23 -08001339
saza1d600522019-10-18 13:29:43 +02001340 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001341 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001342 } else {
saza1d600522019-10-18 13:29:43 +02001343 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001344 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1345
1346 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001347 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001348 }
1349
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001350 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
saza1d600522019-10-18 13:29:43 +02001351 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001352 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
saza1d600522019-10-18 13:29:43 +02001353 } else if (submodules_.echo_cancellation) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001354 // Ensure that the stream delay was set before the call to the
1355 // AEC ProcessCaptureAudio function.
1356 if (!was_stream_delay_set()) {
1357 return AudioProcessing::kStreamParameterNotSetError;
1358 }
1359
saza1d600522019-10-18 13:29:43 +02001360 RETURN_ON_ERR(submodules_.echo_cancellation->ProcessCaptureAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001361 capture_buffer, stream_delay_ms()));
1362 }
1363
saza1d600522019-10-18 13:29:43 +02001364 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001365 submodules_.noise_suppressor->Process(capture_buffer);
1366 } else if (submodules_.legacy_noise_suppressor) {
1367 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001368 }
Per Åhgren46537a32017-06-07 10:08:10 +02001369 }
ivoc9f4a4a02016-10-28 05:39:16 -07001370
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001371 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001372 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001373 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001374 } else {
1375 capture_.stats.voice_detected = absl::nullopt;
1376 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001377
Per Åhgren3daedb62019-11-22 12:11:40 +01001378 if (constants_.use_experimental_agc &&
1379 submodules_.gain_control->is_enabled()) {
1380 submodules_.agc_manager->Process(capture_buffer);
1381
1382 absl::optional<int> new_digital_gain =
1383 submodules_.agc_manager->GetDigitalComressionGain();
1384 if (new_digital_gain) {
1385 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1386 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001387 }
Per Åhgren200feba2019-03-06 04:16:46 +01001388 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001389 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1390 capture_buffer, submodules_.echo_cancellation &&
1391 submodules_.echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001392
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001393 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001394 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001395 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1396 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001397 }
1398
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001399 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001400 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001401 bool ec_active = ec ? ec->ActiveProcessing() : false;
1402 // Only update the fullband buffer if the multiband processing has changed
1403 // the signal. Keep the original signal otherwise.
1404 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1405 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1406 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001407 capture_buffer = capture_.capture_fullband_audio.get();
1408 }
1409
peah9e6a2902017-05-15 07:19:21 -07001410 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001411 RTC_DCHECK(submodules_.echo_detector);
1412 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1413 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001414 }
1415
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001416 // TODO(aluebs): Investigate if the transient suppression placement should be
1417 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001418 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001419 float voice_probability = submodules_.agc_manager.get()
1420 ? submodules_.agc_manager->voice_probability()
1421 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001422
saza1d600522019-10-18 13:29:43 +02001423 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001424 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001425 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001426 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001427 capture_buffer->num_frames_per_band(),
1428 capture_.keyboard_info.keyboard_data,
1429 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001430 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001431 }
1432
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001433 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001434 if (submodules_.capture_analyzer) {
1435 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001436 }
1437
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001438 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001439 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001440 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001441 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001442 }
1443
saza1d600522019-10-18 13:29:43 +02001444 if (submodules_.capture_post_processor) {
1445 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001446 }
1447
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001448 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001449 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001450 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1451 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001452 } else {
1453 capture_.stats.output_rms_dbfs = absl::nullopt;
1454 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001455
Per Åhgren928146f2019-08-20 09:19:21 +02001456 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001457 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001458 capture_nonlocked_.capture_processing_format.num_frames()));
1459 if (log_rms) {
1460 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1461 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1462 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1463 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1464 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1465 }
1466
Per Åhgren0e3198e2019-11-18 08:52:22 +01001467 if (submodules_.agc_manager) {
1468 int level = recommended_stream_analog_level();
1469 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1470 &level);
1471 }
1472
peahdf3efa82015-11-28 12:35:15 -08001473 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001474 return kNoError;
1475}
1476
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001477int AudioProcessingImpl::AnalyzeReverseStream(
1478 const float* const* data,
1479 const StreamConfig& reverse_config) {
1480 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1481 rtc::CritScope cs(&crit_render_);
1482 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1483}
1484
peahde65ddc2016-09-16 15:02:15 -07001485int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1486 const StreamConfig& input_config,
1487 const StreamConfig& output_config,
1488 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001489 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001490 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001491 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001492 if (submodule_states_.RenderMultiBandProcessingActive() ||
1493 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001494 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1495 dest);
peah2ace3f92016-09-10 04:42:27 -07001496 } else if (formats_.api_format.reverse_input_stream() !=
1497 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001498 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1499 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001500 } else {
peahde65ddc2016-09-16 15:02:15 -07001501 CopyAudioIfNeeded(src, input_config.num_frames(),
1502 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001503 }
1504
1505 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001506}
1507
peahdf3efa82015-11-28 12:35:15 -08001508int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001509 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001510 const StreamConfig& input_config,
1511 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001512 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001513 return kNullPointerError;
1514 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001515
peahde65ddc2016-09-16 15:02:15 -07001516 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001517 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001518 }
1519
peahdf3efa82015-11-28 12:35:15 -08001520 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001521 processing_config.reverse_input_stream() = input_config;
1522 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001523
peahdf3efa82015-11-28 12:35:15 -08001524 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001525 RTC_DCHECK_EQ(input_config.num_frames(),
1526 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001527
aleloi868f32f2017-05-23 07:20:05 -07001528 if (aec_dump_) {
1529 const size_t channel_size =
1530 formats_.api_format.reverse_input_stream().num_frames();
1531 const size_t num_channels =
1532 formats_.api_format.reverse_input_stream().num_channels();
1533 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001534 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001535 }
peahdf3efa82015-11-28 12:35:15 -08001536 render_.render_audio->CopyFrom(src,
1537 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001538 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001539}
1540
1541int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001542 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001543 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001544 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001545 return kNullPointerError;
1546 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001547 // Must be a native rate.
1548 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1549 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001550 frame->sample_rate_hz_ != kSampleRate32kHz &&
1551 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001552 return kBadSampleRateError;
1553 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001554
Michael Graczyk86c6d332015-07-23 11:41:39 -07001555 if (frame->num_channels_ <= 0) {
1556 return kBadNumberChannelsError;
1557 }
1558
peahdf3efa82015-11-28 12:35:15 -08001559 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001560 processing_config.reverse_input_stream().set_sample_rate_hz(
1561 frame->sample_rate_hz_);
1562 processing_config.reverse_input_stream().set_num_channels(
1563 frame->num_channels_);
1564 processing_config.reverse_output_stream().set_sample_rate_hz(
1565 frame->sample_rate_hz_);
1566 processing_config.reverse_output_stream().set_num_channels(
1567 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001568
peahdf3efa82015-11-28 12:35:15 -08001569 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001570 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001571 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001572 return kBadDataLengthError;
1573 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001574
aleloi868f32f2017-05-23 07:20:05 -07001575 if (aec_dump_) {
1576 aec_dump_->WriteRenderStreamMessage(*frame);
1577 }
1578
Per Åhgrend47941e2019-08-22 11:51:13 +02001579 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001580 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001581 if (submodule_states_.RenderMultiBandProcessingActive() ||
1582 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001583 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001584 }
aluebsb0319552016-03-17 20:39:53 -07001585 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001586}
niklase@google.com470e71d2011-07-07 08:21:25 +00001587
peahde65ddc2016-09-16 15:02:15 -07001588int AudioProcessingImpl::ProcessRenderStreamLocked() {
1589 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001590
Alex Loiko73ec0192018-05-15 10:52:28 +02001591 HandleRenderRuntimeSettings();
1592
saza1d600522019-10-18 13:29:43 +02001593 if (submodules_.render_pre_processor) {
1594 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001595 }
1596
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001597 QueueNonbandedRenderAudio(render_buffer);
1598
peah2ace3f92016-09-10 04:42:27 -07001599 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001600 SampleRateSupportsMultiBand(
1601 formats_.render_processing_format.sample_rate_hz())) {
1602 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001603 }
1604
peahce4d9152017-05-19 01:28:05 -07001605 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1606 QueueBandedRenderAudio(render_buffer);
1607 }
1608
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001609 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001610 if (submodules_.echo_controller) {
1611 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001612 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001613
peah2ace3f92016-09-10 04:42:27 -07001614 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001615 SampleRateSupportsMultiBand(
1616 formats_.render_processing_format.sample_rate_hz())) {
1617 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001618 }
1619
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001620 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001621}
1622
1623int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001624 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001625 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001626 capture_.was_stream_delay_set = true;
1627 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001628
niklase@google.com470e71d2011-07-07 08:21:25 +00001629 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001630 delay = 0;
1631 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001632 }
1633
1634 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1635 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001636 delay = 500;
1637 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001638 }
1639
peahdf3efa82015-11-28 12:35:15 -08001640 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001641 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001642}
1643
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001644bool AudioProcessingImpl::GetLinearAecOutput(
1645 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1646 rtc::CritScope cs(&crit_capture_);
1647 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1648
1649 RTC_DCHECK(linear_aec_buffer);
1650 if (linear_aec_buffer) {
1651 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1652 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1653
1654 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1655 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1656 rtc::ArrayView<const float> channel_view =
1657 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1658 linear_aec_buffer->num_frames());
1659 std::copy(channel_view.begin(), channel_view.end(),
1660 linear_output[ch].begin());
1661 }
1662 return true;
1663 }
1664 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1665 RTC_NOTREACHED();
1666 return false;
1667}
1668
niklase@google.com470e71d2011-07-07 08:21:25 +00001669int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001670 // Used as callback from submodules, hence locking is not allowed.
1671 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001672}
1673
1674bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001675 // Used as callback from submodules, hence locking is not allowed.
1676 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001677}
1678
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001679void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001680 rtc::CritScope cs(&crit_capture_);
1681 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001682}
1683
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001684void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001685 rtc::CritScope cs(&crit_capture_);
1686 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001687}
1688
1689int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001690 rtc::CritScope cs(&crit_capture_);
1691 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001692}
1693
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001694void AudioProcessingImpl::set_stream_analog_level(int level) {
1695 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001696
1697 if (submodules_.agc_manager) {
1698 submodules_.agc_manager->set_stream_analog_level(level);
1699 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1700 1, &level);
1701 } else {
1702 int error = submodules_.gain_control->set_stream_analog_level(level);
1703 RTC_DCHECK_EQ(kNoError, error);
1704 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001705}
1706
1707int AudioProcessingImpl::recommended_stream_analog_level() const {
1708 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001709 if (submodules_.agc_manager) {
1710 return submodules_.agc_manager->stream_analog_level();
1711 }
1712 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001713}
1714
aleloi868f32f2017-05-23 07:20:05 -07001715void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1716 RTC_DCHECK(aec_dump);
1717 rtc::CritScope cs_render(&crit_render_);
1718 rtc::CritScope cs_capture(&crit_capture_);
1719
1720 // The previously attached AecDump will be destroyed with the
1721 // 'aec_dump' parameter, which is after locks are released.
1722 aec_dump_.swap(aec_dump);
1723 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001724 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001725}
1726
1727void AudioProcessingImpl::DetachAecDump() {
1728 // The d-tor of a task-queue based AecDump blocks until all pending
1729 // tasks are done. This construction avoids blocking while holding
1730 // the render and capture locks.
1731 std::unique_ptr<AecDump> aec_dump = nullptr;
1732 {
1733 rtc::CritScope cs_render(&crit_render_);
1734 rtc::CritScope cs_capture(&crit_capture_);
1735 aec_dump = std::move(aec_dump_);
1736 }
1737}
1738
Sam Zackrisson4d364492018-03-02 16:03:21 +01001739void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1740 std::unique_ptr<AudioGenerator> audio_generator) {
1741 // TODO(bugs.webrtc.org/8882) Stub.
1742 // Reset internal audio generator with audio_generator.
1743}
1744
1745void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1746 // TODO(bugs.webrtc.org/8882) Stub.
1747 // Delete audio generator, if one is attached.
1748}
1749
Ivo Creusen56d46092017-11-24 17:29:59 +01001750AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001751 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001752 rtc::CritScope cs_capture(&crit_capture_);
1753 if (!has_remote_tracks) {
1754 return capture_.stats;
1755 }
1756 AudioProcessingStats stats = capture_.stats;
1757 EchoCancellationImpl::Metrics metrics;
saza1d600522019-10-18 13:29:43 +02001758 if (submodules_.echo_controller) {
1759 auto ec_metrics = submodules_.echo_controller->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001760 stats.echo_return_loss = ec_metrics.echo_return_loss;
1761 stats.echo_return_loss_enhancement =
1762 ec_metrics.echo_return_loss_enhancement;
1763 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001764 }
1765 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001766 RTC_DCHECK(submodules_.echo_detector);
1767 auto ed_metrics = submodules_.echo_detector->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001768 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1769 stats.residual_echo_likelihood_recent_max =
1770 ed_metrics.echo_likelihood_recent_max;
1771 }
Ivo Creusenae026092017-11-20 13:07:16 +01001772 return stats;
1773}
1774
peah8271d042016-11-22 07:24:52 -08001775void AudioProcessingImpl::MutateConfig(
1776 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1777 rtc::CritScope cs_render(&crit_render_);
1778 rtc::CritScope cs_capture(&crit_capture_);
1779 mutator(&config_);
1780 ApplyConfig(config_);
1781}
1782
1783AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1784 rtc::CritScope cs_render(&crit_render_);
1785 rtc::CritScope cs_capture(&crit_capture_);
1786 return config_;
1787}
1788
peah2ace3f92016-09-10 04:42:27 -07001789bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1790 return submodule_states_.Update(
saza1d600522019-10-18 13:29:43 +02001791 config_.high_pass_filter.enabled, !!submodules_.echo_cancellation,
1792 !!submodules_.echo_control_mobile, config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001793 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
1794 submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled,
1795 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 11:46:11 +02001796 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001797}
1798
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001799void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001800 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001801 if (!submodules_.transient_suppressor.get()) {
1802 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001803 }
saza1d600522019-10-18 13:29:43 +02001804 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1805 capture_nonlocked_.split_rate,
1806 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001807 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001808}
1809
Per Åhgren0aefbf02019-08-23 21:29:17 +02001810void AudioProcessingImpl::InitializeHighPassFilter() {
1811 if (submodule_states_.HighPassFilteringRequired()) {
saza1d600522019-10-18 13:29:43 +02001812 submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001813 } else {
saza1d600522019-10-18 13:29:43 +02001814 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001815 }
1816}
alessiob3ec96df2017-05-22 06:57:06 -07001817
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001818void AudioProcessingImpl::InitializeVoiceDetector() {
1819 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001820 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001821 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1822 } else {
saza1d600522019-10-18 13:29:43 +02001823 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001824 }
1825}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001826void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001827 bool use_echo_controller =
1828 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001829 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001830 !config_.echo_canceller.use_legacy_aec);
1831
1832 if (use_echo_controller) {
1833 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001834 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001835 submodules_.echo_controller = echo_control_factory_->Create(
1836 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001837 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001838 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001839 EchoCanceller3Config config =
1840 use_setup_specific_default_aec3_config_
1841 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1842 num_proc_channels())
1843 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001844 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001845 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001846 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001847 }
1848
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001849 // Setup the storage for returning the linear AEC output.
1850 if (config_.echo_canceller.export_linear_aec_output) {
1851 constexpr int kLinearOutputRateHz = 16000;
1852 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1853 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1854 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1855 } else {
1856 capture_.linear_aec_output.reset();
1857 }
1858
Per Åhgren200feba2019-03-06 04:16:46 +01001859 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001860
saza1d600522019-10-18 13:29:43 +02001861 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001862 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001863 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001864 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001865 return;
peahe0eae3c2016-12-14 01:16:23 -08001866 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001867
saza1d600522019-10-18 13:29:43 +02001868 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001869 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001870 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001871
1872 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001873 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001874 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001875 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001876 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001877 return;
1878 }
1879
1880 if (config_.echo_canceller.mobile_mode) {
1881 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001882 size_t max_element_size =
1883 std::max(static_cast<size_t>(1),
1884 kMaxAllowedValuesOfSamplesPerBand *
1885 EchoControlMobileImpl::NumCancellersRequired(
1886 num_output_channels(), num_reverse_channels()));
1887
1888 std::vector<int16_t> template_queue_element(max_element_size);
1889
1890 aecm_render_signal_queue_.reset(
1891 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1892 kMaxNumFramesToBuffer, template_queue_element,
1893 RenderQueueItemVerifier<int16_t>(max_element_size)));
1894
1895 aecm_render_queue_buffer_.resize(max_element_size);
1896 aecm_capture_queue_buffer_.resize(max_element_size);
1897
saza1d600522019-10-18 13:29:43 +02001898 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001899
saza1d600522019-10-18 13:29:43 +02001900 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1901 num_reverse_channels(),
1902 num_output_channels());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001903
saza1d600522019-10-18 13:29:43 +02001904 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001905 aec_render_signal_queue_.reset();
1906 return;
1907 }
1908
saza1d600522019-10-18 13:29:43 +02001909 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001910 aecm_render_signal_queue_.reset();
1911
Per Åhgrenf204faf2019-04-25 15:18:06 +02001912 // Create and activate AEC2.
saza1d600522019-10-18 13:29:43 +02001913 submodules_.echo_cancellation.reset(new EchoCancellationImpl());
1914 submodules_.echo_cancellation->SetExtraOptions(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001915 capture_nonlocked_.use_aec2_extended_filter,
1916 capture_nonlocked_.use_aec2_delay_agnostic,
1917 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1918
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001919 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001920 std::max(static_cast<size_t>(1),
1921 kMaxAllowedValuesOfSamplesPerBand *
1922 EchoCancellationImpl::NumCancellersRequired(
1923 num_output_channels(), num_reverse_channels()));
1924
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001925 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001926
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001927 aec_render_signal_queue_.reset(
1928 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1929 kMaxNumFramesToBuffer, template_queue_element,
1930 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001931
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001932 aec_render_queue_buffer_.resize(element_max_size);
1933 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001934
saza1d600522019-10-18 13:29:43 +02001935 submodules_.echo_cancellation->Initialize(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001936 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1937 num_proc_channels());
1938
saza1d600522019-10-18 13:29:43 +02001939 submodules_.echo_cancellation->set_suppression_level(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001940 config_.echo_canceller.legacy_moderate_suppression_level
1941 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1942 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001943}
peah8271d042016-11-22 07:24:52 -08001944
alessiob3ec96df2017-05-22 06:57:06 -07001945void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001946 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001947 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001948 }
1949}
1950
saza0bad15f2019-10-16 11:46:11 +02001951void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001952 submodules_.legacy_noise_suppressor.reset();
1953 submodules_.noise_suppressor.reset();
1954
saza0bad15f2019-10-16 11:46:11 +02001955 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001956 const bool use_legacy_ns =
1957 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1958
1959 if (!use_legacy_ns) {
1960 auto map_level =
1961 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1962 using NoiseSuppresionConfig =
1963 AudioProcessing::Config::NoiseSuppression;
1964 switch (level) {
1965 case NoiseSuppresionConfig::kLow:
1966 return NsConfig::SuppressionLevel::k6dB;
1967 case NoiseSuppresionConfig::kModerate:
1968 return NsConfig::SuppressionLevel::k12dB;
1969 case NoiseSuppresionConfig::kHigh:
1970 return NsConfig::SuppressionLevel::k18dB;
1971 case NoiseSuppresionConfig::kVeryHigh:
1972 return NsConfig::SuppressionLevel::k21dB;
1973 default:
1974 RTC_NOTREACHED();
1975 }
1976 };
1977
1978 NsConfig cfg;
1979 cfg.target_level = map_level(config_.noise_suppression.level);
1980 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1981 cfg, proc_sample_rate_hz(), num_proc_channels());
1982 } else {
1983 auto ns_level =
1984 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1985 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1986 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1987 }
saza0bad15f2019-10-16 11:46:11 +02001988 }
1989}
1990
Alex Loikob5c9a792018-04-16 16:31:22 +02001991void AudioProcessingImpl::InitializePreAmplifier() {
1992 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001993 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001994 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1995 } else {
saza1d600522019-10-18 13:29:43 +02001996 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001997 }
1998}
1999
ivoc9f4a4a02016-10-28 05:39:16 -07002000void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02002001 RTC_DCHECK(submodules_.echo_detector);
2002 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002003 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02002004 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07002005}
2006
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002007void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002008 if (submodules_.capture_analyzer) {
2009 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2010 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002011 }
2012}
2013
Sam Zackrisson0beac582017-09-25 12:04:02 +02002014void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002015 if (submodules_.capture_post_processor) {
2016 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002017 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002018 }
2019}
2020
Alex Loiko5825aa62017-12-18 16:02:40 +01002021void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002022 if (submodules_.render_pre_processor) {
2023 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002024 formats_.render_processing_format.sample_rate_hz(),
2025 formats_.render_processing_format.num_channels());
2026 }
2027}
2028
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002029void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002030
aleloi868f32f2017-05-23 07:20:05 -07002031void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2032 if (!aec_dump_) {
2033 return;
2034 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002035
2036 std::string experiments_description = "";
saza1d600522019-10-18 13:29:43 +02002037 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02002038 experiments_description +=
saza1d600522019-10-18 13:29:43 +02002039 submodules_.echo_cancellation->GetExperimentsDescription();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002040 }
aleloi868f32f2017-05-23 07:20:05 -07002041 // TODO(peah): Add semicolon-separated concatenations of experiment
2042 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002043 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2044 experiments_description += "AgcClippingLevelExperiment;";
2045 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002046 if (capture_nonlocked_.echo_controller_enabled) {
2047 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002048 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002049 if (config_.gain_controller2.enabled) {
2050 experiments_description += "GainController2;";
2051 }
aleloi868f32f2017-05-23 07:20:05 -07002052
2053 InternalAPMConfig apm_config;
2054
Per Åhgren200feba2019-03-06 04:16:46 +01002055 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002056 apm_config.aec_delay_agnostic_enabled =
saza1d600522019-10-18 13:29:43 +02002057 submodules_.echo_cancellation &&
2058 submodules_.echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002059 apm_config.aec_drift_compensation_enabled =
saza1d600522019-10-18 13:29:43 +02002060 submodules_.echo_cancellation &&
2061 submodules_.echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002062 apm_config.aec_extended_filter_enabled =
saza1d600522019-10-18 13:29:43 +02002063 submodules_.echo_cancellation &&
2064 submodules_.echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002065 apm_config.aec_suppression_level =
saza1d600522019-10-18 13:29:43 +02002066 submodules_.echo_cancellation
2067 ? static_cast<int>(submodules_.echo_cancellation->suppression_level())
Per Åhgrenf204faf2019-04-25 15:18:06 +02002068 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002069
saza1d600522019-10-18 13:29:43 +02002070 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002071 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002072 submodules_.echo_control_mobile &&
2073 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002074 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002075 submodules_.echo_control_mobile
2076 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002077 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002078
saza1d600522019-10-18 13:29:43 +02002079 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
2080 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07002081 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02002082 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01002083 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002084
2085 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2086
saza0bad15f2019-10-16 11:46:11 +02002087 apm_config.ns_enabled = config_.noise_suppression.enabled;
2088 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002089
2090 apm_config.transient_suppression_enabled =
2091 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002092 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002093 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2094 apm_config.pre_amplifier_fixed_gain_factor =
2095 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002096
2097 if (!forced && apm_config == apm_config_for_aec_dump_) {
2098 return;
2099 }
2100 aec_dump_->WriteConfig(apm_config);
2101 apm_config_for_aec_dump_ = apm_config;
2102}
2103
2104void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2105 const float* const* src) {
2106 RTC_DCHECK(aec_dump_);
2107 WriteAecDumpConfigMessage(false);
2108
2109 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2110 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2111 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002112 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002113 RecordAudioProcessingState();
2114}
2115
2116void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2117 const AudioFrame& capture_frame) {
2118 RTC_DCHECK(aec_dump_);
2119 WriteAecDumpConfigMessage(false);
2120
2121 aec_dump_->AddCaptureStreamInput(capture_frame);
2122 RecordAudioProcessingState();
2123}
2124
2125void AudioProcessingImpl::RecordProcessedCaptureStream(
2126 const float* const* processed_capture_stream) {
2127 RTC_DCHECK(aec_dump_);
2128
2129 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2130 const size_t num_channels =
2131 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002132 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2133 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002134 aec_dump_->WriteCaptureStreamMessage();
2135}
2136
2137void AudioProcessingImpl::RecordProcessedCaptureStream(
2138 const AudioFrame& processed_capture_frame) {
2139 RTC_DCHECK(aec_dump_);
2140
2141 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2142 aec_dump_->WriteCaptureStreamMessage();
2143}
2144
2145void AudioProcessingImpl::RecordAudioProcessingState() {
2146 RTC_DCHECK(aec_dump_);
2147 AecDump::AudioProcessingState audio_proc_state;
2148 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2149 audio_proc_state.drift =
saza1d600522019-10-18 13:29:43 +02002150 submodules_.echo_cancellation
2151 ? submodules_.echo_cancellation->stream_drift_samples()
Per Åhgrenf204faf2019-04-25 15:18:06 +02002152 : 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002153 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002154 audio_proc_state.keypress = capture_.key_pressed;
2155 aec_dump_->AddAudioProcessingState(audio_proc_state);
2156}
2157
kwiberg83ffe452016-08-29 14:46:07 -07002158AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002159 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002160 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002161 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002162 output_will_be_muted(false),
2163 key_pressed(false),
2164 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002165 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002166 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002167 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002168 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002169 prev_pre_amp_gain(-1.f),
2170 playout_volume(-1),
2171 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002172
2173AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2174
Per Åhgrena1351272019-08-15 12:15:46 +02002175void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2176 const float* const* data,
2177 const StreamConfig& stream_config) {
2178 if (stream_config.has_keyboard()) {
2179 keyboard_data = data[stream_config.num_channels()];
2180 } else {
2181 keyboard_data = NULL;
2182 }
2183 num_keyboard_frames = stream_config.num_frames();
2184}
2185
kwiberg83ffe452016-08-29 14:46:07 -07002186AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2187
2188AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2189
niklase@google.com470e71d2011-07-07 08:21:25 +00002190} // namespace webrtc