blob: 97a8379452ed414610e6ea6ce29db6dccbc6e092 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:251/*
andrew@webrtc.org40654032012-01-30 20:51:152 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:253 *
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 04:47:3111#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:2512
Michael Graczyk86c6d332015-07-23 18:41:3913#include <algorithm>
Yves Gerey988cc082018-10-23 10:03:0114#include <cstdint>
Mirko Bonadei317a1f02019-09-17 15:06:1815#include <memory>
alessiob3ec96df2017-05-22 13:57:0616#include <string>
Yves Gerey988cc082018-10-23 10:03:0117#include <type_traits>
18#include <utility>
niklase@google.com470e71d2011-07-07 08:21:2519
Yves Gerey988cc082018-10-23 10:03:0120#include "absl/types/optional.h"
21#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3122#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3123#include "common_audio/include/audio_util.h"
Alex Loikob5c9a792018-04-16 14:31:2224#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3125#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3126#include "modules/audio_processing/common.h"
Yves Gerey988cc082018-10-23 10:03:0127#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 20:42:5628#include "modules/audio_processing/logging/apm_data_dumper.h"
Steve Anton10542f22019-01-11 17:11:0029#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3130#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0031#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3132#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 17:11:0033#include "rtc_base/ref_counted_object.h"
34#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3135#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 05:50:3536#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3137#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:3138
Michael Graczyk86c6d332015-07-23 18:41:3939#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:0945 } while (0)
46
niklase@google.com470e71d2011-07-07 08:21:2547namespace webrtc {
aluebsdf6416a2016-03-17 01:26:3548
kwibergd59d3bb2016-09-13 14:49:3349constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 08:52:2850constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-17 01:26:3551
Michael Graczyk86c6d332015-07-23 18:41:3952namespace {
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 12:23:2264 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 18:41:3965 return false;
66}
aluebsdf6416a2016-03-17 01:26:3567
peah2ace3f92016-09-10 11:42:2768bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-17 01:26:3569 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
70 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
71}
72
Per Åhgren0cbb58e2019-10-29 21:59:4473// Checks whether the legacy ns functionality should be enforced.
74bool DetectLegacyNsEnforcement() {
75 return field_trial::IsEnabled("WebRTC-NewNoiseSuppressionKillSwitch");
76}
77
Per Åhgrenb2b58d82019-12-02 13:59:4078// 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 13:49:5186// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-14 22:27:5887int SuitableProcessRate(int minimum_rate,
88 int max_splitting_rate,
89 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 13:49:5190 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-14 22:27:5891 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 13:49:5192 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 11:42:2793 if (rate >= uppermost_native_rate) {
94 return uppermost_native_rate;
95 }
96 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-17 01:26:3597 return rate;
98 }
99 }
peah2ace3f92016-09-10 11:42:27100 RTC_NOTREACHED();
101 return uppermost_native_rate;
aluebsdf6416a2016-03-17 01:26:35102}
103
Sam Zackrisson23513132019-01-11 14:10:32104NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
105 AudioProcessing::Config::NoiseSuppression::Level level) {
106 using NsConfig = AudioProcessing::Config::NoiseSuppression;
107 switch (level) {
108 case NsConfig::kLow:
saza0bad15f2019-10-16 09:46:11109 return NoiseSuppression::Level::kLow;
Sam Zackrisson23513132019-01-11 14:10:32110 case NsConfig::kModerate:
saza0bad15f2019-10-16 09:46:11111 return NoiseSuppression::Level::kModerate;
Sam Zackrisson23513132019-01-11 14:10:32112 case NsConfig::kHigh:
saza0bad15f2019-10-16 09:46:11113 return NoiseSuppression::Level::kHigh;
Sam Zackrisson23513132019-01-11 14:10:32114 case NsConfig::kVeryHigh:
saza0bad15f2019-10-16 09:46:11115 return NoiseSuppression::Level::kVeryHigh;
Sam Zackrisson23513132019-01-11 14:10:32116 default:
117 RTC_NOTREACHED();
118 }
119}
120
Sam Zackrissonf0d1c032019-03-27 12:28:08121GainControl::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 14:19:21134// 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 12:04:30139// 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 18:41:39143} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09144
145// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54146static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09147
saza1d600522019-10-18 11:29:43148AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 15:02:40149 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09150 bool render_pre_processor_enabled,
151 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 15:02:40152 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09153 render_pre_processor_enabled_(render_pre_processor_enabled),
154 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 11:42:27155
saza1d600522019-10-18 11:29:43156bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 12:15:09157 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 11:42:27158 bool echo_canceller_enabled,
159 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 12:39:16160 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 11:42:27161 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 11:42:27162 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 13:57:06163 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 14:31:22164 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 11:49:04165 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 12:03:56166 bool voice_detector_enabled,
peah2ace3f92016-09-10 11:42:27167 bool transient_suppressor_enabled) {
168 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 12:15:09169 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 11:42:27170 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
171 changed |=
172 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 12:39:16173 changed |=
174 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 11:42:27175 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
176 changed |=
peah2ace3f92016-09-10 11:42:27177 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 09:33:37178 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 14:31:22179 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 11:49:04180 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 12:03:56181 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 11:42:27182 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
183 if (changed) {
Sam Zackrissoncb1b5562018-09-28 12:15:09184 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 11:42:27185 echo_canceller_enabled_ = echo_canceller_enabled;
186 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 12:39:16187 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 11:42:27188 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 11:42:27189 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 13:57:06190 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 14:31:22191 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 11:49:04192 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 12:03:56193 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 11:42:27194 transient_suppressor_enabled_ = transient_suppressor_enabled;
195 }
196
197 changed |= first_update_;
198 first_update_ = false;
199 return changed;
200}
201
saza1d600522019-10-18 11:29:43202bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 11:42:27203 const {
Gustaf Ullberg8675eee2019-10-09 11:34:36204 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 11:42:27205}
206
saza1d600522019-10-18 11:29:43207bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
208 const {
Gustaf Ullberg8675eee2019-10-09 11:34:36209 // If echo controller is present, assume it performs active processing.
210 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
211}
212
saza1d600522019-10-18 11:29:43213bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 11:34:36214 bool ec_processing_active) const {
Sam Zackrissoncb1b5562018-09-28 12:15:09215 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 11:42:27216 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 11:34:36217 adaptive_gain_controller_enabled_ ||
218 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 11:42:27219}
220
saza1d600522019-10-18 11:29:43221bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 12:33:56222 const {
Alex Loikob5c9a792018-04-16 14:31:22223 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
224 pre_amplifier_enabled_;
peah23ac8b42017-05-23 12:33:56225}
226
saza1d600522019-10-18 11:29:43227bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09228 return capture_analyzer_enabled_;
229}
230
saza1d600522019-10-18 11:29:43231bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 11:42:27232 const {
233 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 13:24:35234 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 11:49:04235 echo_controller_enabled_;
peah2ace3f92016-09-10 11:42:27236}
237
saza1d600522019-10-18 11:29:43238bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 15:02:40239 const {
240 return render_pre_processor_enabled_;
241}
242
saza1d600522019-10-18 11:29:43243bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 11:42:27244 const {
peah2ace3f92016-09-10 11:42:27245 return false;
peah2ace3f92016-09-10 11:42:27246}
247
saza1d600522019-10-18 11:29:43248bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Sam Zackrissoncb1b5562018-09-28 12:15:09249 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
Per Åhgren4011de02019-12-03 11:48:48250 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 12:15:09251}
252
Ivo Creusen5ec7e122017-12-22 10:35:59253AudioProcessingBuilder::AudioProcessingBuilder() = default;
254AudioProcessingBuilder::~AudioProcessingBuilder() = default;
255
256AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
257 std::unique_ptr<CustomProcessing> capture_post_processing) {
258 capture_post_processing_ = std::move(capture_post_processing);
259 return *this;
260}
261
262AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
263 std::unique_ptr<CustomProcessing> render_pre_processing) {
264 render_pre_processing_ = std::move(render_pre_processing);
265 return *this;
266}
267
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09268AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
269 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
270 capture_analyzer_ = std::move(capture_analyzer);
271 return *this;
272}
273
Ivo Creusen5ec7e122017-12-22 10:35:59274AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
275 std::unique_ptr<EchoControlFactory> echo_control_factory) {
276 echo_control_factory_ = std::move(echo_control_factory);
277 return *this;
278}
279
Ivo Creusen09fa4b02018-01-11 15:08:54280AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 09:02:03281 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 15:08:54282 echo_detector_ = std::move(echo_detector);
283 return *this;
284}
285
Ivo Creusen5ec7e122017-12-22 10:35:59286AudioProcessing* AudioProcessingBuilder::Create() {
287 webrtc::Config config;
288 return Create(config);
289}
290
291AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 15:08:54292 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
293 config, std::move(capture_post_processing_),
294 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09295 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 15:08:54296 if (apm->Initialize() != AudioProcessing::kNoError) {
297 delete apm;
298 apm = nullptr;
299 }
300 return apm;
Ivo Creusen5ec7e122017-12-22 10:35:59301}
302
peah88ac8532016-09-12 23:47:25303AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 05:50:35304 : AudioProcessingImpl(config,
305 /*capture_post_processor=*/nullptr,
306 /*render_pre_processor=*/nullptr,
307 /*echo_control_factory=*/nullptr,
308 /*echo_detector=*/nullptr,
309 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21310
Per Åhgren13735822018-02-12 20:42:56311int AudioProcessingImpl::instance_count_ = 0;
312
Sam Zackrisson0beac582017-09-25 10:04:02313AudioProcessingImpl::AudioProcessingImpl(
314 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 15:02:40315 std::unique_ptr<CustomProcessing> capture_post_processor,
316 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 13:13:17317 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09318 rtc::scoped_refptr<EchoDetector> echo_detector,
319 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 20:42:56320 : data_dumper_(
321 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Per Åhgren0cbb58e2019-10-29 21:59:44322 enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()),
Per Åhgrenb2b58d82019-12-02 13:59:40323 use_setup_specific_default_aec3_config_(
324 UseSetupSpecificDefaultAec3Congfig()),
Alex Loiko73ec0192018-05-15 08:52:28325 capture_runtime_settings_(kRuntimeSettingQueueSize),
326 render_runtime_settings_(kRuntimeSettingQueueSize),
327 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
328 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 13:13:17329 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09330 submodule_states_(!!capture_post_processor,
331 !!render_pre_processor,
332 !!capture_analyzer),
saza1d600522019-10-18 11:29:43333 submodules_(std::move(capture_post_processor),
334 std::move(render_pre_processor),
335 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 11:11:40336 std::move(capture_analyzer)),
337 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
338 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24339#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Per Åhgren3daedb62019-11-22 11:11:40340 /* enabled= */ false,
341 /* enabled_agc2_level_estimator= */ false,
342 /* digital_adaptive_disabled= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24343#else
Per Åhgren3daedb62019-11-22 11:11:40344 config.Get<ExperimentalAgc>().enabled,
345 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
346 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
pbos@webrtc.org788acd12014-12-15 09:41:24347#endif
Sam Zackrissonfeee1e42019-09-20 05:50:35348 !field_trial::IsEnabled(
349 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
350 !field_trial::IsEnabled(
351 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-25 01:14:14352#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 08:11:35353 capture_(false),
andrew1c7075f2015-06-25 01:14:14354#else
Sam Zackrisson9394f6f2018-06-14 08:11:35355 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-25 01:14:14356#endif
Alessio Bazzicacc22f512018-08-30 11:01:34357 capture_nonlocked_() {
Sam Zackrisson72cc71c2019-10-21 10:54:02358 RTC_LOG(LS_INFO) << "Injected APM submodules:"
359 << "\nEcho control factory: " << !!echo_control_factory_
360 << "\nEcho detector: " << !!submodules_.echo_detector
361 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
362 << "\nCapture post processor: "
363 << !!submodules_.capture_post_processor
364 << "\nRender pre processor: "
365 << !!submodules_.render_pre_processor;
366
Sam Zackrisson421c8592019-02-11 12:39:46367 // Mark Echo Controller enabled if a factory is injected.
368 capture_nonlocked_.echo_controller_enabled =
369 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25370
saza1d600522019-10-18 11:29:43371 submodules_.gain_control.reset(new GainControlImpl());
Gustaf Ullbergce045ac2017-10-16 11:49:04372
Sam Zackrisson421c8592019-02-11 12:39:46373 // If no echo detector is injected, use the ResidualEchoDetector.
saza1d600522019-10-18 11:29:43374 if (!submodules_.echo_detector) {
375 submodules_.echo_detector =
Sam Zackrisson421c8592019-02-11 12:39:46376 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 20:35:15377 }
pbos@webrtc.org788acd12014-12-15 09:41:24378
Sam Zackrisson421c8592019-02-11 12:39:46379 // TODO(alessiob): Move the injected gain controller once injection is
380 // implemented.
saza1d600522019-10-18 11:29:43381 submodules_.gain_controller2.reset(new GainController2());
Sam Zackrisson421c8592019-02-11 12:39:46382
andrew@webrtc.orge84978f2014-01-25 02:09:06383 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25384}
385
Per Åhgren0e3198e2019-11-18 07:52:22386AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25387
niklase@google.com470e71d2011-07-07 08:21:25388int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 20:35:15389 // Run in a single-threaded manner during initialization.
390 rtc::CritScope cs_render(&crit_render_);
391 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25392 return InitializeLocked();
393}
394
peahde65ddc2016-09-16 22:02:15395int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
396 int capture_output_sample_rate_hz,
397 int render_input_sample_rate_hz,
398 ChannelLayout capture_input_layout,
399 ChannelLayout capture_output_layout,
400 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 18:41:39401 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 22:02:15402 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
403 LayoutHasKeyboard(capture_input_layout)},
404 {capture_output_sample_rate_hz,
405 ChannelsFromLayout(capture_output_layout),
406 LayoutHasKeyboard(capture_output_layout)},
407 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
408 LayoutHasKeyboard(render_input_layout)},
409 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
410 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 18:41:39411
412 return Initialize(processing_config);
413}
414
415int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 20:35:15416 // Run in a single-threaded manner during initialization.
417 rtc::CritScope cs_render(&crit_render_);
418 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 18:41:39419 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12420}
421
peahdf3efa82015-11-28 20:35:15422int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 10:47:28423 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 20:35:15424 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 12:28:00425 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 10:16:45426 return kNoError;
427 }
peahdf3efa82015-11-28 20:35:15428
429 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 10:16:45430 return InitializeLocked(processing_config);
431}
432
niklase@google.com470e71d2011-07-07 08:21:25433int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 14:00:38434 UpdateActiveSubmoduleStates();
435
Per Åhgrend47941e2019-08-22 09:51:13436 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 20:35:15437 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 09:51:13438 ? formats_.render_processing_format.sample_rate_hz()
439 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 20:35:15440 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
441 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 09:51:13442 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 20:35:15443 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 09:51:13444 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 22:02:15445 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 09:51:13446 render_audiobuffer_sample_rate_hz,
447 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 11:42:27448 if (formats_.api_format.reverse_input_stream() !=
449 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 13:22:32450 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 20:35:15451 formats_.api_format.reverse_input_stream().num_channels(),
452 formats_.api_format.reverse_input_stream().num_frames(),
453 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 13:22:32454 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 17:35:55455 } else {
peahdf3efa82015-11-28 20:35:15456 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 17:35:55457 }
Michael Graczyk86c6d332015-07-23 18:41:39458 } else {
peahdf3efa82015-11-28 20:35:15459 render_.render_audio.reset(nullptr);
460 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 18:41:39461 }
peahce4d9152017-05-19 08:28:05462
Per Åhgrend47941e2019-08-22 09:51:13463 capture_.capture_audio.reset(new AudioBuffer(
464 formats_.api_format.input_stream().sample_rate_hz(),
465 formats_.api_format.input_stream().num_channels(),
466 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
467 formats_.api_format.output_stream().num_channels(),
468 formats_.api_format.output_stream().sample_rate_hz(),
469 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25470
Gustaf Ullberg422b9e02019-10-09 11:02:14471 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
472 formats_.api_format.output_stream().sample_rate_hz() &&
473 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
474 capture_.capture_fullband_audio.reset(
475 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
476 formats_.api_format.input_stream().num_channels(),
477 formats_.api_format.output_stream().sample_rate_hz(),
478 formats_.api_format.output_stream().num_channels(),
479 formats_.api_format.output_stream().sample_rate_hz(),
480 formats_.api_format.output_stream().num_channels()));
481 } else {
482 capture_.capture_fullband_audio.reset();
483 }
484
peah764e3642016-10-22 12:04:30485 AllocateRenderQueue();
486
saza1d600522019-10-18 11:29:43487 submodules_.gain_control->Initialize(num_proc_channels(),
488 proc_sample_rate_hz());
Per Åhgren3daedb62019-11-22 11:11:40489 if (constants_.use_experimental_agc) {
490 if (!submodules_.agc_manager.get() ||
491 submodules_.agc_manager->num_channels() !=
492 static_cast<int>(num_proc_channels()) ||
493 submodules_.agc_manager->sample_rate_hz() !=
494 capture_nonlocked_.split_rate) {
Per Åhgren2a6b3b12019-11-26 18:34:26495 int stream_analog_level = -1;
496 const bool re_creation = !!submodules_.agc_manager;
497 if (re_creation) {
498 stream_analog_level = submodules_.agc_manager->stream_analog_level();
499 }
Per Åhgren3daedb62019-11-22 11:11:40500 submodules_.agc_manager.reset(new AgcManagerDirect(
501 num_proc_channels(), constants_.agc_startup_min_volume,
502 constants_.agc_clipped_level_min,
503 constants_.use_experimental_agc_agc2_level_estimation,
504 constants_.use_experimental_agc_agc2_digital_adaptive,
505 capture_nonlocked_.split_rate));
Per Åhgren2a6b3b12019-11-26 18:34:26506 if (re_creation) {
507 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
508 }
Per Åhgren3daedb62019-11-22 11:11:40509 }
saza1d600522019-10-18 11:29:43510 submodules_.agc_manager->Initialize();
Per Åhgren3daedb62019-11-22 11:11:40511 submodules_.agc_manager->SetupDigitalGainControl(
Per Åhgren0e3198e2019-11-18 07:52:22512 submodules_.gain_control.get());
saza1d600522019-10-18 11:29:43513 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
peahde65ddc2016-09-16 22:02:15514 }
Bjorn Volckeradc46c42015-04-15 09:42:40515 InitializeTransient();
Per Åhgren4011de02019-12-03 11:48:48516 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 12:03:56517 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 12:39:16518 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 06:28:46519 InitializeEchoController();
alessiob3ec96df2017-05-22 13:57:06520 InitializeGainController2();
saza0bad15f2019-10-16 09:46:11521 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 08:37:09522 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 10:04:02523 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 15:02:40524 InitializePreProcessor();
solenberg70f99032015-12-08 19:07:32525
aleloi868f32f2017-05-23 14:20:05526 if (aec_dump_) {
Minyue Li656d6092018-08-10 13:38:52527 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 14:20:05528 }
niklase@google.com470e71d2011-07-07 08:21:25529 return kNoError;
530}
531
Michael Graczyk86c6d332015-07-23 18:41:39532int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 14:00:38533 UpdateActiveSubmoduleStates();
534
Michael Graczyk86c6d332015-07-23 18:41:39535 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 18:41:39536 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
537 return kBadSampleRateError;
538 }
andrew@webrtc.orga8b97372014-03-10 22:26:12539 }
Michael Graczyk86c6d332015-07-23 18:41:39540
Peter Kasting69558702016-01-13 00:26:35541 const size_t num_in_channels = config.input_stream().num_channels();
542 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 18:41:39543
544 // Need at least one input channel.
545 // Need either one output channel or as many outputs as there are inputs.
546 if (num_in_channels == 0 ||
547 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-23 04:06:11548 return kBadNumberChannelsError;
549 }
550
peahdf3efa82015-11-28 20:35:15551 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04552
Per Åhgrenfcbe4072019-09-14 22:27:58553 // Choose maximum rate to use for the split filtering.
554 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
555 config_.pipeline.maximum_internal_processing_rate == 32000);
556 int max_splitting_rate = 48000;
557 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
558 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
559 }
560
Per Åhgrenc8626b62019-08-23 13:49:51561 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 23:06:52562 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 11:42:27563 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-14 22:27:58564 max_splitting_rate,
peah2ace3f92016-09-10 11:42:27565 submodule_states_.CaptureMultiBandSubModulesActive() ||
566 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 13:49:51567 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12568
peahde65ddc2016-09-16 22:02:15569 capture_nonlocked_.capture_processing_format =
570 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 11:42:27571
peah2ce640f2017-04-07 10:57:48572 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 10:32:42573 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 13:49:51574 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 10:57:48575 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
576 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-14 22:27:58577 max_splitting_rate,
peah2ce640f2017-04-07 10:57:48578 submodule_states_.CaptureMultiBandSubModulesActive() ||
579 submodule_states_.RenderMultiBandSubModulesActive());
580 } else {
581 render_processing_rate = capture_processing_rate;
582 }
583
peahde65ddc2016-09-16 22:02:15584 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 22:27:58585 // at this rate.
peahde65ddc2016-09-16 22:02:15586 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
587 kSampleRate8kHz) {
588 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12589 } else {
peahde65ddc2016-09-16 22:02:15590 render_processing_rate =
591 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04592 }
593
Per Åhgrenc8626b62019-08-23 13:49:51594 RTC_DCHECK_NE(8000, render_processing_rate);
595
peahce4d9152017-05-19 08:28:05596 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 05:50:35597 // By default, downmix the render stream to mono for analysis. This has been
598 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 08:34:22599 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
600 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 05:50:35601 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 08:34:22602 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 05:50:35603 ? formats_.api_format.reverse_input_stream().num_channels()
604 : 1;
605 formats_.render_processing_format =
606 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 08:28:05607 } else {
608 formats_.render_processing_format = StreamConfig(
609 formats_.api_format.reverse_input_stream().sample_rate_hz(),
610 formats_.api_format.reverse_input_stream().num_channels());
611 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04612
peahde65ddc2016-09-16 22:02:15613 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
614 kSampleRate32kHz ||
615 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
616 kSampleRate48kHz) {
peahdf3efa82015-11-28 20:35:15617 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04618 } else {
peahdf3efa82015-11-28 20:35:15619 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 22:02:15620 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12621 }
622
623 return InitializeLocked();
624}
625
peah88ac8532016-09-12 23:47:25626void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 10:54:02627 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
628
peah88ac8532016-09-12 23:47:25629 // Run in a single-threaded manner when applying the settings.
630 rtc::CritScope cs_render(&crit_render_);
631 rtc::CritScope cs_capture(&crit_capture_);
632
Sam Zackrissonfeee1e42019-09-20 05:50:35633 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 08:34:22634 config_.pipeline.multi_channel_render !=
635 config.pipeline.multi_channel_render ||
636 config_.pipeline.multi_channel_capture !=
637 config.pipeline.multi_channel_capture;
Sam Zackrissonfeee1e42019-09-20 05:50:35638
Per Åhgren200feba1c2019-03-06 03:16:46639 const bool aec_config_changed =
640 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
641 config_.echo_canceller.use_legacy_aec !=
642 config.echo_canceller.use_legacy_aec ||
643 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
644 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
645 config_.echo_canceller.legacy_moderate_suppression_level !=
646 config.echo_canceller.legacy_moderate_suppression_level);
647
Sam Zackrissonf0d1c032019-03-27 12:28:08648 const bool agc1_config_changed =
649 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
650 config_.gain_controller1.mode != config.gain_controller1.mode ||
651 config_.gain_controller1.target_level_dbfs !=
652 config.gain_controller1.target_level_dbfs ||
653 config_.gain_controller1.compression_gain_db !=
654 config.gain_controller1.compression_gain_db ||
655 config_.gain_controller1.enable_limiter !=
656 config.gain_controller1.enable_limiter ||
657 config_.gain_controller1.analog_level_minimum !=
658 config.gain_controller1.analog_level_minimum ||
659 config_.gain_controller1.analog_level_maximum !=
660 config.gain_controller1.analog_level_maximum;
661
Sam Zackrisson0824c6f2019-10-07 12:03:56662 const bool voice_detection_config_changed =
663 config_.voice_detection.enabled != config.voice_detection.enabled;
664
saza0bad15f2019-10-16 09:46:11665 const bool ns_config_changed =
666 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
667 config_.noise_suppression.level != config.noise_suppression.level;
668
Yves Gerey499bc6c2018-10-10 16:29:07669 config_ = config;
670
Per Åhgren200feba1c2019-03-06 03:16:46671 if (aec_config_changed) {
672 InitializeEchoController();
673 }
Sam Zackrissoncdf0e6d2018-09-17 09:05:17674
saza0bad15f2019-10-16 09:46:11675 if (ns_config_changed) {
676 InitializeNoiseSuppressor();
677 }
Sam Zackrisson23513132019-01-11 14:10:32678
Per Åhgren4011de02019-12-03 11:48:48679 InitializeHighPassFilter();
peah8271d042016-11-22 15:24:52680
Sam Zackrissonf0d1c032019-03-27 12:28:08681 if (agc1_config_changed) {
682 ApplyAgc1Config(config_.gain_controller1);
683 }
684
Sam Zackrissonab1aee02018-03-05 14:59:06685 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 13:57:06686 if (!config_ok) {
Jonas Olsson645b0272018-02-15 14:16:27687 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
688 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 10:09:25689 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 14:16:27690 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 13:57:06691 config_.gain_controller2 = AudioProcessing::Config::GainController2();
692 }
Alessio Bazzica270f7b52017-10-13 09:05:17693 InitializeGainController2();
Alex Loikob5c9a792018-04-16 14:31:22694 InitializePreAmplifier();
saza1d600522019-10-18 11:29:43695 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Sam Zackrissonb24c00f2018-11-26 15:18:25696
saza1d600522019-10-18 11:29:43697 if (config_.level_estimation.enabled && !submodules_.output_level_estimator) {
698 submodules_.output_level_estimator = std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 15:18:25699 }
Sam Zackrisson4db667b2018-12-21 15:29:27700
Sam Zackrisson0824c6f2019-10-07 12:03:56701 if (voice_detection_config_changed) {
702 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 15:29:27703 }
Sam Zackrissonfeee1e42019-09-20 05:50:35704
705 // Reinitialization must happen after all submodule configuration to avoid
706 // additional reinitializations on the next capture / render processing call.
707 if (pipeline_config_changed) {
708 InitializeLocked(formats_.api_format);
709 }
peah88ac8532016-09-12 23:47:25710}
711
Sam Zackrissonf0d1c032019-03-27 12:28:08712void AudioProcessingImpl::ApplyAgc1Config(
713 const Config::GainController1& config) {
Per Åhgren0e3198e2019-11-18 07:52:22714 int error = submodules_.gain_control->Enable(config.enabled);
Sam Zackrissonf0d1c032019-03-27 12:28:08715 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 12:28:08716
Per Åhgren0e3198e2019-11-18 07:52:22717 if (!submodules_.agc_manager) {
718 error = submodules_.gain_control->set_mode(
719 Agc1ConfigModeToInterfaceMode(config.mode));
720 RTC_DCHECK_EQ(kNoError, error);
721 error = submodules_.gain_control->set_target_level_dbfs(
722 config.target_level_dbfs);
723 RTC_DCHECK_EQ(kNoError, error);
724 error = submodules_.gain_control->set_compression_gain_db(
725 config.compression_gain_db);
726 RTC_DCHECK_EQ(kNoError, error);
727 error = submodules_.gain_control->enable_limiter(config.enable_limiter);
728 RTC_DCHECK_EQ(kNoError, error);
729 error = submodules_.gain_control->set_analog_level_limits(
730 config.analog_level_minimum, config.analog_level_maximum);
731 RTC_DCHECK_EQ(kNoError, error);
Sam Zackrissonf0d1c032019-03-27 12:28:08732 }
Sam Zackrissonf0d1c032019-03-27 12:28:08733}
734
peah88ac8532016-09-12 23:47:25735void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 20:35:15736 // Run in a single-threaded manner when setting the extra options.
737 rtc::CritScope cs_render(&crit_render_);
738 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24739
Per Åhgrenf204faf2019-04-25 13:18:06740 capture_nonlocked_.use_aec2_extended_filter =
741 config.Get<ExtendedFilter>().enabled;
742 capture_nonlocked_.use_aec2_delay_agnostic =
743 config.Get<DelayAgnostic>().enabled;
744 capture_nonlocked_.use_aec2_refined_adaptive_filter =
745 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 11:01:14746
peahdf3efa82015-11-28 20:35:15747 if (capture_.transient_suppressor_enabled !=
748 config.Get<ExperimentalNs>().enabled) {
749 capture_.transient_suppressor_enabled =
750 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24751 InitializeTransient();
752 }
andrew@webrtc.org61e596f2013-07-25 18:28:29753}
754
andrew@webrtc.orgddbb8a22014-04-22 21:00:04755int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 20:35:15756 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 22:02:15757 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25758}
759
Gustaf Ullberg422b9e02019-10-09 11:02:14760int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
761 return capture_.capture_fullband_audio
762 ? capture_.capture_fullband_audio->num_frames() * 100
763 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
764}
765
andrew@webrtc.orgddbb8a22014-04-22 21:00:04766int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 20:35:15767 // Used as callback from submodules, hence locking is not allowed.
768 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25769}
770
Peter Kasting69558702016-01-13 00:26:35771size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 20:35:15772 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 22:02:15773 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25774}
775
Peter Kasting69558702016-01-13 00:26:35776size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 20:35:15777 // Used as callback from submodules, hence locking is not allowed.
778 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25779}
780
Peter Kasting69558702016-01-13 00:26:35781size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-12 04:32:29782 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 08:34:22783 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
784 constants_.multi_channel_capture_support;
785 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 05:50:35786 return 1;
787 }
788 return num_output_channels();
aluebsb2328d12016-01-12 04:32:29789}
790
Peter Kasting69558702016-01-13 00:26:35791size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 20:35:15792 // Used as callback from submodules, hence locking is not allowed.
793 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25794}
795
andrew@webrtc.org17342e52014-02-12 22:28:31796void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 20:35:15797 rtc::CritScope cs(&crit_capture_);
798 capture_.output_will_be_muted = muted;
saza1d600522019-10-18 11:29:43799 if (submodules_.agc_manager.get()) {
800 submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24801 }
andrew@webrtc.org17342e52014-02-12 22:28:31802}
803
Alessio Bazzicac054e782018-04-16 10:10:09804void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 08:52:28805 switch (setting.type()) {
806 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 12:22:00807 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Alex Loiko73ec0192018-05-15 08:52:28808 render_runtime_settings_enqueuer_.Enqueue(setting);
809 return;
Alex Loiko73ec0192018-05-15 08:52:28810 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 12:28:08811 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 09:33:37812 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alessio Bazzica7c19a702019-11-07 12:22:00813 capture_runtime_settings_enqueuer_.Enqueue(setting);
814 return;
Fredrik Hernqvistca362852019-05-10 13:50:02815 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 08:52:28816 capture_runtime_settings_enqueuer_.Enqueue(setting);
Alessio Bazzica7c19a702019-11-07 12:22:00817 render_runtime_settings_enqueuer_.Enqueue(setting);
818 return;
819 case RuntimeSetting::Type::kNotSpecified:
820 RTC_NOTREACHED();
Alex Loiko73ec0192018-05-15 08:52:28821 return;
822 }
823 // The language allows the enum to have a non-enumerator
824 // value. Check that this doesn't happen.
825 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 10:10:09826}
827
828AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
829 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 11:16:55830 : runtime_settings_(*runtime_settings) {
831 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 10:10:09832}
833
834AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
835 default;
836
837void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
838 RuntimeSetting setting) {
839 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 11:16:55840 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 10:10:09841 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 11:16:55842 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 10:10:09843 RTC_LOG(LS_ERROR)
844 << "The runtime settings queue is full. Oldest setting discarded.";
845 }
846 if (remaining_attempts == 0)
847 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
848}
andrew@webrtc.org17342e52014-02-12 22:28:31849
andrew@webrtc.orgddbb8a22014-04-22 21:00:04850int AudioProcessingImpl::ProcessStream(const float* const* src,
Michael Graczyk86c6d332015-07-23 18:41:39851 const StreamConfig& input_config,
852 const StreamConfig& output_config,
853 float* const* dest) {
peah369f8282015-12-17 14:42:29854 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 20:35:15855 ProcessingConfig processing_config;
peah2ace3f92016-09-10 11:42:27856 bool reinitialization_required = false;
peahdf3efa82015-11-28 20:35:15857 {
858 // Acquire the capture lock in order to safely call the function
859 // that retrieves the render side data. This function accesses apm
860 // getters that need the capture lock held when being called.
861 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 12:04:30862 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 20:35:15863
864 if (!src || !dest) {
865 return kNullPointerError;
866 }
867
868 processing_config = formats_.api_format;
peah2ace3f92016-09-10 11:42:27869 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25870 }
andrew@webrtc.org17e40642014-03-04 20:58:13871
Oskar Sundbom4b276482019-05-23 12:28:00872 if (processing_config.input_stream() != input_config) {
873 processing_config.input_stream() = input_config;
874 reinitialization_required = true;
peahdf3efa82015-11-28 20:35:15875 }
Oskar Sundbom4b276482019-05-23 12:28:00876
877 if (processing_config.output_stream() != output_config) {
878 processing_config.output_stream() = output_config;
879 reinitialization_required = true;
880 }
881
882 if (reinitialization_required) {
883 // Reinitialize.
884 rtc::CritScope cs_render(&crit_render_);
885 rtc::CritScope cs_capture(&crit_capture_);
886 RETURN_ON_ERR(InitializeLocked(processing_config));
887 }
888
peahdf3efa82015-11-28 20:35:15889 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 12:23:22890 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
891 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13892
aleloi868f32f2017-05-23 14:20:05893 if (aec_dump_) {
894 RecordUnprocessedCaptureStream(src);
895 }
896
Per Åhgrena1351272019-08-15 10:15:46897 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 20:35:15898 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 11:34:36899 if (capture_.capture_fullband_audio) {
900 capture_.capture_fullband_audio->CopyFrom(
901 src, formats_.api_format.input_stream());
902 }
peahde65ddc2016-09-16 22:02:15903 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 11:02:14904 if (capture_.capture_fullband_audio) {
905 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
906 dest);
907 } else {
908 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
909 }
andrew@webrtc.org17e40642014-03-04 20:58:13910
aleloi868f32f2017-05-23 14:20:05911 if (aec_dump_) {
912 RecordProcessedCaptureStream(dest);
913 }
andrew@webrtc.org17e40642014-03-04 20:58:13914 return kNoError;
915}
916
Alex Loiko73ec0192018-05-15 08:52:28917void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 10:10:09918 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 08:52:28919 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 08:18:07920 if (aec_dump_) {
921 aec_dump_->WriteRuntimeSetting(setting);
922 }
Alessio Bazzicac054e782018-04-16 10:10:09923 switch (setting.type()) {
924 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 14:31:22925 if (config_.pre_amplifier.enabled) {
926 float value;
927 setting.GetFloat(&value);
Sam Zackrisson21bfa402019-10-23 07:43:01928 config_.pre_amplifier.fixed_gain_factor = value;
saza1d600522019-10-18 11:29:43929 submodules_.pre_amplifier->SetGainFactor(value);
Alex Loikob5c9a792018-04-16 14:31:22930 }
931 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 10:10:09932 break;
Sam Zackrissonf0d1c032019-03-27 12:28:08933 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 07:52:22934 if (!submodules_.agc_manager) {
935 float value;
936 setting.GetFloat(&value);
937 int int_value = static_cast<int>(value + .5f);
938 config_.gain_controller1.compression_gain_db = int_value;
939 int error =
940 submodules_.gain_control->set_compression_gain_db(int_value);
941 RTC_DCHECK_EQ(kNoError, error);
942 }
Sam Zackrissonf0d1c032019-03-27 12:28:08943 break;
944 }
Per Åhgren6ee75fd2019-04-26 09:33:37945 case RuntimeSetting::Type::kCaptureFixedPostGain: {
946 if (config_.gain_controller2.enabled) {
947 float value;
948 setting.GetFloat(&value);
949 config_.gain_controller2.fixed_digital.gain_db = value;
saza1d600522019-10-18 11:29:43950 submodules_.gain_controller2->ApplyConfig(config_.gain_controller2);
Per Åhgren6ee75fd2019-04-26 09:33:37951 }
952 break;
953 }
Fredrik Hernqvistca362852019-05-10 13:50:02954 case RuntimeSetting::Type::kPlayoutVolumeChange: {
955 int value;
956 setting.GetInt(&value);
957 capture_.playout_volume = value;
958 break;
959 }
Alessio Bazzica7c19a702019-11-07 12:22:00960 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
961 RTC_NOTREACHED();
962 break;
Alex Loiko73ec0192018-05-15 08:52:28963 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
964 RTC_NOTREACHED();
965 break;
966 case RuntimeSetting::Type::kNotSpecified:
967 RTC_NOTREACHED();
968 break;
969 }
970 }
971}
972
973void AudioProcessingImpl::HandleRenderRuntimeSettings() {
974 RuntimeSetting setting;
975 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 08:18:07976 if (aec_dump_) {
977 aec_dump_->WriteRuntimeSetting(setting);
978 }
Alex Loiko73ec0192018-05-15 08:52:28979 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 12:22:00980 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 12:32:20981 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 08:52:28982 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 11:29:43983 if (submodules_.render_pre_processor) {
984 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 08:52:28985 }
986 break;
Sam Zackrissonf0d1c032019-03-27 12:28:08987 case RuntimeSetting::Type::kCapturePreGain: // fall-through
988 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 09:33:37989 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 11:16:55990 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 10:10:09991 RTC_NOTREACHED();
992 break;
993 }
994 }
995}
996
peah9e6a2902017-05-15 14:19:21997void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 23:21:39998 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 12:04:30999
1000 // Insert the samples into the queue.
saza1d600522019-10-18 11:29:431001 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 13:18:061002 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 10:14:501003 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1004 num_reverse_channels(),
1005 &aec_render_queue_buffer_);
1006
Per Åhgrenf204faf2019-04-25 13:18:061007 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1008 // The data queue is full and needs to be emptied.
1009 EmptyQueuedRenderAudio();
peah764e3642016-10-22 12:04:301010
Per Åhgrenf204faf2019-04-25 13:18:061011 // Retry the insert (should always work).
1012 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1013 RTC_DCHECK(result);
1014 }
peaha0624602016-10-25 11:45:241015 }
1016
saza1d600522019-10-18 11:29:431017 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 10:14:501018 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1019 num_reverse_channels(),
1020 &aecm_render_queue_buffer_);
1021 RTC_DCHECK(aecm_render_signal_queue_);
1022 // Insert the samples into the queue.
1023 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1024 // The data queue is full and needs to be emptied.
1025 EmptyQueuedRenderAudio();
peaha0624602016-10-25 11:45:241026
Per Åhgrenb6e24d72019-04-29 10:14:501027 // Retry the insert (should always work).
1028 bool result =
1029 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1030 RTC_DCHECK(result);
1031 }
peah764e3642016-10-22 12:04:301032 }
peah701d6282016-10-25 12:42:201033
Per Åhgren0e3198e2019-11-18 07:52:221034 if (!submodules_.agc_manager) {
Per Åhgrene35b32c2019-11-22 17:22:041035 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 12:42:201036 // Insert the samples into the queue.
1037 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1038 // The data queue is full and needs to be emptied.
1039 EmptyQueuedRenderAudio();
1040
1041 // Retry the insert (should always work).
1042 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1043 RTC_DCHECK(result);
1044 }
1045 }
peah9e6a2902017-05-15 14:19:211046}
ivoc9f4a4a02016-10-28 12:39:161047
peah9e6a2902017-05-15 14:19:211048void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 12:39:161049 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1050
1051 // Insert the samples into the queue.
1052 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1053 // The data queue is full and needs to be emptied.
1054 EmptyQueuedRenderAudio();
1055
1056 // Retry the insert (should always work).
1057 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1058 RTC_DCHECK(result);
1059 }
peah764e3642016-10-22 12:04:301060}
1061
1062void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 12:42:201063 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 14:19:211064 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 12:42:201065
ivoc9f4a4a02016-10-28 12:39:161066 const size_t new_red_render_queue_element_max_size =
1067 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1068
peaha0624602016-10-25 11:45:241069 // Reallocate the queues if the queue item sizes are too small to fit the
1070 // data to put in the queues.
peah701d6282016-10-25 12:42:201071
1072 if (agc_render_queue_element_max_size_ <
1073 new_agc_render_queue_element_max_size) {
1074 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1075
1076 std::vector<int16_t> template_queue_element(
1077 agc_render_queue_element_max_size_);
1078
1079 agc_render_signal_queue_.reset(
1080 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1081 kMaxNumFramesToBuffer, template_queue_element,
1082 RenderQueueItemVerifier<int16_t>(
1083 agc_render_queue_element_max_size_)));
1084
1085 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1086 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1087 } else {
1088 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 12:04:301089 }
ivoc9f4a4a02016-10-28 12:39:161090
1091 if (red_render_queue_element_max_size_ <
1092 new_red_render_queue_element_max_size) {
1093 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1094
1095 std::vector<float> template_queue_element(
1096 red_render_queue_element_max_size_);
1097
1098 red_render_signal_queue_.reset(
1099 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1100 kMaxNumFramesToBuffer, template_queue_element,
1101 RenderQueueItemVerifier<float>(
1102 red_render_queue_element_max_size_)));
1103
1104 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1105 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1106 } else {
1107 red_render_signal_queue_->Clear();
1108 }
peah764e3642016-10-22 12:04:301109}
1110
1111void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1112 rtc::CritScope cs_capture(&crit_capture_);
saza1d600522019-10-18 11:29:431113 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 13:18:061114 RTC_DCHECK(aec_render_signal_queue_);
1115 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
saza1d600522019-10-18 11:29:431116 submodules_.echo_cancellation->ProcessRenderAudio(
Per Åhgrenf204faf2019-04-25 13:18:061117 aec_capture_queue_buffer_);
1118 }
peaha0624602016-10-25 11:45:241119 }
1120
saza1d600522019-10-18 11:29:431121 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 10:14:501122 RTC_DCHECK(aecm_render_signal_queue_);
1123 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 11:29:431124 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 10:14:501125 aecm_capture_queue_buffer_);
1126 }
peah701d6282016-10-25 12:42:201127 }
1128
1129 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
saza1d600522019-10-18 11:29:431130 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
peah764e3642016-10-22 12:04:301131 }
ivoc9f4a4a02016-10-28 12:39:161132
1133 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
saza1d600522019-10-18 11:29:431134 RTC_DCHECK(submodules_.echo_detector);
1135 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
ivoc9f4a4a02016-10-28 12:39:161136 }
peah764e3642016-10-22 12:04:301137}
1138
andrew@webrtc.org17e40642014-03-04 20:58:131139int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 14:42:291140 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 20:35:151141 {
1142 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 12:23:111143 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 20:35:151144 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 20:35:151145 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 12:04:301146 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 20:35:151147 }
peahfa6228e2015-11-17 00:27:421148
andrew@webrtc.org17e40642014-03-04 20:58:131149 if (!frame) {
1150 return kNullPointerError;
1151 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:041152 // Must be a native rate.
1153 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1154 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:231155 frame->sample_rate_hz_ != kSampleRate32kHz &&
1156 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:041157 return kBadSampleRateError;
1158 }
peah192164e2015-11-17 10:16:451159
peahdf3efa82015-11-28 20:35:151160 ProcessingConfig processing_config;
peah2ace3f92016-09-10 11:42:271161 bool reinitialization_required = false;
peahdf3efa82015-11-28 20:35:151162 {
1163 // Aquire lock for the access of api_format.
1164 // The lock is released immediately due to the conditional
1165 // reinitialization.
1166 rtc::CritScope cs_capture(&crit_capture_);
1167 // TODO(ajm): The input and output rates and channels are currently
1168 // constrained to be identical in the int16 interface.
1169 processing_config = formats_.api_format;
peah2ace3f92016-09-10 11:42:271170
1171 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 20:35:151172 }
Michael Graczyk86c6d332015-07-23 18:41:391173
Oskar Sundbom4b276482019-05-23 12:28:001174 reinitialization_required =
1175 reinitialization_required ||
1176 processing_config.input_stream().sample_rate_hz() !=
1177 frame->sample_rate_hz_ ||
1178 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1179 processing_config.output_stream().sample_rate_hz() !=
1180 frame->sample_rate_hz_ ||
1181 processing_config.output_stream().num_channels() != frame->num_channels_;
1182
1183 if (reinitialization_required) {
1184 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1185 processing_config.input_stream().set_num_channels(frame->num_channels_);
1186 processing_config.output_stream().set_sample_rate_hz(
1187 frame->sample_rate_hz_);
1188 processing_config.output_stream().set_num_channels(frame->num_channels_);
1189
1190 // Reinitialize.
peahdf3efa82015-11-28 20:35:151191 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 12:28:001192 rtc::CritScope cs_capture(&crit_capture_);
1193 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 20:35:151194 }
Oskar Sundbom4b276482019-05-23 12:28:001195
peahdf3efa82015-11-28 20:35:151196 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 10:16:451197 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 20:35:151198 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:251199 return kBadDataLengthError;
1200 }
1201
aleloi868f32f2017-05-23 14:20:051202 if (aec_dump_) {
1203 RecordUnprocessedCaptureStream(*frame);
1204 }
1205
Per Åhgrend47941e2019-08-22 09:51:131206 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 11:14:441207 if (capture_.capture_fullband_audio) {
1208 capture_.capture_fullband_audio->CopyFrom(frame);
1209 }
peahde65ddc2016-09-16 22:02:151210 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 11:34:361211 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 10:15:461212 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 11:02:141213 if (capture_.capture_fullband_audio) {
1214 capture_.capture_fullband_audio->CopyTo(frame);
1215 } else {
1216 capture_.capture_audio->CopyTo(frame);
1217 }
Per Åhgrena1351272019-08-15 10:15:461218 }
Sam Zackrisson0824c6f2019-10-07 12:03:561219 if (capture_.stats.voice_detected) {
1220 frame->vad_activity_ = *capture_.stats.voice_detected
1221 ? AudioFrame::kVadActive
1222 : AudioFrame::kVadPassive;
1223 }
andrew@webrtc.org17e40642014-03-04 20:58:131224
aleloi868f32f2017-05-23 14:20:051225 if (aec_dump_) {
1226 RecordProcessedCaptureStream(*frame);
1227 }
andrew@webrtc.org17e40642014-03-04 20:58:131228
1229 return kNoError;
1230}
1231
peahde65ddc2016-09-16 22:02:151232int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 08:52:281233 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 10:10:091234
peahb58a1582016-03-15 16:34:241235 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:071236 // TODO(peah): Simplify once the public API Enable functions for these
1237 // are moved to APM.
saza1d600522019-10-18 11:29:431238 RTC_DCHECK_LE(!!submodules_.echo_controller +
1239 !!submodules_.echo_cancellation +
1240 !!submodules_.echo_control_mobile,
Per Åhgrenb6e24d72019-04-29 10:14:501241 1);
peahb58a1582016-03-15 16:34:241242
peahde65ddc2016-09-16 22:02:151243 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 17:35:551244
saza1d600522019-10-18 11:29:431245 if (submodules_.pre_amplifier) {
1246 submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 09:51:131247 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 14:31:221248 capture_buffer->num_frames()));
1249 }
1250
Per Åhgren928146f2019-08-20 07:19:211251 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 09:51:131252 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 16:09:091253 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 21:45:581254 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1255 if (log_rms) {
1256 capture_rms_interval_counter_ = 0;
1257 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 12:28:041258 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1259 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1260 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1261 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 16:09:091262 }
1263
saza1d600522019-10-18 11:29:431264 if (submodules_.echo_controller) {
Per Åhgren88cf0502018-07-16 15:08:411265 // Detect and flag any change in the analog gain.
Per Åhgren0e3198e2019-11-18 07:52:221266 int analog_mic_level = recommended_stream_analog_level();
Per Åhgren88cf0502018-07-16 15:08:411267 capture_.echo_path_gain_change =
1268 capture_.prev_analog_mic_level != analog_mic_level &&
1269 capture_.prev_analog_mic_level != -1;
1270 capture_.prev_analog_mic_level = analog_mic_level;
1271
Per Åhgrend2650d12018-10-02 15:00:591272 // Detect and flag any change in the pre-amplifier gain.
saza1d600522019-10-18 11:29:431273 if (submodules_.pre_amplifier) {
1274 float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor();
Per Åhgrend2650d12018-10-02 15:00:591275 capture_.echo_path_gain_change =
1276 capture_.echo_path_gain_change ||
1277 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 21:10:381278 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 15:00:591279 capture_.prev_pre_amp_gain = pre_amp_gain;
1280 }
Fredrik Hernqvistca362852019-05-10 13:50:021281
1282 // Detect volume change.
1283 capture_.echo_path_gain_change =
1284 capture_.echo_path_gain_change ||
1285 (capture_.prev_playout_volume != capture_.playout_volume &&
1286 capture_.prev_playout_volume >= 0);
1287 capture_.prev_playout_volume = capture_.playout_volume;
1288
saza1d600522019-10-18 11:29:431289 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 09:16:231290 }
1291
Per Åhgren3daedb62019-11-22 11:11:401292 if (constants_.use_experimental_agc &&
1293 submodules_.gain_control->is_enabled()) {
1294 submodules_.agc_manager->AnalyzePreProcess(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:241295 }
1296
peah2ace3f92016-09-10 11:42:271297 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1298 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 22:02:151299 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1300 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:251301 }
1302
Per Åhgrene14cb992019-11-27 08:34:221303 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1304 constants_.multi_channel_capture_support;
1305 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 13:16:261306 // Force down-mixing of the number of channels after the detection of
1307 // capture signal saturation.
1308 // TODO(peah): Look into ensuring that this kind of tampering with the
1309 // AudioBuffer functionality should not be needed.
1310 capture_buffer->set_num_channels(1);
1311 }
1312
saza1d600522019-10-18 11:29:431313 if (submodules_.high_pass_filter) {
1314 submodules_.high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 15:24:521315 }
Per Åhgren0cbb58e2019-10-29 21:59:441316
Per Åhgrene35b32c2019-11-22 17:22:041317 RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
Per Åhgren0cbb58e2019-10-29 21:59:441318 RTC_DCHECK(
1319 !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor));
saza1d600522019-10-18 11:29:431320 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 21:59:441321 submodules_.noise_suppressor->Analyze(*capture_buffer);
1322 } else if (submodules_.legacy_noise_suppressor) {
1323 submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 09:46:111324 }
peahb58a1582016-03-15 16:34:241325
saza1d600522019-10-18 11:29:431326 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 10:14:501327 // Ensure that the stream delay was set before the call to the
1328 // AECM ProcessCaptureAudio function.
1329 if (!was_stream_delay_set()) {
1330 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 07:35:131331 }
1332
saza1d600522019-10-18 11:29:431333 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 21:59:441334 submodules_.noise_suppressor->Process(capture_buffer);
1335 } else if (submodules_.legacy_noise_suppressor) {
saza1d600522019-10-18 11:29:431336 submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer);
Per Åhgren0cbb58e2019-10-29 21:59:441337 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
Per Åhgrenb6e24d72019-04-29 10:14:501338 }
peahe0eae3c2016-12-14 09:16:231339
saza1d600522019-10-18 11:29:431340 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 08:08:101341 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 10:14:501342 } else {
saza1d600522019-10-18 11:29:431343 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 10:14:501344 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1345
1346 if (was_stream_delay_set()) {
saza1d600522019-10-18 11:29:431347 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 10:14:501348 }
1349
Per Åhgrenc20a19c2019-11-13 10:12:291350 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
saza1d600522019-10-18 11:29:431351 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 10:12:291352 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
saza1d600522019-10-18 11:29:431353 } else if (submodules_.echo_cancellation) {
Per Åhgrenb6e24d72019-04-29 10:14:501354 // Ensure that the stream delay was set before the call to the
1355 // AEC ProcessCaptureAudio function.
1356 if (!was_stream_delay_set()) {
1357 return AudioProcessing::kStreamParameterNotSetError;
1358 }
1359
saza1d600522019-10-18 11:29:431360 RETURN_ON_ERR(submodules_.echo_cancellation->ProcessCaptureAudio(
Per Åhgrenb6e24d72019-04-29 10:14:501361 capture_buffer, stream_delay_ms()));
1362 }
1363
saza1d600522019-10-18 11:29:431364 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 21:59:441365 submodules_.noise_suppressor->Process(capture_buffer);
1366 } else if (submodules_.legacy_noise_suppressor) {
1367 submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer);
saza0bad15f2019-10-16 09:46:111368 }
Per Åhgren46537a32017-06-07 08:08:101369 }
ivoc9f4a4a02016-10-28 12:39:161370
Sam Zackrisson4db667b2018-12-21 15:29:271371 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 15:29:271372 capture_.stats.voice_detected =
saza1d600522019-10-18 11:29:431373 submodules_.voice_detector->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 15:29:271374 } else {
1375 capture_.stats.voice_detected = absl::nullopt;
1376 }
pbos@webrtc.org788acd12014-12-15 09:41:241377
Per Åhgren3daedb62019-11-22 11:11:401378 if (constants_.use_experimental_agc &&
1379 submodules_.gain_control->is_enabled()) {
1380 submodules_.agc_manager->Process(capture_buffer);
1381
1382 absl::optional<int> new_digital_gain =
1383 submodules_.agc_manager->GetDigitalComressionGain();
1384 if (new_digital_gain) {
1385 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1386 }
pbos@webrtc.org788acd12014-12-15 09:41:241387 }
Per Åhgren200feba1c2019-03-06 03:16:461388 // TODO(peah): Add reporting from AEC3 whether there is echo.
saza1d600522019-10-18 11:29:431389 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1390 capture_buffer, submodules_.echo_cancellation &&
1391 submodules_.echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:251392
Gustaf Ullberg8675eee2019-10-09 11:34:361393 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 11:42:271394 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 22:02:151395 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1396 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:251397 }
1398
Gustaf Ullberg422b9e02019-10-09 11:02:141399 if (capture_.capture_fullband_audio) {
saza1d600522019-10-18 11:29:431400 const auto& ec = submodules_.echo_controller;
Gustaf Ullberg8675eee2019-10-09 11:34:361401 bool ec_active = ec ? ec->ActiveProcessing() : false;
1402 // Only update the fullband buffer if the multiband processing has changed
1403 // the signal. Keep the original signal otherwise.
1404 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1405 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1406 }
Gustaf Ullberg422b9e02019-10-09 11:02:141407 capture_buffer = capture_.capture_fullband_audio.get();
1408 }
1409
peah9e6a2902017-05-15 14:19:211410 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 11:29:431411 RTC_DCHECK(submodules_.echo_detector);
1412 submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>(
1413 capture_buffer->channels()[0], capture_buffer->num_frames()));
peah9e6a2902017-05-15 14:19:211414 }
1415
pbos@webrtc.org788acd12014-12-15 09:41:241416 // TODO(aluebs): Investigate if the transient suppression placement should be
1417 // before or after the AGC.
peahdf3efa82015-11-28 20:35:151418 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 11:29:431419 float voice_probability = submodules_.agc_manager.get()
1420 ? submodules_.agc_manager->voice_probability()
1421 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:241422
saza1d600522019-10-18 11:29:431423 submodules_.transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 09:51:131424 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 22:02:151425 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 09:51:131426 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 10:15:461427 capture_buffer->num_frames_per_band(),
1428 capture_.keyboard_info.keyboard_data,
1429 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 20:35:151430 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:241431 }
1432
Valeriia Nemychnikovaf06eb572018-08-29 08:37:091433 // Experimental APM sub-module that analyzes |capture_buffer|.
saza1d600522019-10-18 11:29:431434 if (submodules_.capture_analyzer) {
1435 submodules_.capture_analyzer->Analyze(capture_buffer);
Valeriia Nemychnikovaf06eb572018-08-29 08:37:091436 }
1437
Alessio Bazzica270f7b52017-10-13 09:05:171438 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 11:29:431439 submodules_.gain_controller2->NotifyAnalogLevel(
Per Åhgren0e3198e2019-11-18 07:52:221440 recommended_stream_analog_level());
saza1d600522019-10-18 11:29:431441 submodules_.gain_controller2->Process(capture_buffer);
alessiob3ec96df2017-05-22 13:57:061442 }
1443
saza1d600522019-10-18 11:29:431444 if (submodules_.capture_post_processor) {
1445 submodules_.capture_post_processor->Process(capture_buffer);
Sam Zackrisson0beac582017-09-25 10:04:021446 }
1447
andrew@webrtc.org755b04a2011-11-15 16:57:561448 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 15:18:251449 if (config_.level_estimation.enabled) {
saza1d600522019-10-18 11:29:431450 submodules_.output_level_estimator->ProcessStream(*capture_buffer);
1451 capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS();
Sam Zackrissonb24c00f2018-11-26 15:18:251452 } else {
1453 capture_.stats.output_rms_dbfs = absl::nullopt;
1454 }
ajm@google.com808e0e02011-08-03 21:08:511455
Per Åhgren928146f2019-08-20 07:19:211456 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 09:51:131457 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 21:45:581458 capture_nonlocked_.capture_processing_format.num_frames()));
1459 if (log_rms) {
1460 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1461 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1462 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1463 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1464 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1465 }
1466
Per Åhgren0e3198e2019-11-18 07:52:221467 if (submodules_.agc_manager) {
1468 int level = recommended_stream_analog_level();
1469 data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1,
1470 &level);
1471 }
1472
peahdf3efa82015-11-28 20:35:151473 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:251474 return kNoError;
1475}
1476
Gustaf Ullberg8c51f2e2019-10-22 13:21:311477int AudioProcessingImpl::AnalyzeReverseStream(
1478 const float* const* data,
1479 const StreamConfig& reverse_config) {
1480 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
1481 rtc::CritScope cs(&crit_render_);
1482 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1483}
1484
peahde65ddc2016-09-16 22:02:151485int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1486 const StreamConfig& input_config,
1487 const StreamConfig& output_config,
1488 float* const* dest) {
peah369f8282015-12-17 14:42:291489 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 20:35:151490 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 22:02:151491 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 15:02:401492 if (submodule_states_.RenderMultiBandProcessingActive() ||
1493 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 20:35:151494 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1495 dest);
peah2ace3f92016-09-10 11:42:271496 } else if (formats_.api_format.reverse_input_stream() !=
1497 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 22:02:151498 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1499 output_config.num_samples());
ekmeyerson60d9b332015-08-14 17:35:551500 } else {
peahde65ddc2016-09-16 22:02:151501 CopyAudioIfNeeded(src, input_config.num_frames(),
1502 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 17:35:551503 }
1504
1505 return kNoError;
Michael Graczyk86c6d332015-07-23 18:41:391506}
1507
peahdf3efa82015-11-28 20:35:151508int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 17:35:551509 const float* const* src,
peahde65ddc2016-09-16 22:02:151510 const StreamConfig& input_config,
1511 const StreamConfig& output_config) {
peahdf3efa82015-11-28 20:35:151512 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:131513 return kNullPointerError;
1514 }
andrew@webrtc.org17e40642014-03-04 20:58:131515
peahde65ddc2016-09-16 22:02:151516 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 18:41:391517 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:131518 }
1519
peahdf3efa82015-11-28 20:35:151520 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 22:02:151521 processing_config.reverse_input_stream() = input_config;
1522 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 18:41:391523
peahdf3efa82015-11-28 20:35:151524 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 20:44:091525 RTC_DCHECK_EQ(input_config.num_frames(),
1526 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 18:41:391527
aleloi868f32f2017-05-23 14:20:051528 if (aec_dump_) {
1529 const size_t channel_size =
1530 formats_.api_format.reverse_input_stream().num_frames();
1531 const size_t num_channels =
1532 formats_.api_format.reverse_input_stream().num_channels();
1533 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 10:54:071534 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 14:20:051535 }
peahdf3efa82015-11-28 20:35:151536 render_.render_audio->CopyFrom(src,
1537 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 22:02:151538 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 17:35:551539}
1540
1541int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 14:42:291542 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 20:35:151543 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 20:35:151544 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:251545 return kNullPointerError;
1546 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:041547 // Must be a native rate.
1548 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1549 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:231550 frame->sample_rate_hz_ != kSampleRate32kHz &&
1551 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:041552 return kBadSampleRateError;
1553 }
andrew@webrtc.orga8b97372014-03-10 22:26:121554
Michael Graczyk86c6d332015-07-23 18:41:391555 if (frame->num_channels_ <= 0) {
1556 return kBadNumberChannelsError;
1557 }
1558
peahdf3efa82015-11-28 20:35:151559 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 17:35:551560 processing_config.reverse_input_stream().set_sample_rate_hz(
1561 frame->sample_rate_hz_);
1562 processing_config.reverse_input_stream().set_num_channels(
1563 frame->num_channels_);
1564 processing_config.reverse_output_stream().set_sample_rate_hz(
1565 frame->sample_rate_hz_);
1566 processing_config.reverse_output_stream().set_num_channels(
1567 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 18:41:391568
peahdf3efa82015-11-28 20:35:151569 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 18:41:391570 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 20:35:151571 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:131572 return kBadDataLengthError;
1573 }
niklase@google.com470e71d2011-07-07 08:21:251574
aleloi868f32f2017-05-23 14:20:051575 if (aec_dump_) {
1576 aec_dump_->WriteRenderStreamMessage(*frame);
1577 }
1578
Per Åhgrend47941e2019-08-22 09:51:131579 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 22:02:151580 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 10:15:461581 if (submodule_states_.RenderMultiBandProcessingActive() ||
1582 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 09:51:131583 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 10:15:461584 }
aluebsb0319552016-03-18 03:39:531585 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:131586}
niklase@google.com470e71d2011-07-07 08:21:251587
peahde65ddc2016-09-16 22:02:151588int AudioProcessingImpl::ProcessRenderStreamLocked() {
1589 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 14:19:211590
Alex Loiko73ec0192018-05-15 08:52:281591 HandleRenderRuntimeSettings();
1592
saza1d600522019-10-18 11:29:431593 if (submodules_.render_pre_processor) {
1594 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 15:02:401595 }
1596
Alessio Bazzicad2b97402018-08-09 12:23:111597 QueueNonbandedRenderAudio(render_buffer);
1598
peah2ace3f92016-09-10 11:42:271599 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 22:02:151600 SampleRateSupportsMultiBand(
1601 formats_.render_processing_format.sample_rate_hz())) {
1602 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:251603 }
1604
peahce4d9152017-05-19 08:28:051605 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1606 QueueBandedRenderAudio(render_buffer);
1607 }
1608
Alessio Bazzicad2b97402018-08-09 12:23:111609 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 11:29:431610 if (submodules_.echo_controller) {
1611 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 09:16:231612 }
niklase@google.com470e71d2011-07-07 08:21:251613
peah2ace3f92016-09-10 11:42:271614 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 22:02:151615 SampleRateSupportsMultiBand(
1616 formats_.render_processing_format.sample_rate_hz())) {
1617 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 17:35:551618 }
1619
andrew@webrtc.org17e40642014-03-04 20:58:131620 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:251621}
1622
1623int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 20:35:151624 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:061625 Error retval = kNoError;
peahdf3efa82015-11-28 20:35:151626 capture_.was_stream_delay_set = true;
1627 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:391628
niklase@google.com470e71d2011-07-07 08:21:251629 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:061630 delay = 0;
1631 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:251632 }
1633
1634 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1635 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:061636 delay = 500;
1637 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:251638 }
1639
peahdf3efa82015-11-28 20:35:151640 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:061641 return retval;
niklase@google.com470e71d2011-07-07 08:21:251642}
1643
Per Åhgrenc20a19c2019-11-13 10:12:291644bool AudioProcessingImpl::GetLinearAecOutput(
1645 rtc::ArrayView<std::array<float, 160>> linear_output) const {
1646 rtc::CritScope cs(&crit_capture_);
1647 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1648
1649 RTC_DCHECK(linear_aec_buffer);
1650 if (linear_aec_buffer) {
1651 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1652 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1653
1654 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1655 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1656 rtc::ArrayView<const float> channel_view =
1657 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1658 linear_aec_buffer->num_frames());
1659 std::copy(channel_view.begin(), channel_view.end(),
1660 linear_output[ch].begin());
1661 }
1662 return true;
1663 }
1664 RTC_LOG(LS_ERROR) << "No linear AEC output available";
1665 RTC_NOTREACHED();
1666 return false;
1667}
1668
niklase@google.com470e71d2011-07-07 08:21:251669int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 20:35:151670 // Used as callback from submodules, hence locking is not allowed.
1671 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:251672}
1673
1674bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 20:35:151675 // Used as callback from submodules, hence locking is not allowed.
1676 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:251677}
1678
andrew@webrtc.org17e40642014-03-04 20:58:131679void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 20:35:151680 rtc::CritScope cs(&crit_capture_);
1681 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:131682}
1683
andrew@webrtc.org6f9f8172012-03-06 19:03:391684void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 20:35:151685 rtc::CritScope cs(&crit_capture_);
1686 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:391687}
1688
1689int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 20:35:151690 rtc::CritScope cs(&crit_capture_);
1691 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:391692}
1693
Sam Zackrissonf0d1c032019-03-27 12:28:081694void AudioProcessingImpl::set_stream_analog_level(int level) {
1695 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 07:52:221696
1697 if (submodules_.agc_manager) {
1698 submodules_.agc_manager->set_stream_analog_level(level);
1699 data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level",
1700 1, &level);
1701 } else {
1702 int error = submodules_.gain_control->set_stream_analog_level(level);
1703 RTC_DCHECK_EQ(kNoError, error);
1704 }
Sam Zackrissonf0d1c032019-03-27 12:28:081705}
1706
1707int AudioProcessingImpl::recommended_stream_analog_level() const {
1708 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgren0e3198e2019-11-18 07:52:221709 if (submodules_.agc_manager) {
1710 return submodules_.agc_manager->stream_analog_level();
1711 }
1712 return submodules_.gain_control->stream_analog_level();
Sam Zackrissonf0d1c032019-03-27 12:28:081713}
1714
aleloi868f32f2017-05-23 14:20:051715void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1716 RTC_DCHECK(aec_dump);
1717 rtc::CritScope cs_render(&crit_render_);
1718 rtc::CritScope cs_capture(&crit_capture_);
1719
1720 // The previously attached AecDump will be destroyed with the
1721 // 'aec_dump' parameter, which is after locks are released.
1722 aec_dump_.swap(aec_dump);
1723 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 13:38:521724 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 14:20:051725}
1726
1727void AudioProcessingImpl::DetachAecDump() {
1728 // The d-tor of a task-queue based AecDump blocks until all pending
1729 // tasks are done. This construction avoids blocking while holding
1730 // the render and capture locks.
1731 std::unique_ptr<AecDump> aec_dump = nullptr;
1732 {
1733 rtc::CritScope cs_render(&crit_render_);
1734 rtc::CritScope cs_capture(&crit_capture_);
1735 aec_dump = std::move(aec_dump_);
1736 }
1737}
1738
Sam Zackrisson4d364492018-03-02 15:03:211739void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1740 std::unique_ptr<AudioGenerator> audio_generator) {
1741 // TODO(bugs.webrtc.org/8882) Stub.
1742 // Reset internal audio generator with audio_generator.
1743}
1744
1745void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1746 // TODO(bugs.webrtc.org/8882) Stub.
1747 // Delete audio generator, if one is attached.
1748}
1749
Ivo Creusen56d460902017-11-24 16:29:591750AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae0260962017-11-20 12:07:161751 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 15:18:251752 rtc::CritScope cs_capture(&crit_capture_);
1753 if (!has_remote_tracks) {
1754 return capture_.stats;
1755 }
1756 AudioProcessingStats stats = capture_.stats;
1757 EchoCancellationImpl::Metrics metrics;
saza1d600522019-10-18 11:29:431758 if (submodules_.echo_controller) {
1759 auto ec_metrics = submodules_.echo_controller->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 15:18:251760 stats.echo_return_loss = ec_metrics.echo_return_loss;
1761 stats.echo_return_loss_enhancement =
1762 ec_metrics.echo_return_loss_enhancement;
1763 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 15:18:251764 }
1765 if (config_.residual_echo_detector.enabled) {
saza1d600522019-10-18 11:29:431766 RTC_DCHECK(submodules_.echo_detector);
1767 auto ed_metrics = submodules_.echo_detector->GetMetrics();
Sam Zackrissonb24c00f2018-11-26 15:18:251768 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1769 stats.residual_echo_likelihood_recent_max =
1770 ed_metrics.echo_likelihood_recent_max;
1771 }
Ivo Creusenae0260962017-11-20 12:07:161772 return stats;
1773}
1774
peah8271d042016-11-22 15:24:521775void AudioProcessingImpl::MutateConfig(
1776 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1777 rtc::CritScope cs_render(&crit_render_);
1778 rtc::CritScope cs_capture(&crit_capture_);
1779 mutator(&config_);
1780 ApplyConfig(config_);
1781}
1782
1783AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1784 rtc::CritScope cs_render(&crit_render_);
1785 rtc::CritScope cs_capture(&crit_capture_);
1786 return config_;
1787}
1788
peah2ace3f92016-09-10 11:42:271789bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1790 return submodule_states_.Update(
Per Åhgren4011de02019-12-03 11:48:481791 config_.high_pass_filter.enabled, !!submodules_.echo_cancellation,
saza1d600522019-10-18 11:29:431792 !!submodules_.echo_control_mobile, config_.residual_echo_detector.enabled,
Per Åhgren0cbb58e2019-10-29 21:59:441793 !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor,
1794 submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled,
1795 config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 09:46:111796 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 17:35:551797}
1798
Bjorn Volckeradc46c42015-04-15 09:42:401799void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 20:35:151800 if (capture_.transient_suppressor_enabled) {
saza1d600522019-10-18 11:29:431801 if (!submodules_.transient_suppressor.get()) {
1802 submodules_.transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:241803 }
saza1d600522019-10-18 11:29:431804 submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(),
1805 capture_nonlocked_.split_rate,
1806 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:241807 }
pbos@webrtc.org788acd12014-12-15 09:41:241808}
1809
Per Åhgren4011de02019-12-03 11:48:481810void AudioProcessingImpl::InitializeHighPassFilter() {
Per Åhgrenb8106462019-12-04 07:34:121811 bool high_pass_filter_needed_by_aec =
1812 config_.echo_canceller.enabled &&
1813 config_.echo_canceller.enforce_high_pass_filtering &&
1814 !config_.echo_canceller.mobile_mode;
1815 if (submodule_states_.HighPassFilteringRequired() ||
1816 high_pass_filter_needed_by_aec) {
saza1d600522019-10-18 11:29:431817 submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 15:24:521818 } else {
saza1d600522019-10-18 11:29:431819 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 15:24:521820 }
1821}
alessiob3ec96df2017-05-22 13:57:061822
Sam Zackrisson0824c6f2019-10-07 12:03:561823void AudioProcessingImpl::InitializeVoiceDetector() {
1824 if (config_.voice_detection.enabled) {
saza1d600522019-10-18 11:29:431825 submodules_.voice_detector = std::make_unique<VoiceDetection>(
Sam Zackrisson0824c6f2019-10-07 12:03:561826 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1827 } else {
saza1d600522019-10-18 11:29:431828 submodules_.voice_detector.reset();
Sam Zackrisson0824c6f2019-10-07 12:03:561829 }
1830}
Gustaf Ullberg8eb9c7d2017-10-14 06:28:461831void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 10:14:501832 bool use_echo_controller =
1833 echo_control_factory_ ||
Per Åhgren200feba1c2019-03-06 03:16:461834 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 10:14:501835 !config_.echo_canceller.use_legacy_aec);
1836
1837 if (use_echo_controller) {
1838 // Create and activate the echo controller.
Per Åhgren200feba1c2019-03-06 03:16:461839 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 19:44:111840 submodules_.echo_controller = echo_control_factory_->Create(
1841 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 16:15:121842 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba1c2019-03-06 03:16:461843 } else {
Per Åhgrenb2b58d82019-12-02 13:59:401844 EchoCanceller3Config config =
1845 use_setup_specific_default_aec3_config_
1846 ? EchoCanceller3::CreateDefaultConfig(num_reverse_channels(),
1847 num_proc_channels())
1848 : EchoCanceller3Config();
saza1d600522019-10-18 11:29:431849 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Per Åhgrenb2b58d82019-12-02 13:59:401850 config, proc_sample_rate_hz(), num_reverse_channels(),
Sam Zackrissonfeee1e42019-09-20 05:50:351851 num_proc_channels());
Per Åhgren200feba1c2019-03-06 03:16:461852 }
1853
Per Åhgrenc20a19c2019-11-13 10:12:291854 // Setup the storage for returning the linear AEC output.
1855 if (config_.echo_canceller.export_linear_aec_output) {
1856 constexpr int kLinearOutputRateHz = 16000;
1857 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1858 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1859 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1860 } else {
1861 capture_.linear_aec_output.reset();
1862 }
1863
Per Åhgren200feba1c2019-03-06 03:16:461864 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba1c2019-03-06 03:16:461865
saza1d600522019-10-18 11:29:431866 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 13:18:061867 aec_render_signal_queue_.reset();
saza1d600522019-10-18 11:29:431868 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 10:14:501869 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 13:18:061870 return;
peahe0eae3c2016-12-14 09:16:231871 }
Per Åhgrenf204faf2019-04-25 13:18:061872
saza1d600522019-10-18 11:29:431873 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 13:18:061874 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 10:12:291875 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 13:18:061876
1877 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 11:29:431878 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 13:18:061879 aec_render_signal_queue_.reset();
saza1d600522019-10-18 11:29:431880 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 10:14:501881 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 13:18:061882 return;
1883 }
1884
1885 if (config_.echo_canceller.mobile_mode) {
1886 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 10:14:501887 size_t max_element_size =
1888 std::max(static_cast<size_t>(1),
1889 kMaxAllowedValuesOfSamplesPerBand *
1890 EchoControlMobileImpl::NumCancellersRequired(
1891 num_output_channels(), num_reverse_channels()));
1892
1893 std::vector<int16_t> template_queue_element(max_element_size);
1894
1895 aecm_render_signal_queue_.reset(
1896 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1897 kMaxNumFramesToBuffer, template_queue_element,
1898 RenderQueueItemVerifier<int16_t>(max_element_size)));
1899
1900 aecm_render_queue_buffer_.resize(max_element_size);
1901 aecm_capture_queue_buffer_.resize(max_element_size);
1902
saza1d600522019-10-18 11:29:431903 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 10:14:501904
saza1d600522019-10-18 11:29:431905 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1906 num_reverse_channels(),
1907 num_output_channels());
Per Åhgrenb6e24d72019-04-29 10:14:501908
saza1d600522019-10-18 11:29:431909 submodules_.echo_cancellation.reset();
Per Åhgrenf204faf2019-04-25 13:18:061910 aec_render_signal_queue_.reset();
1911 return;
1912 }
1913
saza1d600522019-10-18 11:29:431914 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 10:14:501915 aecm_render_signal_queue_.reset();
1916
Per Åhgrenf204faf2019-04-25 13:18:061917 // Create and activate AEC2.
saza1d600522019-10-18 11:29:431918 submodules_.echo_cancellation.reset(new EchoCancellationImpl());
1919 submodules_.echo_cancellation->SetExtraOptions(
Per Åhgrenf204faf2019-04-25 13:18:061920 capture_nonlocked_.use_aec2_extended_filter,
1921 capture_nonlocked_.use_aec2_delay_agnostic,
1922 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1923
Per Åhgrenb6e24d72019-04-29 10:14:501924 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 13:18:061925 std::max(static_cast<size_t>(1),
1926 kMaxAllowedValuesOfSamplesPerBand *
1927 EchoCancellationImpl::NumCancellersRequired(
1928 num_output_channels(), num_reverse_channels()));
1929
Per Åhgrenb6e24d72019-04-29 10:14:501930 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 13:18:061931
Per Åhgrenb6e24d72019-04-29 10:14:501932 aec_render_signal_queue_.reset(
1933 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1934 kMaxNumFramesToBuffer, template_queue_element,
1935 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 13:18:061936
Per Åhgrenb6e24d72019-04-29 10:14:501937 aec_render_queue_buffer_.resize(element_max_size);
1938 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 13:18:061939
saza1d600522019-10-18 11:29:431940 submodules_.echo_cancellation->Initialize(
Per Åhgrenf204faf2019-04-25 13:18:061941 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1942 num_proc_channels());
1943
saza1d600522019-10-18 11:29:431944 submodules_.echo_cancellation->set_suppression_level(
Per Åhgrenf204faf2019-04-25 13:18:061945 config_.echo_canceller.legacy_moderate_suppression_level
1946 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1947 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 09:16:231948}
peah8271d042016-11-22 15:24:521949
alessiob3ec96df2017-05-22 13:57:061950void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 09:05:171951 if (config_.gain_controller2.enabled) {
saza1d600522019-10-18 11:29:431952 submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 13:57:061953 }
1954}
1955
saza0bad15f2019-10-16 09:46:111956void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 21:59:441957 submodules_.legacy_noise_suppressor.reset();
1958 submodules_.noise_suppressor.reset();
1959
saza0bad15f2019-10-16 09:46:111960 if (config_.noise_suppression.enabled) {
Per Åhgren0cbb58e2019-10-29 21:59:441961 const bool use_legacy_ns =
1962 config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_;
1963
1964 if (!use_legacy_ns) {
1965 auto map_level =
1966 [](AudioProcessing::Config::NoiseSuppression::Level level) {
1967 using NoiseSuppresionConfig =
1968 AudioProcessing::Config::NoiseSuppression;
1969 switch (level) {
1970 case NoiseSuppresionConfig::kLow:
1971 return NsConfig::SuppressionLevel::k6dB;
1972 case NoiseSuppresionConfig::kModerate:
1973 return NsConfig::SuppressionLevel::k12dB;
1974 case NoiseSuppresionConfig::kHigh:
1975 return NsConfig::SuppressionLevel::k18dB;
1976 case NoiseSuppresionConfig::kVeryHigh:
1977 return NsConfig::SuppressionLevel::k21dB;
1978 default:
1979 RTC_NOTREACHED();
1980 }
1981 };
1982
1983 NsConfig cfg;
1984 cfg.target_level = map_level(config_.noise_suppression.level);
1985 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
1986 cfg, proc_sample_rate_hz(), num_proc_channels());
1987 } else {
1988 auto ns_level =
1989 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1990 submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>(
1991 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1992 }
saza0bad15f2019-10-16 09:46:111993 }
1994}
1995
Alex Loikob5c9a792018-04-16 14:31:221996void AudioProcessingImpl::InitializePreAmplifier() {
1997 if (config_.pre_amplifier.enabled) {
saza1d600522019-10-18 11:29:431998 submodules_.pre_amplifier.reset(
Alex Loikob5c9a792018-04-16 14:31:221999 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
2000 } else {
saza1d600522019-10-18 11:29:432001 submodules_.pre_amplifier.reset();
Alex Loikob5c9a792018-04-16 14:31:222002 }
2003}
2004
ivoc9f4a4a02016-10-28 12:39:162005void AudioProcessingImpl::InitializeResidualEchoDetector() {
saza1d600522019-10-18 11:29:432006 RTC_DCHECK(submodules_.echo_detector);
2007 submodules_.echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 11:02:142008 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 14:15:582009 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 12:39:162010}
2011
Valeriia Nemychnikovaf06eb572018-08-29 08:37:092012void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 11:29:432013 if (submodules_.capture_analyzer) {
2014 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2015 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 08:37:092016 }
2017}
2018
Sam Zackrisson0beac582017-09-25 10:04:022019void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 11:29:432020 if (submodules_.capture_post_processor) {
2021 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 11:02:142022 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 10:04:022023 }
2024}
2025
Alex Loiko5825aa62017-12-18 15:02:402026void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 11:29:432027 if (submodules_.render_pre_processor) {
2028 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 15:02:402029 formats_.render_processing_format.sample_rate_hz(),
2030 formats_.render_processing_format.num_channels());
2031 }
2032}
2033
Per Åhgrenea4c5df2019-05-03 07:00:082034void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 09:50:052035
aleloi868f32f2017-05-23 14:20:052036void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2037 if (!aec_dump_) {
2038 return;
2039 }
Per Åhgrenf204faf2019-04-25 13:18:062040
2041 std::string experiments_description = "";
saza1d600522019-10-18 11:29:432042 if (submodules_.echo_cancellation) {
Per Åhgrenf204faf2019-04-25 13:18:062043 experiments_description +=
saza1d600522019-10-18 11:29:432044 submodules_.echo_cancellation->GetExperimentsDescription();
Per Åhgrenf204faf2019-04-25 13:18:062045 }
aleloi868f32f2017-05-23 14:20:052046 // TODO(peah): Add semicolon-separated concatenations of experiment
2047 // descriptions for other submodules.
aleloi868f32f2017-05-23 14:20:052048 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2049 experiments_description += "AgcClippingLevelExperiment;";
2050 }
Gustaf Ullbergce045ac2017-10-16 11:49:042051 if (capture_nonlocked_.echo_controller_enabled) {
2052 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 14:20:052053 }
Alessio Bazzica270f7b52017-10-13 09:05:172054 if (config_.gain_controller2.enabled) {
2055 experiments_description += "GainController2;";
2056 }
aleloi868f32f2017-05-23 14:20:052057
2058 InternalAPMConfig apm_config;
2059
Per Åhgren200feba1c2019-03-06 03:16:462060 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 14:20:052061 apm_config.aec_delay_agnostic_enabled =
saza1d600522019-10-18 11:29:432062 submodules_.echo_cancellation &&
2063 submodules_.echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 14:20:052064 apm_config.aec_drift_compensation_enabled =
saza1d600522019-10-18 11:29:432065 submodules_.echo_cancellation &&
2066 submodules_.echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 14:20:052067 apm_config.aec_extended_filter_enabled =
saza1d600522019-10-18 11:29:432068 submodules_.echo_cancellation &&
2069 submodules_.echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 13:18:062070 apm_config.aec_suppression_level =
saza1d600522019-10-18 11:29:432071 submodules_.echo_cancellation
2072 ? static_cast<int>(submodules_.echo_cancellation->suppression_level())
Per Åhgrenf204faf2019-04-25 13:18:062073 : 0;
aleloi868f32f2017-05-23 14:20:052074
saza1d600522019-10-18 11:29:432075 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 14:20:052076 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 11:29:432077 submodules_.echo_control_mobile &&
2078 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 10:14:502079 apm_config.aecm_routing_mode =
saza1d600522019-10-18 11:29:432080 submodules_.echo_control_mobile
2081 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 10:14:502082 : 0;
aleloi868f32f2017-05-23 14:20:052083
saza1d600522019-10-18 11:29:432084 apm_config.agc_enabled = submodules_.gain_control->is_enabled();
2085 apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode());
aleloi868f32f2017-05-23 14:20:052086 apm_config.agc_limiter_enabled =
saza1d600522019-10-18 11:29:432087 submodules_.gain_control->is_limiter_enabled();
Per Åhgren0e3198e2019-11-18 07:52:222088 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 14:20:052089
2090 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2091
saza0bad15f2019-10-16 09:46:112092 apm_config.ns_enabled = config_.noise_suppression.enabled;
2093 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 14:20:052094
2095 apm_config.transient_suppression_enabled =
2096 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 14:20:052097 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 11:52:322098 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2099 apm_config.pre_amplifier_fixed_gain_factor =
2100 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 14:20:052101
2102 if (!forced && apm_config == apm_config_for_aec_dump_) {
2103 return;
2104 }
2105 aec_dump_->WriteConfig(apm_config);
2106 apm_config_for_aec_dump_ = apm_config;
2107}
2108
2109void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2110 const float* const* src) {
2111 RTC_DCHECK(aec_dump_);
2112 WriteAecDumpConfigMessage(false);
2113
2114 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2115 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2116 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 10:54:072117 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 14:20:052118 RecordAudioProcessingState();
2119}
2120
2121void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2122 const AudioFrame& capture_frame) {
2123 RTC_DCHECK(aec_dump_);
2124 WriteAecDumpConfigMessage(false);
2125
2126 aec_dump_->AddCaptureStreamInput(capture_frame);
2127 RecordAudioProcessingState();
2128}
2129
2130void AudioProcessingImpl::RecordProcessedCaptureStream(
2131 const float* const* processed_capture_stream) {
2132 RTC_DCHECK(aec_dump_);
2133
2134 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2135 const size_t num_channels =
2136 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 10:54:072137 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2138 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 14:20:052139 aec_dump_->WriteCaptureStreamMessage();
2140}
2141
2142void AudioProcessingImpl::RecordProcessedCaptureStream(
2143 const AudioFrame& processed_capture_frame) {
2144 RTC_DCHECK(aec_dump_);
2145
2146 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2147 aec_dump_->WriteCaptureStreamMessage();
2148}
2149
2150void AudioProcessingImpl::RecordAudioProcessingState() {
2151 RTC_DCHECK(aec_dump_);
2152 AecDump::AudioProcessingState audio_proc_state;
2153 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2154 audio_proc_state.drift =
saza1d600522019-10-18 11:29:432155 submodules_.echo_cancellation
2156 ? submodules_.echo_cancellation->stream_drift_samples()
Per Åhgrenf204faf2019-04-25 13:18:062157 : 0;
Per Åhgren0e3198e2019-11-18 07:52:222158 audio_proc_state.level = recommended_stream_analog_level();
aleloi868f32f2017-05-23 14:20:052159 audio_proc_state.keypress = capture_.key_pressed;
2160 aec_dump_->AddAudioProcessingState(audio_proc_state);
2161}
2162
kwiberg83ffe452016-08-29 21:46:072163AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 08:11:352164 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 07:00:082165 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 21:46:072166 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 21:46:072167 output_will_be_muted(false),
2168 key_pressed(false),
2169 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 22:02:152170 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 21:12:412171 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 15:08:412172 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 15:00:592173 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 13:50:022174 prev_pre_amp_gain(-1.f),
2175 playout_volume(-1),
2176 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 21:46:072177
2178AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2179
Per Åhgrena1351272019-08-15 10:15:462180void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2181 const float* const* data,
2182 const StreamConfig& stream_config) {
2183 if (stream_config.has_keyboard()) {
2184 keyboard_data = data[stream_config.num_channels()];
2185 } else {
2186 keyboard_data = NULL;
2187 }
2188 num_keyboard_frames = stream_config.num_frames();
2189}
2190
kwiberg83ffe452016-08-29 21:46:072191AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2192
2193AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2194
niklase@google.com470e71d2011-07-07 08:21:252195} // namespace webrtc