blob: 6bd03a5a118d78fbda5e2c791001f4ee26bdb6a9 [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_ ||
Per Åhgren3a77f932019-12-03 11:15:18 +0100250 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
251 echo_controller_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200252}
253
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100254AudioProcessingBuilder::AudioProcessingBuilder() = default;
255AudioProcessingBuilder::~AudioProcessingBuilder() = default;
256
257AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
258 std::unique_ptr<CustomProcessing> capture_post_processing) {
259 capture_post_processing_ = std::move(capture_post_processing);
260 return *this;
261}
262
263AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
264 std::unique_ptr<CustomProcessing> render_pre_processing) {
265 render_pre_processing_ = std::move(render_pre_processing);
266 return *this;
267}
268
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200269AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
270 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
271 capture_analyzer_ = std::move(capture_analyzer);
272 return *this;
273}
274
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100275AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
276 std::unique_ptr<EchoControlFactory> echo_control_factory) {
277 echo_control_factory_ = std::move(echo_control_factory);
278 return *this;
279}
280
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100281AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200282 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100283 echo_detector_ = std::move(echo_detector);
284 return *this;
285}
286
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100287AudioProcessing* AudioProcessingBuilder::Create() {
288 webrtc::Config config;
289 return Create(config);
290}
291
292AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100293 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
294 config, std::move(capture_post_processing_),
295 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200296 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100297 if (apm->Initialize() != AudioProcessing::kNoError) {
298 delete apm;
299 apm = nullptr;
300 }
301 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100302}
303
peah88ac8532016-09-12 16:47:25 -0700304AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200305 : AudioProcessingImpl(config,
306 /*capture_post_processor=*/nullptr,
307 /*render_pre_processor=*/nullptr,
308 /*echo_control_factory=*/nullptr,
309 /*echo_detector=*/nullptr,
310 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000311
Per Åhgren13735822018-02-12 21:42:56 +0100312int AudioProcessingImpl::instance_count_ = 0;
313
Sam Zackrisson0beac582017-09-25 12:04:02 +0200314AudioProcessingImpl::AudioProcessingImpl(
315 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100316 std::unique_ptr<CustomProcessing> capture_post_processor,
317 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200318 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200319 rtc::scoped_refptr<EchoDetector> echo_detector,
320 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100321 : data_dumper_(
322 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgren0cbb58e2019-10-29 22:59:44 +0100323 enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100324 use_setup_specific_default_aec3_config_(
325 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200326 capture_runtime_settings_(kRuntimeSettingQueueSize),
327 render_runtime_settings_(kRuntimeSettingQueueSize),
328 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
329 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200330 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200331 submodule_states_(!!capture_post_processor,
332 !!render_pre_processor,
333 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200334 submodules_(std::move(capture_post_processor),
335 std::move(render_pre_processor),
336 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100337 std::move(capture_analyzer)),
338 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
339 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000340#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Per Åhgren3daedb62019-11-22 12:11:40 +0100341 /* enabled= */ false,
342 /* enabled_agc2_level_estimator= */ false,
343 /* digital_adaptive_disabled= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000344#else
Per Åhgren3daedb62019-11-22 12:11:40 +0100345 config.Get<ExperimentalAgc>().enabled,
346 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
347 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000348#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200349 !field_trial::IsEnabled(
350 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
351 !field_trial::IsEnabled(
352 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700353#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200354 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700355#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200356 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700357#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200358 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200359 RTC_LOG(LS_INFO) << "Injected APM submodules:"
360 << "\nEcho control factory: " << !!echo_control_factory_
361 << "\nEcho detector: " << !!submodules_.echo_detector
362 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
363 << "\nCapture post processor: "
364 << !!submodules_.capture_post_processor
365 << "\nRender pre processor: "
366 << !!submodules_.render_pre_processor;
367
Sam Zackrisson421c8592019-02-11 13:39:46 +0100368 // Mark Echo Controller enabled if a factory is injected.
369 capture_nonlocked_.echo_controller_enabled =
370 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000371
saza1d600522019-10-18 13:29:43 +0200372 submodules_.gain_control.reset(new GainControlImpl());
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200373
Sam Zackrisson421c8592019-02-11 13:39:46 +0100374 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 13:29:43 +0200375 if (!submodules_.echo_detector) {
376 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 13:39:46 +0100377 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800378 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000379
Sam Zackrisson421c8592019-02-11 13:39:46 +0100380 // TODO(alessiob): Move the injected gain controller once injection is
381 // implemented.
saza1d600522019-10-18 13:29:43 +0200382 submodules_.gain_controller2.reset(new GainController2());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100383
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000384 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000385}
386
Per Åhgren0e3198e2019-11-18 08:52:22 +0100387AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000388
niklase@google.com470e71d2011-07-07 08:21:25 +0000389int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800390 // Run in a single-threaded manner during initialization.
391 rtc::CritScope cs_render(&crit_render_);
392 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000393 return InitializeLocked();
394}
395
peahde65ddc2016-09-16 15:02:15 -0700396int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
397 int capture_output_sample_rate_hz,
398 int render_input_sample_rate_hz,
399 ChannelLayout capture_input_layout,
400 ChannelLayout capture_output_layout,
401 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700402 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700403 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
404 LayoutHasKeyboard(capture_input_layout)},
405 {capture_output_sample_rate_hz,
406 ChannelsFromLayout(capture_output_layout),
407 LayoutHasKeyboard(capture_output_layout)},
408 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
409 LayoutHasKeyboard(render_input_layout)},
410 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
411 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700412
413 return Initialize(processing_config);
414}
415
416int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800417 // Run in a single-threaded manner during initialization.
418 rtc::CritScope cs_render(&crit_render_);
419 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700420 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000421}
422
peahdf3efa82015-11-28 12:35:15 -0800423int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800424 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800425 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200426 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800427 return kNoError;
428 }
peahdf3efa82015-11-28 12:35:15 -0800429
430 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800431 return InitializeLocked(processing_config);
432}
433
niklase@google.com470e71d2011-07-07 08:21:25 +0000434int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200435 UpdateActiveSubmoduleStates();
436
Per Åhgrend47941e2019-08-22 11:51:13 +0200437 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800438 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200439 ? formats_.render_processing_format.sample_rate_hz()
440 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800441 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
442 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200443 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800444 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200445 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700446 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200447 render_audiobuffer_sample_rate_hz,
448 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700449 if (formats_.api_format.reverse_input_stream() !=
450 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800451 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800452 formats_.api_format.reverse_input_stream().num_channels(),
453 formats_.api_format.reverse_input_stream().num_frames(),
454 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800455 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700456 } else {
peahdf3efa82015-11-28 12:35:15 -0800457 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700458 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700459 } else {
peahdf3efa82015-11-28 12:35:15 -0800460 render_.render_audio.reset(nullptr);
461 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700462 }
peahce4d9152017-05-19 01:28:05 -0700463
Per Åhgrend47941e2019-08-22 11:51:13 +0200464 capture_.capture_audio.reset(new AudioBuffer(
465 formats_.api_format.input_stream().sample_rate_hz(),
466 formats_.api_format.input_stream().num_channels(),
467 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
468 formats_.api_format.output_stream().num_channels(),
469 formats_.api_format.output_stream().sample_rate_hz(),
470 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000471
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200472 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
473 formats_.api_format.output_stream().sample_rate_hz() &&
474 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
475 capture_.capture_fullband_audio.reset(
476 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
477 formats_.api_format.input_stream().num_channels(),
478 formats_.api_format.output_stream().sample_rate_hz(),
479 formats_.api_format.output_stream().num_channels(),
480 formats_.api_format.output_stream().sample_rate_hz(),
481 formats_.api_format.output_stream().num_channels()));
482 } else {
483 capture_.capture_fullband_audio.reset();
484 }
485
peah764e3642016-10-22 05:04:30 -0700486 AllocateRenderQueue();
487
saza1d600522019-10-18 13:29:43 +0200488 submodules_.gain_control->Initialize(num_proc_channels(),
489 proc_sample_rate_hz());
Per Åhgren3daedb62019-11-22 12:11:40 +0100490 if (constants_.use_experimental_agc) {
491 if (!submodules_.agc_manager.get() ||
492 submodules_.agc_manager->num_channels() !=
493 static_cast<int>(num_proc_channels()) ||
494 submodules_.agc_manager->sample_rate_hz() !=
495 capture_nonlocked_.split_rate) {
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100496 int stream_analog_level = -1;
497 const bool re_creation = !!submodules_.agc_manager;
498 if (re_creation) {
499 stream_analog_level = submodules_.agc_manager->stream_analog_level();
500 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100501 submodules_.agc_manager.reset(new AgcManagerDirect(
502 num_proc_channels(), constants_.agc_startup_min_volume,
503 constants_.agc_clipped_level_min,
504 constants_.use_experimental_agc_agc2_level_estimation,
505 constants_.use_experimental_agc_agc2_digital_adaptive,
506 capture_nonlocked_.split_rate));
Per Åhgren2a6b3b12019-11-26 19:34:26 +0100507 if (re_creation) {
508 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
509 }
Per Åhgren3daedb62019-11-22 12:11:40 +0100510 }
saza1d600522019-10-18 13:29:43 +0200511 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 12:11:40 +0100512 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 08:52:22 +0100513 submodules_.gain_control.get());
saza1d600522019-10-18 13:29:43 +0200514 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 15:02:15 -0700515 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200516 InitializeTransient();
Per Åhgren3a77f932019-12-03 11:15:18 +0100517 InitializeHighPassFilter(false);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200518 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700519 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200520 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700521 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200522 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200523 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200524 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100525 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800526
aleloi868f32f2017-05-23 07:20:05 -0700527 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200528 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700529 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000530 return kNoError;
531}
532
Michael Graczyk86c6d332015-07-23 11:41:39 -0700533int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200534 UpdateActiveSubmoduleStates();
535
Michael Graczyk86c6d332015-07-23 11:41:39 -0700536 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700537 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
538 return kBadSampleRateError;
539 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000540 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700541
Peter Kasting69558702016-01-12 16:26:35 -0800542 const size_t num_in_channels = config.input_stream().num_channels();
543 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700544
545 // Need at least one input channel.
546 // Need either one output channel or as many outputs as there are inputs.
547 if (num_in_channels == 0 ||
548 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700549 return kBadNumberChannelsError;
550 }
551
peahdf3efa82015-11-28 12:35:15 -0800552 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000553
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200554 // Choose maximum rate to use for the split filtering.
555 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
556 config_.pipeline.maximum_internal_processing_rate == 32000);
557 int max_splitting_rate = 48000;
558 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
559 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
560 }
561
Per Åhgrenc8626b62019-08-23 15:49:51 +0200562 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700563 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700564 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200565 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700566 submodule_states_.CaptureMultiBandSubModulesActive() ||
567 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200568 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000569
peahde65ddc2016-09-16 15:02:15 -0700570 capture_nonlocked_.capture_processing_format =
571 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700572
peah2ce640f2017-04-07 03:57:48 -0700573 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200574 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200575 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700576 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
577 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200578 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700579 submodule_states_.CaptureMultiBandSubModulesActive() ||
580 submodule_states_.RenderMultiBandSubModulesActive());
581 } else {
582 render_processing_rate = capture_processing_rate;
583 }
584
peahde65ddc2016-09-16 15:02:15 -0700585 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700586 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700587 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
588 kSampleRate8kHz) {
589 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000590 } else {
peahde65ddc2016-09-16 15:02:15 -0700591 render_processing_rate =
592 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000593 }
594
Per Åhgrenc8626b62019-08-23 15:49:51 +0200595 RTC_DCHECK_NE(8000, render_processing_rate);
596
peahce4d9152017-05-19 01:28:05 -0700597 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200598 // By default, downmix the render stream to mono for analysis. This has been
599 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100600 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
601 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200602 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100603 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200604 ? formats_.api_format.reverse_input_stream().num_channels()
605 : 1;
606 formats_.render_processing_format =
607 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700608 } else {
609 formats_.render_processing_format = StreamConfig(
610 formats_.api_format.reverse_input_stream().sample_rate_hz(),
611 formats_.api_format.reverse_input_stream().num_channels());
612 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000613
peahde65ddc2016-09-16 15:02:15 -0700614 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
615 kSampleRate32kHz ||
616 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
617 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800618 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000619 } else {
peahdf3efa82015-11-28 12:35:15 -0800620 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700621 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000622 }
623
624 return InitializeLocked();
625}
626
peah88ac8532016-09-12 16:47:25 -0700627void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200628 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
629
peah88ac8532016-09-12 16:47:25 -0700630 // Run in a single-threaded manner when applying the settings.
631 rtc::CritScope cs_render(&crit_render_);
632 rtc::CritScope cs_capture(&crit_capture_);
633
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200634 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100635 config_.pipeline.multi_channel_render !=
636 config.pipeline.multi_channel_render ||
637 config_.pipeline.multi_channel_capture !=
638 config.pipeline.multi_channel_capture;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200639
Per Åhgren200feba2019-03-06 04:16:46 +0100640 const bool aec_config_changed =
641 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
642 config_.echo_canceller.use_legacy_aec !=
643 config.echo_canceller.use_legacy_aec ||
644 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
645 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
646 config_.echo_canceller.legacy_moderate_suppression_level !=
647 config.echo_canceller.legacy_moderate_suppression_level);
648
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100649 const bool agc1_config_changed =
650 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
651 config_.gain_controller1.mode != config.gain_controller1.mode ||
652 config_.gain_controller1.target_level_dbfs !=
653 config.gain_controller1.target_level_dbfs ||
654 config_.gain_controller1.compression_gain_db !=
655 config.gain_controller1.compression_gain_db ||
656 config_.gain_controller1.enable_limiter !=
657 config.gain_controller1.enable_limiter ||
658 config_.gain_controller1.analog_level_minimum !=
659 config.gain_controller1.analog_level_minimum ||
660 config_.gain_controller1.analog_level_maximum !=
661 config.gain_controller1.analog_level_maximum;
662
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200663 const bool voice_detection_config_changed =
664 config_.voice_detection.enabled != config.voice_detection.enabled;
665
saza0bad15f2019-10-16 11:46:11 +0200666 const bool ns_config_changed =
667 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
668 config_.noise_suppression.level != config.noise_suppression.level;
669
Yves Gerey499bc6c2018-10-10 18:29:07 +0200670 config_ = config;
671
Per Åhgren200feba2019-03-06 04:16:46 +0100672 if (aec_config_changed) {
673 InitializeEchoController();
674 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200675
saza0bad15f2019-10-16 11:46:11 +0200676 if (ns_config_changed) {
677 InitializeNoiseSuppressor();
678 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100679
Per Åhgren3a77f932019-12-03 11:15:18 +0100680 InitializeHighPassFilter(config_.echo_canceller.enabled &&
681 !config.echo_canceller.mobile_mode);
peah8271d042016-11-22 07:24:52 -0800682
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100683 if (agc1_config_changed) {
684 ApplyAgc1Config(config_.gain_controller1);
685 }
686
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100687 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700688 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100689 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
690 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100691 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100692 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700693 config_.gain_controller2 = AudioProcessing::Config::GainController2();
694 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200695 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200696 InitializePreAmplifier();
saza1d600522019-10-18 13:29:43 +0200697 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100698
saza1d600522019-10-18 13:29:43 +0200699 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
700 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100701 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100702
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200703 if (voice_detection_config_changed) {
704 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100705 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200706
707 // Reinitialization must happen after all submodule configuration to avoid
708 // additional reinitializations on the next capture / render processing call.
709 if (pipeline_config_changed) {
710 InitializeLocked(formats_.api_format);
711 }
peah88ac8532016-09-12 16:47:25 -0700712}
713
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100714void AudioProcessingImpl::ApplyAgc1Config(
715 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100716 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100717 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100718
Per Åhgren0e3198e2019-11-18 08:52:22 +0100719 if (!submodules_.agc_manager) {
720 error = submodules_.gain_control->set_mode(
721 Agc1ConfigModeToInterfaceMode(config.mode));
722 RTC_DCHECK_EQ(kNoError, error);
723 error = submodules_.gain_control->set_target_level_dbfs(
724 config.target_level_dbfs);
725 RTC_DCHECK_EQ(kNoError, error);
726 error = submodules_.gain_control->set_compression_gain_db(
727 config.compression_gain_db);
728 RTC_DCHECK_EQ(kNoError, error);
729 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
730 RTC_DCHECK_EQ(kNoError, error);
731 error = submodules_.gain_control->set_analog_level_limits(
732 config.analog_level_minimum, config.analog_level_maximum);
733 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100734 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100735}
736
peah88ac8532016-09-12 16:47:25 -0700737void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800738 // Run in a single-threaded manner when setting the extra options.
739 rtc::CritScope cs_render(&crit_render_);
740 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000741
Per Åhgrenf204faf2019-04-25 15:18:06 +0200742 capture_nonlocked_.use_aec2_extended_filter =
743 config.Get<ExtendedFilter>().enabled;
744 capture_nonlocked_.use_aec2_delay_agnostic =
745 config.Get<DelayAgnostic>().enabled;
746 capture_nonlocked_.use_aec2_refined_adaptive_filter =
747 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800748
peahdf3efa82015-11-28 12:35:15 -0800749 if (capture_.transient_suppressor_enabled !=
750 config.Get<ExperimentalNs>().enabled) {
751 capture_.transient_suppressor_enabled =
752 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000753 InitializeTransient();
754 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000755}
756
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000757int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800758 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700759 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000760}
761
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200762int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
763 return capture_.capture_fullband_audio
764 ? capture_.capture_fullband_audio->num_frames() * 100
765 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
766}
767
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000768int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800769 // Used as callback from submodules, hence locking is not allowed.
770 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000771}
772
Peter Kasting69558702016-01-12 16:26:35 -0800773size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800774 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700775 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000776}
777
Peter Kasting69558702016-01-12 16:26:35 -0800778size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800779 // Used as callback from submodules, hence locking is not allowed.
780 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000781}
782
Peter Kasting69558702016-01-12 16:26:35 -0800783size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800784 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100785 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
786 constants_.multi_channel_capture_support;
787 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200788 return 1;
789 }
790 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800791}
792
Peter Kasting69558702016-01-12 16:26:35 -0800793size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800794 // Used as callback from submodules, hence locking is not allowed.
795 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000796}
797
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000798void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800799 rtc::CritScope cs(&crit_capture_);
800 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 13:29:43 +0200801 if (submodules_.agc_manager.get()) {
802 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000803 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000804}
805
Alessio Bazzicac054e782018-04-16 12:10:09 +0200806void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200807 switch (setting.type()) {
808 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100809 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200810 render_runtime_settings_enqueuer_.Enqueue(setting);
811 return;
Alex Loiko73ec0192018-05-15 10:52:28 +0200812 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100813 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200814 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100815 capture_runtime_settings_enqueuer_.Enqueue(setting);
816 return;
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200817 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200818 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100819 render_runtime_settings_enqueuer_.Enqueue(setting);
820 return;
821 case RuntimeSetting::Type::kNotSpecified:
822 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +0200823 return;
824 }
825 // The language allows the enum to have a non-enumerator
826 // value. Check that this doesn't happen.
827 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200828}
829
830AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
831 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200832 : runtime_settings_(*runtime_settings) {
833 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200834}
835
836AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
837 default;
838
839void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
840 RuntimeSetting setting) {
841 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200842 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200843 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200844 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200845 RTC_LOG(LS_ERROR)
846 << "The runtime settings queue is full. Oldest setting discarded.";
847 }
848 if (remaining_attempts == 0)
849 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
850}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000851
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000852int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700853 const StreamConfig& input_config,
854 const StreamConfig& output_config,
855 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800856 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800857 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700858 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800859 {
860 // Acquire the capture lock in order to safely call the function
861 // that retrieves the render side data. This function accesses apm
862 // getters that need the capture lock held when being called.
863 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700864 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800865
866 if (!src || !dest) {
867 return kNullPointerError;
868 }
869
870 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700871 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000872 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000873
Oskar Sundbom4b276482019-05-23 14:28:00 +0200874 if (processing_config.input_stream() != input_config) {
875 processing_config.input_stream() = input_config;
876 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800877 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200878
879 if (processing_config.output_stream() != output_config) {
880 processing_config.output_stream() = output_config;
881 reinitialization_required = true;
882 }
883
884 if (reinitialization_required) {
885 // Reinitialize.
886 rtc::CritScope cs_render(&crit_render_);
887 rtc::CritScope cs_capture(&crit_capture_);
888 RETURN_ON_ERR(InitializeLocked(processing_config));
889 }
890
peahdf3efa82015-11-28 12:35:15 -0800891 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700892 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
893 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000894
aleloi868f32f2017-05-23 07:20:05 -0700895 if (aec_dump_) {
896 RecordUnprocessedCaptureStream(src);
897 }
898
Per Åhgrena1351272019-08-15 12:15:46 +0200899 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800900 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200901 if (capture_.capture_fullband_audio) {
902 capture_.capture_fullband_audio->CopyFrom(
903 src, formats_.api_format.input_stream());
904 }
peahde65ddc2016-09-16 15:02:15 -0700905 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200906 if (capture_.capture_fullband_audio) {
907 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
908 dest);
909 } else {
910 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
911 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000912
aleloi868f32f2017-05-23 07:20:05 -0700913 if (aec_dump_) {
914 RecordProcessedCaptureStream(dest);
915 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000916 return kNoError;
917}
918
Alex Loiko73ec0192018-05-15 10:52:28 +0200919void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200920 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200921 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200922 if (aec_dump_) {
923 aec_dump_->WriteRuntimeSetting(setting);
924 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200925 switch (setting.type()) {
926 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200927 if (config_.pre_amplifier.enabled) {
928 float value;
929 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 09:43:01 +0200930 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 13:29:43 +0200931 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 16:31:22 +0200932 }
933 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200934 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100935 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100936 if (!submodules_.agc_manager) {
937 float value;
938 setting.GetFloat(&value);
939 int int_value = static_cast<int>(value + .5f);
940 config_.gain_controller1.compression_gain_db = int_value;
941 int error =
942 submodules_.gain_control->set_compression_gain_db(int_value);
943 RTC_DCHECK_EQ(kNoError, error);
944 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100945 break;
946 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200947 case RuntimeSetting::Type::kCaptureFixedPostGain: {
948 if (config_.gain_controller2.enabled) {
949 float value;
950 setting.GetFloat(&value);
951 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 13:29:43 +0200952 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200953 }
954 break;
955 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200956 case RuntimeSetting::Type::kPlayoutVolumeChange: {
957 int value;
958 setting.GetInt(&value);
959 capture_.playout_volume = value;
960 break;
961 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100962 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
963 RTC_NOTREACHED();
964 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200965 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
966 RTC_NOTREACHED();
967 break;
968 case RuntimeSetting::Type::kNotSpecified:
969 RTC_NOTREACHED();
970 break;
971 }
972 }
973}
974
975void AudioProcessingImpl::HandleRenderRuntimeSettings() {
976 RuntimeSetting setting;
977 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200978 if (aec_dump_) {
979 aec_dump_->WriteRuntimeSetting(setting);
980 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200981 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100982 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +0100983 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +0200984 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +0200985 if (submodules_.render_pre_processor) {
986 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200987 }
988 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100989 case RuntimeSetting::Type::kCapturePreGain: // fall-through
990 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200991 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200992 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200993 RTC_NOTREACHED();
994 break;
995 }
996 }
997}
998
peah9e6a2902017-05-15 07:19:21 -0700999void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001000 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001001
1002 // Insert the samples into the queue.
saza1d600522019-10-18 13:29:43 +02001003 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02001004 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001005 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1006 num_reverse_channels(),
1007 &aec_render_queue_buffer_);
1008
Per Åhgrenf204faf2019-04-25 15:18:06 +02001009 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1010 // The data queue is full and needs to be emptied.
1011 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001012
Per Åhgrenf204faf2019-04-25 15:18:06 +02001013 // Retry the insert (should always work).
1014 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1015 RTC_DCHECK(result);
1016 }
peaha0624602016-10-25 04:45:24 -07001017 }
1018
saza1d600522019-10-18 13:29:43 +02001019 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001020 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1021 num_reverse_channels(),
1022 &aecm_render_queue_buffer_);
1023 RTC_DCHECK(aecm_render_signal_queue_);
1024 // Insert the samples into the queue.
1025 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1026 // The data queue is full and needs to be emptied.
1027 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001028
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001029 // Retry the insert (should always work).
1030 bool result =
1031 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1032 RTC_DCHECK(result);
1033 }
peah764e3642016-10-22 05:04:30 -07001034 }
peah701d6282016-10-25 05:42:20 -07001035
Per Åhgren0e3198e2019-11-18 08:52:22 +01001036 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001037 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001038 // Insert the samples into the queue.
1039 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1040 // The data queue is full and needs to be emptied.
1041 EmptyQueuedRenderAudio();
1042
1043 // Retry the insert (should always work).
1044 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1045 RTC_DCHECK(result);
1046 }
1047 }
peah9e6a2902017-05-15 07:19:21 -07001048}
ivoc9f4a4a02016-10-28 05:39:16 -07001049
peah9e6a2902017-05-15 07:19:21 -07001050void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001051 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1052
1053 // Insert the samples into the queue.
1054 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1055 // The data queue is full and needs to be emptied.
1056 EmptyQueuedRenderAudio();
1057
1058 // Retry the insert (should always work).
1059 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1060 RTC_DCHECK(result);
1061 }
peah764e3642016-10-22 05:04:30 -07001062}
1063
1064void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001065 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001066 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001067
ivoc9f4a4a02016-10-28 05:39:16 -07001068 const size_t new_red_render_queue_element_max_size =
1069 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1070
peaha0624602016-10-25 04:45:24 -07001071 // Reallocate the queues if the queue item sizes are too small to fit the
1072 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001073
1074 if (agc_render_queue_element_max_size_ <
1075 new_agc_render_queue_element_max_size) {
1076 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1077
1078 std::vector<int16_t> template_queue_element(
1079 agc_render_queue_element_max_size_);
1080
1081 agc_render_signal_queue_.reset(
1082 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1083 kMaxNumFramesToBuffer, template_queue_element,
1084 RenderQueueItemVerifier<int16_t>(
1085 agc_render_queue_element_max_size_)));
1086
1087 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1088 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1089 } else {
1090 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001091 }
ivoc9f4a4a02016-10-28 05:39:16 -07001092
1093 if (red_render_queue_element_max_size_ <
1094 new_red_render_queue_element_max_size) {
1095 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1096
1097 std::vector<float> template_queue_element(
1098 red_render_queue_element_max_size_);
1099
1100 red_render_signal_queue_.reset(
1101 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1102 kMaxNumFramesToBuffer, template_queue_element,
1103 RenderQueueItemVerifier<float>(
1104 red_render_queue_element_max_size_)));
1105
1106 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1107 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1108 } else {
1109 red_render_signal_queue_->Clear();
1110 }
peah764e3642016-10-22 05:04:30 -07001111}
1112
1113void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1114 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 13:29:43 +02001115 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02001116 RTC_DCHECK(aec_render_signal_queue_);
1117 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001118 submodules_.echo_cancellation->ProcessRenderAudio(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001119 aec_capture_queue_buffer_);
1120 }
peaha0624602016-10-25 04:45:24 -07001121 }
1122
saza1d600522019-10-18 13:29:43 +02001123 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001124 RTC_DCHECK(aecm_render_signal_queue_);
1125 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001126 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001127 aecm_capture_queue_buffer_);
1128 }
peah701d6282016-10-25 05:42:20 -07001129 }
1130
1131 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001132 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001133 }
ivoc9f4a4a02016-10-28 05:39:16 -07001134
1135 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001136 RTC_DCHECK(submodules_.echo_detector);
1137 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 05:39:16 -07001138 }
peah764e3642016-10-22 05:04:30 -07001139}
1140
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001141int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001142 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001143 {
1144 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001145 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001146 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001147 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001148 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001149 }
peahfa6228e2015-11-16 16:27:42 -08001150
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001151 if (!frame) {
1152 return kNullPointerError;
1153 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001154 // Must be a native rate.
1155 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1156 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001157 frame->sample_rate_hz_ != kSampleRate32kHz &&
1158 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001159 return kBadSampleRateError;
1160 }
peah192164e2015-11-17 02:16:45 -08001161
peahdf3efa82015-11-28 12:35:15 -08001162 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001163 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001164 {
1165 // Aquire lock for the access of api_format.
1166 // The lock is released immediately due to the conditional
1167 // reinitialization.
1168 rtc::CritScope cs_capture(&crit_capture_);
1169 // TODO(ajm): The input and output rates and channels are currently
1170 // constrained to be identical in the int16 interface.
1171 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001172
1173 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001174 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001175
Oskar Sundbom4b276482019-05-23 14:28:00 +02001176 reinitialization_required =
1177 reinitialization_required ||
1178 processing_config.input_stream().sample_rate_hz() !=
1179 frame->sample_rate_hz_ ||
1180 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1181 processing_config.output_stream().sample_rate_hz() !=
1182 frame->sample_rate_hz_ ||
1183 processing_config.output_stream().num_channels() != frame->num_channels_;
1184
1185 if (reinitialization_required) {
1186 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1187 processing_config.input_stream().set_num_channels(frame->num_channels_);
1188 processing_config.output_stream().set_sample_rate_hz(
1189 frame->sample_rate_hz_);
1190 processing_config.output_stream().set_num_channels(frame->num_channels_);
1191
1192 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001193 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001194 rtc::CritScope cs_capture(&crit_capture_);
1195 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001196 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001197
peahdf3efa82015-11-28 12:35:15 -08001198 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001199 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001200 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001201 return kBadDataLengthError;
1202 }
1203
aleloi868f32f2017-05-23 07:20:05 -07001204 if (aec_dump_) {
1205 RecordUnprocessedCaptureStream(*frame);
1206 }
1207
Per Åhgrend47941e2019-08-22 11:51:13 +02001208 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001209 if (capture_.capture_fullband_audio) {
1210 capture_.capture_fullband_audio->CopyFrom(frame);
1211 }
peahde65ddc2016-09-16 15:02:15 -07001212 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001213 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001214 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001215 if (capture_.capture_fullband_audio) {
1216 capture_.capture_fullband_audio->CopyTo(frame);
1217 } else {
1218 capture_.capture_audio->CopyTo(frame);
1219 }
Per Åhgrena1351272019-08-15 12:15:46 +02001220 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001221 if (capture_.stats.voice_detected) {
1222 frame->vad_activity_ = *capture_.stats.voice_detected
1223 ? AudioFrame::kVadActive
1224 : AudioFrame::kVadPassive;
1225 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001226
aleloi868f32f2017-05-23 07:20:05 -07001227 if (aec_dump_) {
1228 RecordProcessedCaptureStream(*frame);
1229 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001230
1231 return kNoError;
1232}
1233
peahde65ddc2016-09-16 15:02:15 -07001234int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001235 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001236
peahb58a1582016-03-15 09:34:24 -07001237 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001238 // TODO(peah): Simplify once the public API Enable functions for these
1239 // are moved to APM.
saza1d600522019-10-18 13:29:43 +02001240 RTC_DCHECK_LE(!!submodules_.echo_controller +
1241 !!submodules_.echo_cancellation +
1242 !!submodules_.echo_control_mobile,
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001243 1);
peahb58a1582016-03-15 09:34:24 -07001244
peahde65ddc2016-09-16 15:02:15 -07001245 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001246
saza1d600522019-10-18 13:29:43 +02001247 if (submodules_.pre_amplifier) {
1248 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001249 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001250 capture_buffer->num_frames()));
1251 }
1252
Per Åhgren928146f2019-08-20 09:19:21 +02001253 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001254 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001255 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001256 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1257 if (log_rms) {
1258 capture_rms_interval_counter_ = 0;
1259 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001260 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1261 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1262 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1263 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001264 }
1265
saza1d600522019-10-18 13:29:43 +02001266 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001267 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 08:52:22 +01001268 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001269 capture_.echo_path_gain_change =
1270 capture_.prev_analog_mic_level != analog_mic_level &&
1271 capture_.prev_analog_mic_level != -1;
1272 capture_.prev_analog_mic_level = analog_mic_level;
1273
Per Åhgrend2650d12018-10-02 17:00:59 +02001274 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 13:29:43 +02001275 if (submodules_.pre_amplifier) {
1276 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 17:00:59 +02001277 capture_.echo_path_gain_change =
1278 capture_.echo_path_gain_change ||
1279 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001280 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001281 capture_.prev_pre_amp_gain = pre_amp_gain;
1282 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001283
1284 // Detect volume change.
1285 capture_.echo_path_gain_change =
1286 capture_.echo_path_gain_change ||
1287 (capture_.prev_playout_volume != capture_.playout_volume &&
1288 capture_.prev_playout_volume >= 0);
1289 capture_.prev_playout_volume = capture_.playout_volume;
1290
saza1d600522019-10-18 13:29:43 +02001291 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001292 }
1293
Per Åhgren3daedb62019-11-22 12:11:40 +01001294 if (constants_.use_experimental_agc &&
1295 submodules_.gain_control->is_enabled()) {
1296 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001297 }
1298
peah2ace3f92016-09-10 04:42:27 -07001299 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1300 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001301 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1302 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001303 }
1304
Per Åhgrene14cb992019-11-27 09:34:22 +01001305 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1306 constants_.multi_channel_capture_support;
1307 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001308 // Force down-mixing of the number of channels after the detection of
1309 // capture signal saturation.
1310 // TODO(peah): Look into ensuring that this kind of tampering with the
1311 // AudioBuffer functionality should not be needed.
1312 capture_buffer->set_num_channels(1);
1313 }
1314
saza1d600522019-10-18 13:29:43 +02001315 if (submodules_.high_pass_filter) {
1316 submodules_.high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001317 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001318
Per Åhgrene35b32c2019-11-22 18:22:04 +01001319 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001320 RTC_DCHECK(
1321 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
saza1d600522019-10-18 13:29:43 +02001322 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001323 submodules_.noise_suppressor->Analyze(*capture_buffer);
1324 } else if (submodules_.legacy_noise_suppressor) {
1325 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001326 }
peahb58a1582016-03-15 09:34:24 -07001327
saza1d600522019-10-18 13:29:43 +02001328 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001329 // Ensure that the stream delay was set before the call to the
1330 // AECM ProcessCaptureAudio function.
1331 if (!was_stream_delay_set()) {
1332 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001333 }
1334
saza1d600522019-10-18 13:29:43 +02001335 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001336 submodules_.noise_suppressor->Process(capture_buffer);
1337 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 13:29:43 +02001338 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001339 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001340 }
peahe0eae3c2016-12-14 01:16:23 -08001341
saza1d600522019-10-18 13:29:43 +02001342 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001343 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001344 } else {
saza1d600522019-10-18 13:29:43 +02001345 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001346 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1347
1348 if (was_stream_delay_set()) {
saza1d600522019-10-18 13:29:43 +02001349 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001350 }
1351
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001352 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
saza1d600522019-10-18 13:29:43 +02001353 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001354 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
saza1d600522019-10-18 13:29:43 +02001355 } else if (submodules_.echo_cancellation) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001356 // Ensure that the stream delay was set before the call to the
1357 // AEC ProcessCaptureAudio function.
1358 if (!was_stream_delay_set()) {
1359 return AudioProcessing::kStreamParameterNotSetError;
1360 }
1361
saza1d600522019-10-18 13:29:43 +02001362 RETURN_ON_ERR(submodules_.echo_cancellation->ProcessCaptureAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001363 capture_buffer, stream_delay_ms()));
1364 }
1365
saza1d600522019-10-18 13:29:43 +02001366 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001367 submodules_.noise_suppressor->Process(capture_buffer);
1368 } else if (submodules_.legacy_noise_suppressor) {
1369 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001370 }
Per Åhgren46537a32017-06-07 10:08:10 +02001371 }
ivoc9f4a4a02016-10-28 05:39:16 -07001372
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001373 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001374 capture_.stats.voice_detected =
saza1d600522019-10-18 13:29:43 +02001375 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001376 } else {
1377 capture_.stats.voice_detected = absl::nullopt;
1378 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001379
Per Åhgren3daedb62019-11-22 12:11:40 +01001380 if (constants_.use_experimental_agc &&
1381 submodules_.gain_control->is_enabled()) {
1382 submodules_.agc_manager->Process(capture_buffer);
1383
1384 absl::optional<int> new_digital_gain =
1385 submodules_.agc_manager->GetDigitalComressionGain();
1386 if (new_digital_gain) {
1387 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1388 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001389 }
Per Åhgren200feba2019-03-06 04:16:46 +01001390 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 13:29:43 +02001391 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1392 capture_buffer, submodules_.echo_cancellation &&
1393 submodules_.echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001394
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001395 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001396 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001397 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1398 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001399 }
1400
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001401 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 13:29:43 +02001402 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001403 bool ec_active = ec ? ec->ActiveProcessing() : false;
1404 // Only update the fullband buffer if the multiband processing has changed
1405 // the signal. Keep the original signal otherwise.
1406 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1407 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1408 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001409 capture_buffer = capture_.capture_fullband_audio.get();
1410 }
1411
peah9e6a2902017-05-15 07:19:21 -07001412 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001413 RTC_DCHECK(submodules_.echo_detector);
1414 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1415 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 07:19:21 -07001416 }
1417
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001418 // TODO(aluebs): Investigate if the transient suppression placement should be
1419 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001420 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001421 float voice_probability = submodules_.agc_manager.get()
1422 ? submodules_.agc_manager->voice_probability()
1423 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001424
saza1d600522019-10-18 13:29:43 +02001425 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001426 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001427 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001428 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001429 capture_buffer->num_frames_per_band(),
1430 capture_.keyboard_info.keyboard_data,
1431 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001432 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001433 }
1434
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001435 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 13:29:43 +02001436 if (submodules_.capture_analyzer) {
1437 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001438 }
1439
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001440 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001441 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 08:52:22 +01001442 recommended_stream_analog_level());
saza1d600522019-10-18 13:29:43 +02001443 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 06:57:06 -07001444 }
1445
saza1d600522019-10-18 13:29:43 +02001446 if (submodules_.capture_post_processor) {
1447 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 12:04:02 +02001448 }
1449
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001450 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001451 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 13:29:43 +02001452 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1453 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001454 } else {
1455 capture_.stats.output_rms_dbfs = absl::nullopt;
1456 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001457
Per Åhgren928146f2019-08-20 09:19:21 +02001458 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001459 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001460 capture_nonlocked_.capture_processing_format.num_frames()));
1461 if (log_rms) {
1462 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1463 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1464 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1465 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1466 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1467 }
1468
Per Åhgren0e3198e2019-11-18 08:52:22 +01001469 if (submodules_.agc_manager) {
1470 int level = recommended_stream_analog_level();
1471 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1472 &level);
1473 }
1474
peahdf3efa82015-11-28 12:35:15 -08001475 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001476 return kNoError;
1477}
1478
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001479int AudioProcessingImpl::AnalyzeReverseStream(
1480 const float* const* data,
1481 const StreamConfig& reverse_config) {
1482 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1483 rtc::CritScope cs(&crit_render_);
1484 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1485}
1486
peahde65ddc2016-09-16 15:02:15 -07001487int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1488 const StreamConfig& input_config,
1489 const StreamConfig& output_config,
1490 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001491 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001492 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001493 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001494 if (submodule_states_.RenderMultiBandProcessingActive() ||
1495 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001496 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1497 dest);
peah2ace3f92016-09-10 04:42:27 -07001498 } else if (formats_.api_format.reverse_input_stream() !=
1499 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001500 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1501 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001502 } else {
peahde65ddc2016-09-16 15:02:15 -07001503 CopyAudioIfNeeded(src, input_config.num_frames(),
1504 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001505 }
1506
1507 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001508}
1509
peahdf3efa82015-11-28 12:35:15 -08001510int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001511 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001512 const StreamConfig& input_config,
1513 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001514 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001515 return kNullPointerError;
1516 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001517
peahde65ddc2016-09-16 15:02:15 -07001518 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001519 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001520 }
1521
peahdf3efa82015-11-28 12:35:15 -08001522 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001523 processing_config.reverse_input_stream() = input_config;
1524 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001525
peahdf3efa82015-11-28 12:35:15 -08001526 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001527 RTC_DCHECK_EQ(input_config.num_frames(),
1528 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001529
aleloi868f32f2017-05-23 07:20:05 -07001530 if (aec_dump_) {
1531 const size_t channel_size =
1532 formats_.api_format.reverse_input_stream().num_frames();
1533 const size_t num_channels =
1534 formats_.api_format.reverse_input_stream().num_channels();
1535 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001536 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001537 }
peahdf3efa82015-11-28 12:35:15 -08001538 render_.render_audio->CopyFrom(src,
1539 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001540 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001541}
1542
1543int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001544 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001545 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001546 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001547 return kNullPointerError;
1548 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001549 // Must be a native rate.
1550 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1551 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001552 frame->sample_rate_hz_ != kSampleRate32kHz &&
1553 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001554 return kBadSampleRateError;
1555 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001556
Michael Graczyk86c6d332015-07-23 11:41:39 -07001557 if (frame->num_channels_ <= 0) {
1558 return kBadNumberChannelsError;
1559 }
1560
peahdf3efa82015-11-28 12:35:15 -08001561 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001562 processing_config.reverse_input_stream().set_sample_rate_hz(
1563 frame->sample_rate_hz_);
1564 processing_config.reverse_input_stream().set_num_channels(
1565 frame->num_channels_);
1566 processing_config.reverse_output_stream().set_sample_rate_hz(
1567 frame->sample_rate_hz_);
1568 processing_config.reverse_output_stream().set_num_channels(
1569 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001570
peahdf3efa82015-11-28 12:35:15 -08001571 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001572 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001573 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001574 return kBadDataLengthError;
1575 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001576
aleloi868f32f2017-05-23 07:20:05 -07001577 if (aec_dump_) {
1578 aec_dump_->WriteRenderStreamMessage(*frame);
1579 }
1580
Per Åhgrend47941e2019-08-22 11:51:13 +02001581 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001582 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001583 if (submodule_states_.RenderMultiBandProcessingActive() ||
1584 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001585 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001586 }
aluebsb0319552016-03-17 20:39:53 -07001587 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001588}
niklase@google.com470e71d2011-07-07 08:21:25 +00001589
peahde65ddc2016-09-16 15:02:15 -07001590int AudioProcessingImpl::ProcessRenderStreamLocked() {
1591 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001592
Alex Loiko73ec0192018-05-15 10:52:28 +02001593 HandleRenderRuntimeSettings();
1594
saza1d600522019-10-18 13:29:43 +02001595 if (submodules_.render_pre_processor) {
1596 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001597 }
1598
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001599 QueueNonbandedRenderAudio(render_buffer);
1600
peah2ace3f92016-09-10 04:42:27 -07001601 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001602 SampleRateSupportsMultiBand(
1603 formats_.render_processing_format.sample_rate_hz())) {
1604 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001605 }
1606
peahce4d9152017-05-19 01:28:05 -07001607 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1608 QueueBandedRenderAudio(render_buffer);
1609 }
1610
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001611 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001612 if (submodules_.echo_controller) {
1613 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001614 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001615
peah2ace3f92016-09-10 04:42:27 -07001616 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001617 SampleRateSupportsMultiBand(
1618 formats_.render_processing_format.sample_rate_hz())) {
1619 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001620 }
1621
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001622 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001623}
1624
1625int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001626 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001627 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001628 capture_.was_stream_delay_set = true;
1629 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001630
niklase@google.com470e71d2011-07-07 08:21:25 +00001631 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001632 delay = 0;
1633 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001634 }
1635
1636 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1637 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001638 delay = 500;
1639 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001640 }
1641
peahdf3efa82015-11-28 12:35:15 -08001642 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001643 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001644}
1645
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001646bool AudioProcessingImpl::GetLinearAecOutput(
1647 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1648 rtc::CritScope cs(&crit_capture_);
1649 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1650
1651 RTC_DCHECK(linear_aec_buffer);
1652 if (linear_aec_buffer) {
1653 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1654 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1655
1656 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1657 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1658 rtc::ArrayView<const float> channel_view =
1659 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1660 linear_aec_buffer->num_frames());
1661 std::copy(channel_view.begin(), channel_view.end(),
1662 linear_output[ch].begin());
1663 }
1664 return true;
1665 }
1666 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1667 RTC_NOTREACHED();
1668 return false;
1669}
1670
niklase@google.com470e71d2011-07-07 08:21:25 +00001671int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001672 // Used as callback from submodules, hence locking is not allowed.
1673 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001674}
1675
1676bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001677 // Used as callback from submodules, hence locking is not allowed.
1678 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001679}
1680
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001681void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001682 rtc::CritScope cs(&crit_capture_);
1683 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001684}
1685
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001686void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001687 rtc::CritScope cs(&crit_capture_);
1688 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001689}
1690
1691int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001692 rtc::CritScope cs(&crit_capture_);
1693 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001694}
1695
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001696void AudioProcessingImpl::set_stream_analog_level(int level) {
1697 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001698
1699 if (submodules_.agc_manager) {
1700 submodules_.agc_manager->set_stream_analog_level(level);
1701 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1702 1, &level);
1703 } else {
1704 int error = submodules_.gain_control->set_stream_analog_level(level);
1705 RTC_DCHECK_EQ(kNoError, error);
1706 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001707}
1708
1709int AudioProcessingImpl::recommended_stream_analog_level() const {
1710 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 08:52:22 +01001711 if (submodules_.agc_manager) {
1712 return submodules_.agc_manager->stream_analog_level();
1713 }
1714 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001715}
1716
aleloi868f32f2017-05-23 07:20:05 -07001717void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1718 RTC_DCHECK(aec_dump);
1719 rtc::CritScope cs_render(&crit_render_);
1720 rtc::CritScope cs_capture(&crit_capture_);
1721
1722 // The previously attached AecDump will be destroyed with the
1723 // 'aec_dump' parameter, which is after locks are released.
1724 aec_dump_.swap(aec_dump);
1725 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001726 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001727}
1728
1729void AudioProcessingImpl::DetachAecDump() {
1730 // The d-tor of a task-queue based AecDump blocks until all pending
1731 // tasks are done. This construction avoids blocking while holding
1732 // the render and capture locks.
1733 std::unique_ptr<AecDump> aec_dump = nullptr;
1734 {
1735 rtc::CritScope cs_render(&crit_render_);
1736 rtc::CritScope cs_capture(&crit_capture_);
1737 aec_dump = std::move(aec_dump_);
1738 }
1739}
1740
Sam Zackrisson4d364492018-03-02 16:03:21 +01001741void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1742 std::unique_ptr<AudioGenerator> audio_generator) {
1743 // TODO(bugs.webrtc.org/8882) Stub.
1744 // Reset internal audio generator with audio_generator.
1745}
1746
1747void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1748 // TODO(bugs.webrtc.org/8882) Stub.
1749 // Delete audio generator, if one is attached.
1750}
1751
Ivo Creusen56d46092017-11-24 17:29:59 +01001752AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001753 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001754 rtc::CritScope cs_capture(&crit_capture_);
1755 if (!has_remote_tracks) {
1756 return capture_.stats;
1757 }
1758 AudioProcessingStats stats = capture_.stats;
1759 EchoCancellationImpl::Metrics metrics;
saza1d600522019-10-18 13:29:43 +02001760 if (submodules_.echo_controller) {
1761 auto ec_metrics = submodules_.echo_controller->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001762 stats.echo_return_loss = ec_metrics.echo_return_loss;
1763 stats.echo_return_loss_enhancement =
1764 ec_metrics.echo_return_loss_enhancement;
1765 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001766 }
1767 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 13:29:43 +02001768 RTC_DCHECK(submodules_.echo_detector);
1769 auto ed_metrics = submodules_.echo_detector->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001770 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1771 stats.residual_echo_likelihood_recent_max =
1772 ed_metrics.echo_likelihood_recent_max;
1773 }
Ivo Creusenae026092017-11-20 13:07:16 +01001774 return stats;
1775}
1776
peah8271d042016-11-22 07:24:52 -08001777void AudioProcessingImpl::MutateConfig(
1778 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1779 rtc::CritScope cs_render(&crit_render_);
1780 rtc::CritScope cs_capture(&crit_capture_);
1781 mutator(&config_);
1782 ApplyConfig(config_);
1783}
1784
1785AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1786 rtc::CritScope cs_render(&crit_render_);
1787 rtc::CritScope cs_capture(&crit_capture_);
1788 return config_;
1789}
1790
peah2ace3f92016-09-10 04:42:27 -07001791bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1792 return submodule_states_.Update(
Per Åhgren3a77f932019-12-03 11:15:18 +01001793 config_.high_pass_filter.enabled, config_.echo_canceller.enabled,
saza1d600522019-10-18 13:29:43 +02001794 !!submodules_.echo_control_mobile, config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001795 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
1796 submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled,
1797 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 11:46:11 +02001798 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001799}
1800
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001801void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001802 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 13:29:43 +02001803 if (!submodules_.transient_suppressor.get()) {
1804 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001805 }
saza1d600522019-10-18 13:29:43 +02001806 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1807 capture_nonlocked_.split_rate,
1808 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001809 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001810}
1811
Per Åhgren3a77f932019-12-03 11:15:18 +01001812void AudioProcessingImpl::InitializeHighPassFilter(bool force_activation) {
1813 if (force_activation || submodule_states_.HighPassFilteringRequired()) {
saza1d600522019-10-18 13:29:43 +02001814 submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001815 } else {
saza1d600522019-10-18 13:29:43 +02001816 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001817 }
1818}
alessiob3ec96df2017-05-22 06:57:06 -07001819
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001820void AudioProcessingImpl::InitializeVoiceDetector() {
1821 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 13:29:43 +02001822 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001823 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1824 } else {
saza1d600522019-10-18 13:29:43 +02001825 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001826 }
1827}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001828void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001829 bool use_echo_controller =
1830 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001831 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001832 !config_.echo_canceller.use_legacy_aec);
1833
1834 if (use_echo_controller) {
1835 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001836 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001837 submodules_.echo_controller = echo_control_factory_->Create(
1838 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001839 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001840 } else {
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001841 EchoCanceller3Config config =
1842 use_setup_specific_default_aec3_config_
1843 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1844 num_proc_channels())
1845 : EchoCanceller3Config();
saza1d600522019-10-18 13:29:43 +02001846 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 14:59:40 +01001847 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001848 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001849 }
1850
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001851 // Setup the storage for returning the linear AEC output.
1852 if (config_.echo_canceller.export_linear_aec_output) {
1853 constexpr int kLinearOutputRateHz = 16000;
1854 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1855 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1856 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1857 } else {
1858 capture_.linear_aec_output.reset();
1859 }
1860
Per Åhgren200feba2019-03-06 04:16:46 +01001861 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001862
saza1d600522019-10-18 13:29:43 +02001863 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001864 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001865 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001866 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001867 return;
peahe0eae3c2016-12-14 01:16:23 -08001868 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001869
saza1d600522019-10-18 13:29:43 +02001870 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001871 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001872 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001873
1874 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001875 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001876 aec_render_signal_queue_.reset();
saza1d600522019-10-18 13:29:43 +02001877 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001878 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001879 return;
1880 }
1881
1882 if (config_.echo_canceller.mobile_mode) {
1883 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001884 size_t max_element_size =
1885 std::max(static_cast<size_t>(1),
1886 kMaxAllowedValuesOfSamplesPerBand *
1887 EchoControlMobileImpl::NumCancellersRequired(
1888 num_output_channels(), num_reverse_channels()));
1889
1890 std::vector<int16_t> template_queue_element(max_element_size);
1891
1892 aecm_render_signal_queue_.reset(
1893 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1894 kMaxNumFramesToBuffer, template_queue_element,
1895 RenderQueueItemVerifier<int16_t>(max_element_size)));
1896
1897 aecm_render_queue_buffer_.resize(max_element_size);
1898 aecm_capture_queue_buffer_.resize(max_element_size);
1899
saza1d600522019-10-18 13:29:43 +02001900 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001901
saza1d600522019-10-18 13:29:43 +02001902 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1903 num_reverse_channels(),
1904 num_output_channels());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001905
saza1d600522019-10-18 13:29:43 +02001906 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001907 aec_render_signal_queue_.reset();
1908 return;
1909 }
1910
saza1d600522019-10-18 13:29:43 +02001911 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001912 aecm_render_signal_queue_.reset();
1913
Per Åhgrenf204faf2019-04-25 15:18:06 +02001914 // Create and activate AEC2.
saza1d600522019-10-18 13:29:43 +02001915 submodules_.echo_cancellation.reset(new EchoCancellationImpl());
1916 submodules_.echo_cancellation->SetExtraOptions(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001917 capture_nonlocked_.use_aec2_extended_filter,
1918 capture_nonlocked_.use_aec2_delay_agnostic,
1919 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1920
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001921 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001922 std::max(static_cast<size_t>(1),
1923 kMaxAllowedValuesOfSamplesPerBand *
1924 EchoCancellationImpl::NumCancellersRequired(
1925 num_output_channels(), num_reverse_channels()));
1926
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001927 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001928
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001929 aec_render_signal_queue_.reset(
1930 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1931 kMaxNumFramesToBuffer, template_queue_element,
1932 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001933
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001934 aec_render_queue_buffer_.resize(element_max_size);
1935 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001936
saza1d600522019-10-18 13:29:43 +02001937 submodules_.echo_cancellation->Initialize(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001938 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1939 num_proc_channels());
1940
saza1d600522019-10-18 13:29:43 +02001941 submodules_.echo_cancellation->set_suppression_level(
Per Åhgrenf204faf2019-04-25 15:18:06 +02001942 config_.echo_canceller.legacy_moderate_suppression_level
1943 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1944 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001945}
peah8271d042016-11-22 07:24:52 -08001946
alessiob3ec96df2017-05-22 06:57:06 -07001947void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001948 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 13:29:43 +02001949 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001950 }
1951}
1952
saza0bad15f2019-10-16 11:46:11 +02001953void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001954 submodules_.legacy_noise_suppressor.reset();
1955 submodules_.noise_suppressor.reset();
1956
saza0bad15f2019-10-16 11:46:11 +02001957 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001958 const bool use_legacy_ns =
1959 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1960
1961 if (!use_legacy_ns) {
1962 auto map_level =
1963 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1964 using NoiseSuppresionConfig =
1965 AudioProcessing::Config::NoiseSuppression;
1966 switch (level) {
1967 case NoiseSuppresionConfig::kLow:
1968 return NsConfig::SuppressionLevel::k6dB;
1969 case NoiseSuppresionConfig::kModerate:
1970 return NsConfig::SuppressionLevel::k12dB;
1971 case NoiseSuppresionConfig::kHigh:
1972 return NsConfig::SuppressionLevel::k18dB;
1973 case NoiseSuppresionConfig::kVeryHigh:
1974 return NsConfig::SuppressionLevel::k21dB;
1975 default:
1976 RTC_NOTREACHED();
1977 }
1978 };
1979
1980 NsConfig cfg;
1981 cfg.target_level = map_level(config_.noise_suppression.level);
1982 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1983 cfg, proc_sample_rate_hz(), num_proc_channels());
1984 } else {
1985 auto ns_level =
1986 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1987 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1988 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1989 }
saza0bad15f2019-10-16 11:46:11 +02001990 }
1991}
1992
Alex Loikob5c9a792018-04-16 16:31:22 +02001993void AudioProcessingImpl::InitializePreAmplifier() {
1994 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 13:29:43 +02001995 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 16:31:22 +02001996 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1997 } else {
saza1d600522019-10-18 13:29:43 +02001998 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02001999 }
2000}
2001
ivoc9f4a4a02016-10-28 05:39:16 -07002002void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 13:29:43 +02002003 RTC_DCHECK(submodules_.echo_detector);
2004 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002005 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02002006 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07002007}
2008
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002009void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002010 if (submodules_.capture_analyzer) {
2011 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2012 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002013 }
2014}
2015
Sam Zackrisson0beac582017-09-25 12:04:02 +02002016void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002017 if (submodules_.capture_post_processor) {
2018 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002019 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002020 }
2021}
2022
Alex Loiko5825aa62017-12-18 16:02:40 +01002023void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002024 if (submodules_.render_pre_processor) {
2025 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002026 formats_.render_processing_format.sample_rate_hz(),
2027 formats_.render_processing_format.num_channels());
2028 }
2029}
2030
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002031void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002032
aleloi868f32f2017-05-23 07:20:05 -07002033void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2034 if (!aec_dump_) {
2035 return;
2036 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002037
2038 std::string experiments_description = "";
saza1d600522019-10-18 13:29:43 +02002039 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 15:18:06 +02002040 experiments_description +=
saza1d600522019-10-18 13:29:43 +02002041 submodules_.echo_cancellation->GetExperimentsDescription();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002042 }
aleloi868f32f2017-05-23 07:20:05 -07002043 // TODO(peah): Add semicolon-separated concatenations of experiment
2044 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002045 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2046 experiments_description += "AgcClippingLevelExperiment;";
2047 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002048 if (capture_nonlocked_.echo_controller_enabled) {
2049 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002050 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002051 if (config_.gain_controller2.enabled) {
2052 experiments_description += "GainController2;";
2053 }
aleloi868f32f2017-05-23 07:20:05 -07002054
2055 InternalAPMConfig apm_config;
2056
Per Åhgren200feba2019-03-06 04:16:46 +01002057 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002058 apm_config.aec_delay_agnostic_enabled =
saza1d600522019-10-18 13:29:43 +02002059 submodules_.echo_cancellation &&
2060 submodules_.echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002061 apm_config.aec_drift_compensation_enabled =
saza1d600522019-10-18 13:29:43 +02002062 submodules_.echo_cancellation &&
2063 submodules_.echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002064 apm_config.aec_extended_filter_enabled =
saza1d600522019-10-18 13:29:43 +02002065 submodules_.echo_cancellation &&
2066 submodules_.echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002067 apm_config.aec_suppression_level =
saza1d600522019-10-18 13:29:43 +02002068 submodules_.echo_cancellation
2069 ? static_cast<int>(submodules_.echo_cancellation->suppression_level())
Per Åhgrenf204faf2019-04-25 15:18:06 +02002070 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002071
saza1d600522019-10-18 13:29:43 +02002072 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002073 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002074 submodules_.echo_control_mobile &&
2075 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002076 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002077 submodules_.echo_control_mobile
2078 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002079 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002080
saza1d600522019-10-18 13:29:43 +02002081 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
2082 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 07:20:05 -07002083 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 13:29:43 +02002084 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 08:52:22 +01002085 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002086
2087 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2088
saza0bad15f2019-10-16 11:46:11 +02002089 apm_config.ns_enabled = config_.noise_suppression.enabled;
2090 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002091
2092 apm_config.transient_suppression_enabled =
2093 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002094 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002095 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2096 apm_config.pre_amplifier_fixed_gain_factor =
2097 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002098
2099 if (!forced && apm_config == apm_config_for_aec_dump_) {
2100 return;
2101 }
2102 aec_dump_->WriteConfig(apm_config);
2103 apm_config_for_aec_dump_ = apm_config;
2104}
2105
2106void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2107 const float* const* src) {
2108 RTC_DCHECK(aec_dump_);
2109 WriteAecDumpConfigMessage(false);
2110
2111 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2112 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2113 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002114 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002115 RecordAudioProcessingState();
2116}
2117
2118void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2119 const AudioFrame& capture_frame) {
2120 RTC_DCHECK(aec_dump_);
2121 WriteAecDumpConfigMessage(false);
2122
2123 aec_dump_->AddCaptureStreamInput(capture_frame);
2124 RecordAudioProcessingState();
2125}
2126
2127void AudioProcessingImpl::RecordProcessedCaptureStream(
2128 const float* const* processed_capture_stream) {
2129 RTC_DCHECK(aec_dump_);
2130
2131 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2132 const size_t num_channels =
2133 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002134 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2135 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002136 aec_dump_->WriteCaptureStreamMessage();
2137}
2138
2139void AudioProcessingImpl::RecordProcessedCaptureStream(
2140 const AudioFrame& processed_capture_frame) {
2141 RTC_DCHECK(aec_dump_);
2142
2143 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2144 aec_dump_->WriteCaptureStreamMessage();
2145}
2146
2147void AudioProcessingImpl::RecordAudioProcessingState() {
2148 RTC_DCHECK(aec_dump_);
2149 AecDump::AudioProcessingState audio_proc_state;
2150 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2151 audio_proc_state.drift =
saza1d600522019-10-18 13:29:43 +02002152 submodules_.echo_cancellation
2153 ? submodules_.echo_cancellation->stream_drift_samples()
Per Åhgrenf204faf2019-04-25 15:18:06 +02002154 : 0;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002155 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002156 audio_proc_state.keypress = capture_.key_pressed;
2157 aec_dump_->AddAudioProcessingState(audio_proc_state);
2158}
2159
kwiberg83ffe452016-08-29 14:46:07 -07002160AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002161 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002162 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002163 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002164 output_will_be_muted(false),
2165 key_pressed(false),
2166 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002167 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002168 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002169 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002170 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002171 prev_pre_amp_gain(-1.f),
2172 playout_volume(-1),
2173 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002174
2175AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2176
Per Åhgrena1351272019-08-15 12:15:46 +02002177void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2178 const float* const* data,
2179 const StreamConfig& stream_config) {
2180 if (stream_config.has_keyboard()) {
2181 keyboard_data = data[stream_config.num_channels()];
2182 } else {
2183 keyboard_data = NULL;
2184 }
2185 num_keyboard_frames = stream_config.num_frames();
2186}
2187
kwiberg83ffe452016-08-29 14:46:07 -07002188AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2189
2190AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2191
niklase@google.com470e71d2011-07-07 08:21:25 +00002192} // namespace webrtc