blob: f34e9c5bb3c94e558a568f859b38b9e3054102a6 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
25#include "modules/audio_processing/beamformer/nonlinear_beamformer.h"
26#include "modules/audio_processing/common.h"
27#include "modules/audio_processing/echo_cancellation_impl.h"
28#include "modules/audio_processing/echo_control_mobile_impl.h"
29#include "modules/audio_processing/gain_control_for_experimental_agc.h"
30#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010031#include "modules/audio_processing/gain_controller2.h"
Per Åhgren13735822018-02-12 21:42:56 +010032#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/checks.h"
34#include "rtc_base/logging.h"
35#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020036#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070038#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070040#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "modules/audio_processing/level_estimator_impl.h"
42#include "modules/audio_processing/low_cut_filter.h"
43#include "modules/audio_processing/noise_suppression_impl.h"
44#include "modules/audio_processing/residual_echo_detector.h"
45#include "modules/audio_processing/transient/transient_suppressor.h"
46#include "modules/audio_processing/voice_detection_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010047#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000049
peah1bcfce52016-08-26 07:16:04 -070050// Check to verify that the define for the intelligibility enhancer is properly
51// set.
52#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
53 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
54 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
55#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
56#endif
57
Michael Graczyk86c6d332015-07-23 11:41:39 -070058#define RETURN_ON_ERR(expr) \
59 do { \
60 int err = (expr); \
61 if (err != kNoError) { \
62 return err; \
63 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000064 } while (0)
65
niklase@google.com470e71d2011-07-07 08:21:25 +000066namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070067
kwibergd59d3bb2016-09-13 07:49:33 -070068constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020069constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070070
Michael Graczyk86c6d332015-07-23 11:41:39 -070071namespace {
72
73static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
74 switch (layout) {
75 case AudioProcessing::kMono:
76 case AudioProcessing::kStereo:
77 return false;
78 case AudioProcessing::kMonoAndKeyboard:
79 case AudioProcessing::kStereoAndKeyboard:
80 return true;
81 }
82
kwiberg9e2be5f2016-09-14 05:23:22 -070083 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070084 return false;
85}
aluebsdf6416a2016-03-16 18:26:35 -070086
peah2ace3f92016-09-10 04:42:27 -070087bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070088 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
89 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
90}
91
peah2ace3f92016-09-10 04:42:27 -070092int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
93#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070094 constexpr int kMaxSplittingNativeProcessRate =
95 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070096#else
kwibergd59d3bb2016-09-13 07:49:33 -070097 constexpr int kMaxSplittingNativeProcessRate =
98 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070099#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700100 static_assert(
101 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
102 "");
peah2ace3f92016-09-10 04:42:27 -0700103 const int uppermost_native_rate = band_splitting_required
104 ? kMaxSplittingNativeProcessRate
105 : AudioProcessing::kSampleRate48kHz;
106
107 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
108 if (rate >= uppermost_native_rate) {
109 return uppermost_native_rate;
110 }
111 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700112 return rate;
113 }
114 }
peah2ace3f92016-09-10 04:42:27 -0700115 RTC_NOTREACHED();
116 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700117}
118
peah9e6a2902017-05-15 07:19:21 -0700119// Maximum lengths that frame of samples being passed from the render side to
120// the capture side can have (does not apply to AEC3).
121static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
122static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum number of frames to buffer in the render queue.
125// TODO(peah): Decrease this once we properly handle hugely unbalanced
126// reverse and forward call numbers.
127static const size_t kMaxNumFramesToBuffer = 100;
128
peah8271d042016-11-22 07:24:52 -0800129class HighPassFilterImpl : public HighPassFilter {
130 public:
131 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
132 ~HighPassFilterImpl() override = default;
133
134 // HighPassFilter implementation.
135 int Enable(bool enable) override {
136 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
137 config->high_pass_filter.enabled = enable;
138 });
139
140 return AudioProcessing::kNoError;
141 }
142
143 bool is_enabled() const override {
144 return apm_->GetConfig().high_pass_filter.enabled;
145 }
146
147 private:
148 AudioProcessingImpl* apm_;
149 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
150};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700151} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000152
153// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000154static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000155
Sam Zackrisson0beac582017-09-25 12:04:02 +0200156AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100157 bool capture_post_processor_enabled,
158 bool render_pre_processor_enabled)
159 : capture_post_processor_enabled_(capture_post_processor_enabled),
160 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700161
162bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800163 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700164 bool echo_canceller_enabled,
165 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700166 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700167 bool noise_suppressor_enabled,
168 bool intelligibility_enhancer_enabled,
peah2ace3f92016-09-10 04:42:27 -0700169 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700170 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200171 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200172 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700173 bool voice_activity_detector_enabled,
174 bool level_estimator_enabled,
175 bool transient_suppressor_enabled) {
176 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800177 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700178 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
179 changed |=
180 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700181 changed |=
182 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700183 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
184 changed |=
185 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700186 changed |=
187 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700188 changed |=
189 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200190 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200191 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700192 changed |= (level_estimator_enabled != level_estimator_enabled_);
193 changed |=
194 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
195 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
196 if (changed) {
peah8271d042016-11-22 07:24:52 -0800197 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700198 echo_canceller_enabled_ = echo_canceller_enabled;
199 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700200 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700201 noise_suppressor_enabled_ = noise_suppressor_enabled;
202 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
peah2ace3f92016-09-10 04:42:27 -0700203 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700204 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200205 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200206 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700207 level_estimator_enabled_ = level_estimator_enabled;
208 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
209 transient_suppressor_enabled_ = transient_suppressor_enabled;
210 }
211
212 changed |= first_update_;
213 first_update_ = false;
214 return changed;
215}
216
217bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
218 const {
219#if WEBRTC_INTELLIGIBILITY_ENHANCER
220 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700221 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700222#else
peah52775842017-05-16 06:14:09 -0700223 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700224#endif
225}
226
227bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
228 const {
peah8271d042016-11-22 07:24:52 -0800229 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700230 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200231 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700232}
233
peah23ac8b42017-05-23 05:33:56 -0700234bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
235 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200236 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
237 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700238}
239
peah2ace3f92016-09-10 04:42:27 -0700240bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
241 const {
242 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800243 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200244 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700245}
246
Alex Loiko5825aa62017-12-18 16:02:40 +0100247bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
248 const {
249 return render_pre_processor_enabled_;
250}
251
peah2ace3f92016-09-10 04:42:27 -0700252bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
253 const {
254#if WEBRTC_INTELLIGIBILITY_ENHANCER
255 return intelligibility_enhancer_enabled_;
256#else
257 return false;
258#endif
259}
260
solenberg5e465c32015-12-08 13:22:33 -0800261struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800262 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800263 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800264 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800265 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800266 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800267 std::unique_ptr<LevelEstimatorImpl> level_estimator;
268 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
269 std::unique_ptr<VoiceDetectionImpl> voice_detection;
270 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800271 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800272
273 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800274 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700275#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800276 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700277#endif
solenberg5e465c32015-12-08 13:22:33 -0800278};
279
280struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200281 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100282 std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100283 std::unique_ptr<CustomProcessing> render_pre_processor,
Ivo Creusend1f970d2018-06-14 11:02:03 +0200284 rtc::scoped_refptr<EchoDetector> echo_detector)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200285 : beamformer(beamformer),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100286 echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100287 capture_post_processor(std::move(capture_post_processor)),
288 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800289 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700290 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800291 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700292 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800293 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200294 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200295 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100296 std::unique_ptr<CustomProcessing> capture_post_processor;
297 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200298 std::unique_ptr<GainApplier> pre_amplifier;
solenberg5e465c32015-12-08 13:22:33 -0800299};
300
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100301AudioProcessingBuilder::AudioProcessingBuilder() = default;
302AudioProcessingBuilder::~AudioProcessingBuilder() = default;
303
304AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
305 std::unique_ptr<CustomProcessing> capture_post_processing) {
306 capture_post_processing_ = std::move(capture_post_processing);
307 return *this;
308}
309
310AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
311 std::unique_ptr<CustomProcessing> render_pre_processing) {
312 render_pre_processing_ = std::move(render_pre_processing);
313 return *this;
314}
315
316AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
317 std::unique_ptr<EchoControlFactory> echo_control_factory) {
318 echo_control_factory_ = std::move(echo_control_factory);
319 return *this;
320}
321
322AudioProcessingBuilder& AudioProcessingBuilder::SetNonlinearBeamformer(
323 std::unique_ptr<NonlinearBeamformer> nonlinear_beamformer) {
324 nonlinear_beamformer_ = std::move(nonlinear_beamformer);
325 return *this;
326}
327
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100328AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200329 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100330 echo_detector_ = std::move(echo_detector);
331 return *this;
332}
333
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100334AudioProcessing* AudioProcessingBuilder::Create() {
335 webrtc::Config config;
336 return Create(config);
337}
338
339AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100340 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
341 config, std::move(capture_post_processing_),
342 std::move(render_pre_processing_), std::move(echo_control_factory_),
343 std::move(echo_detector_), nonlinear_beamformer_.release());
344 if (apm->Initialize() != AudioProcessing::kNoError) {
345 delete apm;
346 apm = nullptr;
347 }
348 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100349}
350
peah88ac8532016-09-12 16:47:25 -0700351AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100352 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
353}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000354
Per Åhgren13735822018-02-12 21:42:56 +0100355int AudioProcessingImpl::instance_count_ = 0;
356
Sam Zackrisson0beac582017-09-25 12:04:02 +0200357AudioProcessingImpl::AudioProcessingImpl(
358 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100359 std::unique_ptr<CustomProcessing> capture_post_processor,
360 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200361 std::unique_ptr<EchoControlFactory> echo_control_factory,
Ivo Creusend1f970d2018-06-14 11:02:03 +0200362 rtc::scoped_refptr<EchoDetector> echo_detector,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200363 NonlinearBeamformer* beamformer)
Per Åhgren13735822018-02-12 21:42:56 +0100364 : data_dumper_(
365 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200366 capture_runtime_settings_(kRuntimeSettingQueueSize),
367 render_runtime_settings_(kRuntimeSettingQueueSize),
368 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
369 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100370 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200371 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100372 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800373 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200374 private_submodules_(
375 new ApmPrivateSubmodules(beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100376 std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100377 std::move(render_pre_processor),
378 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800379 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800380 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000381#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700382 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000383#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700384 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000385#endif
andrew1c7075f2015-06-24 18:14:14 -0700386#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200387 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700388#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200389 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700390#endif
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200391 capture_nonlocked_(config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800392 {
393 rtc::CritScope cs_render(&crit_render_);
394 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000395
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200396 // Mark Echo Controller enabled if a factory is injected.
397 capture_nonlocked_.echo_controller_enabled =
398 static_cast<bool>(echo_control_factory_);
399
peahb624d8c2016-03-05 03:01:14 -0800400 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700401 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800402 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700403 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800404 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200405 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800406 public_submodules_->level_estimator.reset(
407 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800408 public_submodules_->noise_suppression.reset(
409 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800410 public_submodules_->voice_detection.reset(
411 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800412 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800413 new GainControlForExperimentalAgc(
414 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100415
416 // If no echo detector is injected, use the ResidualEchoDetector.
417 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200418 private_submodules_->echo_detector =
419 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100420 }
peahca4cac72016-06-29 15:26:12 -0700421
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200422 // TODO(alessiob): Move the injected gain controller once injection is
423 // implemented.
424 private_submodules_->gain_controller2.reset(new GainController2());
425
Mirko Bonadei675513b2017-11-09 11:09:25 +0100426 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100427 << !!private_submodules_->capture_post_processor
428 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100429 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800430 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000431
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000432 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000433}
434
435AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800436 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800437 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800438 private_submodules_->agc_manager.reset();
439 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800440 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000441}
442
niklase@google.com470e71d2011-07-07 08:21:25 +0000443int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800444 // Run in a single-threaded manner during initialization.
445 rtc::CritScope cs_render(&crit_render_);
446 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000447 return InitializeLocked();
448}
449
peahde65ddc2016-09-16 15:02:15 -0700450int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
451 int capture_output_sample_rate_hz,
452 int render_input_sample_rate_hz,
453 ChannelLayout capture_input_layout,
454 ChannelLayout capture_output_layout,
455 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700456 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700457 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
458 LayoutHasKeyboard(capture_input_layout)},
459 {capture_output_sample_rate_hz,
460 ChannelsFromLayout(capture_output_layout),
461 LayoutHasKeyboard(capture_output_layout)},
462 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
463 LayoutHasKeyboard(render_input_layout)},
464 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
465 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700466
467 return Initialize(processing_config);
468}
469
470int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800471 // Run in a single-threaded manner during initialization.
472 rtc::CritScope cs_render(&crit_render_);
473 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700474 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000475}
476
peahdf3efa82015-11-28 12:35:15 -0800477int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800478 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700479 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800480}
481
peahdf3efa82015-11-28 12:35:15 -0800482int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700483 const ProcessingConfig& processing_config,
484 bool force_initialization) {
485 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800486}
487
peah192164e2015-11-17 02:16:45 -0800488// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800489// their current values (needs to be called while holding the crit_render_lock).
490int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700491 const ProcessingConfig& processing_config,
492 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800493 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700494 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800495 return kNoError;
496 }
peahdf3efa82015-11-28 12:35:15 -0800497
498 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800499 return InitializeLocked(processing_config);
500}
501
niklase@google.com470e71d2011-07-07 08:21:25 +0000502int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200503 UpdateActiveSubmoduleStates();
504
peahde65ddc2016-09-16 15:02:15 -0700505 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800506 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700507 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800508 : formats_.api_format.reverse_output_stream().num_frames();
509 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
510 render_.render_audio.reset(new AudioBuffer(
511 formats_.api_format.reverse_input_stream().num_frames(),
512 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700513 formats_.render_processing_format.num_frames(),
514 formats_.render_processing_format.num_channels(),
515 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700516 if (formats_.api_format.reverse_input_stream() !=
517 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800518 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800519 formats_.api_format.reverse_input_stream().num_channels(),
520 formats_.api_format.reverse_input_stream().num_frames(),
521 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800522 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700523 } else {
peahdf3efa82015-11-28 12:35:15 -0800524 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700525 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700526 } else {
peahdf3efa82015-11-28 12:35:15 -0800527 render_.render_audio.reset(nullptr);
528 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700529 }
peahce4d9152017-05-19 01:28:05 -0700530
peahdf3efa82015-11-28 12:35:15 -0800531 capture_.capture_audio.reset(
532 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
533 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700534 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200535 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800536 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000537
peahde65ddc2016-09-16 15:02:15 -0700538 public_submodules_->echo_cancellation->Initialize(
539 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
540 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700541 AllocateRenderQueue();
542
ivoc3e9a5372016-10-28 07:55:33 -0700543 int success = public_submodules_->echo_cancellation->enable_metrics(true);
544 RTC_DCHECK_EQ(0, success);
545 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
546 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700547 public_submodules_->echo_control_mobile->Initialize(
548 proc_split_sample_rate_hz(), num_reverse_channels(),
549 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700550
551 public_submodules_->gain_control->Initialize(num_proc_channels(),
552 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700553 if (constants_.use_experimental_agc) {
554 if (!private_submodules_->agc_manager.get()) {
555 private_submodules_->agc_manager.reset(new AgcManagerDirect(
556 public_submodules_->gain_control.get(),
557 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800558 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700559 }
560 private_submodules_->agc_manager->Initialize();
561 private_submodules_->agc_manager->SetCaptureMuted(
562 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700563 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700564 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200565 InitializeTransient();
peah1bcfce52016-08-26 07:16:04 -0700566#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700567 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700568#endif
peah8271d042016-11-22 07:24:52 -0800569 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700570 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
571 proc_sample_rate_hz());
572 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
573 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700574 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200575 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700576 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200577 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100578 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800579
aleloi868f32f2017-05-23 07:20:05 -0700580 if (aec_dump_) {
Alex Loiko1aec5942018-05-15 13:13:22 +0200581 aec_dump_->WriteInitMessage(formats_.api_format);
aleloi868f32f2017-05-23 07:20:05 -0700582 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000583 return kNoError;
584}
585
Michael Graczyk86c6d332015-07-23 11:41:39 -0700586int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200587 UpdateActiveSubmoduleStates();
588
Michael Graczyk86c6d332015-07-23 11:41:39 -0700589 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
591 return kBadSampleRateError;
592 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000593 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700594
Peter Kasting69558702016-01-12 16:26:35 -0800595 const size_t num_in_channels = config.input_stream().num_channels();
596 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700597
598 // Need at least one input channel.
599 // Need either one output channel or as many outputs as there are inputs.
600 if (num_in_channels == 0 ||
601 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700602 return kBadNumberChannelsError;
603 }
604
peahdf3efa82015-11-28 12:35:15 -0800605 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000606
peahde65ddc2016-09-16 15:02:15 -0700607 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700608 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700609 formats_.api_format.output_stream().sample_rate_hz()),
610 submodule_states_.CaptureMultiBandSubModulesActive() ||
611 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000612
peahde65ddc2016-09-16 15:02:15 -0700613 capture_nonlocked_.capture_processing_format =
614 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700615
peah2ce640f2017-04-07 03:57:48 -0700616 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200617 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700618 render_processing_rate = FindNativeProcessRateToUse(
619 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
620 formats_.api_format.reverse_output_stream().sample_rate_hz()),
621 submodule_states_.CaptureMultiBandSubModulesActive() ||
622 submodule_states_.RenderMultiBandSubModulesActive());
623 } else {
624 render_processing_rate = capture_processing_rate;
625 }
626
aluebseb3603b2016-04-20 15:27:58 -0700627 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
628 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700629 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200630 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700631 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
632 ? kSampleRate32kHz
633 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700634 }
peah2ce640f2017-04-07 03:57:48 -0700635
peahde65ddc2016-09-16 15:02:15 -0700636 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700637 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700638 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
639 kSampleRate8kHz) {
640 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000641 } else {
peahde65ddc2016-09-16 15:02:15 -0700642 render_processing_rate =
643 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000644 }
645
peahde65ddc2016-09-16 15:02:15 -0700646 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000647 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700648 if (submodule_states_.RenderMultiBandSubModulesActive()) {
649 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
650 } else {
651 formats_.render_processing_format = StreamConfig(
652 formats_.api_format.reverse_input_stream().sample_rate_hz(),
653 formats_.api_format.reverse_input_stream().num_channels());
654 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000655
peahde65ddc2016-09-16 15:02:15 -0700656 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
657 kSampleRate32kHz ||
658 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
659 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800660 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000661 } else {
peahdf3efa82015-11-28 12:35:15 -0800662 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700663 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000664 }
665
666 return InitializeLocked();
667}
668
peah88ac8532016-09-12 16:47:25 -0700669void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700670 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700671
peah88ac8532016-09-12 16:47:25 -0700672 // Run in a single-threaded manner when applying the settings.
673 rtc::CritScope cs_render(&crit_render_);
674 rtc::CritScope cs_capture(&crit_capture_);
675
peah8271d042016-11-22 07:24:52 -0800676 InitializeLowCutFilter();
677
Mirko Bonadei675513b2017-11-09 11:09:25 +0100678 RTC_LOG(LS_INFO) << "Highpass filter activated: "
679 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800680
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100681 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700682 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100683 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
684 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100685 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100686 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700687 config_.gain_controller2 = AudioProcessing::Config::GainController2();
688 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200689 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200690 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200691 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100692 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
693 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200694 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
695 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700696}
697
698void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800699 // Run in a single-threaded manner when setting the extra options.
700 rtc::CritScope cs_render(&crit_render_);
701 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000702
peahb624d8c2016-03-05 03:01:14 -0800703 public_submodules_->echo_cancellation->SetExtraOptions(config);
704
peahdf3efa82015-11-28 12:35:15 -0800705 if (capture_.transient_suppressor_enabled !=
706 config.Get<ExperimentalNs>().enabled) {
707 capture_.transient_suppressor_enabled =
708 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000709 InitializeTransient();
710 }
aluebs2a346882016-01-11 18:04:30 -0800711
peah1bcfce52016-08-26 07:16:04 -0700712#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700713 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700714 config.Get<Intelligibility>().enabled) {
715 capture_nonlocked_.intelligibility_enabled =
716 config.Get<Intelligibility>().enabled;
717 InitializeIntelligibility();
718 }
peah1bcfce52016-08-26 07:16:04 -0700719#endif
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000720}
721
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000722int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800723 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700724 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000727int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800728 // Used as callback from submodules, hence locking is not allowed.
729 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000730}
731
Peter Kasting69558702016-01-12 16:26:35 -0800732size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800733 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700734 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000735}
736
Peter Kasting69558702016-01-12 16:26:35 -0800737size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800738 // Used as callback from submodules, hence locking is not allowed.
739 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000740}
741
Peter Kasting69558702016-01-12 16:26:35 -0800742size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800743 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200744 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800745}
746
Peter Kasting69558702016-01-12 16:26:35 -0800747size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800748 // Used as callback from submodules, hence locking is not allowed.
749 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000750}
751
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000752void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800753 rtc::CritScope cs(&crit_capture_);
754 capture_.output_will_be_muted = muted;
755 if (private_submodules_->agc_manager.get()) {
756 private_submodules_->agc_manager->SetCaptureMuted(
757 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000758 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000759}
760
Alessio Bazzicac054e782018-04-16 12:10:09 +0200761void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200762 switch (setting.type()) {
763 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
764 render_runtime_settings_enqueuer_.Enqueue(setting);
765 return;
766 case RuntimeSetting::Type::kNotSpecified:
767 RTC_NOTREACHED();
768 return;
769 case RuntimeSetting::Type::kCapturePreGain:
770 capture_runtime_settings_enqueuer_.Enqueue(setting);
771 return;
772 }
773 // The language allows the enum to have a non-enumerator
774 // value. Check that this doesn't happen.
775 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200776}
777
778AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
779 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200780 : runtime_settings_(*runtime_settings) {
781 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200782}
783
784AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
785 default;
786
787void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
788 RuntimeSetting setting) {
789 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200790 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200791 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200792 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200793 RTC_LOG(LS_ERROR)
794 << "The runtime settings queue is full. Oldest setting discarded.";
795 }
796 if (remaining_attempts == 0)
797 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
798}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000799
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000800int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700801 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000802 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000803 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000804 int output_sample_rate_hz,
805 ChannelLayout output_layout,
806 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800807 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800808 StreamConfig input_stream;
809 StreamConfig output_stream;
810 {
811 // Access the formats_.api_format.input_stream beneath the capture lock.
812 // The lock must be released as it is later required in the call
813 // to ProcessStream(,,,);
814 rtc::CritScope cs(&crit_capture_);
815 input_stream = formats_.api_format.input_stream();
816 output_stream = formats_.api_format.output_stream();
817 }
818
Michael Graczyk86c6d332015-07-23 11:41:39 -0700819 input_stream.set_sample_rate_hz(input_sample_rate_hz);
820 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
821 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700822 output_stream.set_sample_rate_hz(output_sample_rate_hz);
823 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
824 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
825
826 if (samples_per_channel != input_stream.num_frames()) {
827 return kBadDataLengthError;
828 }
829 return ProcessStream(src, input_stream, output_stream, dest);
830}
831
832int AudioProcessingImpl::ProcessStream(const float* const* src,
833 const StreamConfig& input_config,
834 const StreamConfig& output_config,
835 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800836 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800837 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700838 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800839 {
840 // Acquire the capture lock in order to safely call the function
841 // that retrieves the render side data. This function accesses apm
842 // getters that need the capture lock held when being called.
843 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700844 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800845
846 if (!src || !dest) {
847 return kNullPointerError;
848 }
849
850 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700851 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000852 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000853
Michael Graczyk86c6d332015-07-23 11:41:39 -0700854 processing_config.input_stream() = input_config;
855 processing_config.output_stream() = output_config;
856
peahdf3efa82015-11-28 12:35:15 -0800857 {
858 // Do conditional reinitialization.
859 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700860 RETURN_ON_ERR(
861 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800862 }
863 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700864 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
865 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000866
aleloi868f32f2017-05-23 07:20:05 -0700867 if (aec_dump_) {
868 RecordUnprocessedCaptureStream(src);
869 }
870
peahdf3efa82015-11-28 12:35:15 -0800871 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700872 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800873 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000874
aleloi868f32f2017-05-23 07:20:05 -0700875 if (aec_dump_) {
876 RecordProcessedCaptureStream(dest);
877 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000878 return kNoError;
879}
880
Alex Loiko73ec0192018-05-15 10:52:28 +0200881void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200882 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200883 while (capture_runtime_settings_.Remove(&setting)) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200884 switch (setting.type()) {
885 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200886 if (config_.pre_amplifier.enabled) {
887 float value;
888 setting.GetFloat(&value);
889 private_submodules_->pre_amplifier->SetGainFactor(value);
890 }
891 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200892 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200893 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
894 RTC_NOTREACHED();
895 break;
896 case RuntimeSetting::Type::kNotSpecified:
897 RTC_NOTREACHED();
898 break;
899 }
900 }
901}
902
903void AudioProcessingImpl::HandleRenderRuntimeSettings() {
904 RuntimeSetting setting;
905 while (render_runtime_settings_.Remove(&setting)) {
906 switch (setting.type()) {
907 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
908 if (private_submodules_->render_pre_processor) {
909 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
910 }
911 break;
912 case RuntimeSetting::Type::kCapturePreGain:
913 RTC_NOTREACHED();
914 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200915 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200916 RTC_NOTREACHED();
917 break;
918 }
919 }
920}
921
peah9e6a2902017-05-15 07:19:21 -0700922void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700923 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
924 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700925 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700926
kwibergaf476c72016-11-28 15:21:39 -0800927 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700928
929 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700930 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700931 // The data queue is full and needs to be emptied.
932 EmptyQueuedRenderAudio();
933
934 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700935 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700936 RTC_DCHECK(result);
937 }
938
939 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
940 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700941 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700942
943 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700944 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700945 // The data queue is full and needs to be emptied.
946 EmptyQueuedRenderAudio();
947
948 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700949 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700950 RTC_DCHECK(result);
951 }
peah701d6282016-10-25 05:42:20 -0700952
953 if (!constants_.use_experimental_agc) {
954 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
955 // Insert the samples into the queue.
956 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
957 // The data queue is full and needs to be emptied.
958 EmptyQueuedRenderAudio();
959
960 // Retry the insert (should always work).
961 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
962 RTC_DCHECK(result);
963 }
964 }
peah9e6a2902017-05-15 07:19:21 -0700965}
ivoc9f4a4a02016-10-28 05:39:16 -0700966
peah9e6a2902017-05-15 07:19:21 -0700967void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700968 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
969
970 // Insert the samples into the queue.
971 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
972 // The data queue is full and needs to be emptied.
973 EmptyQueuedRenderAudio();
974
975 // Retry the insert (should always work).
976 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
977 RTC_DCHECK(result);
978 }
peah764e3642016-10-22 05:04:30 -0700979}
980
981void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700982 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700983 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700984 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700985 EchoCancellationImpl::NumCancellersRequired(
986 num_output_channels(), num_reverse_channels()));
987
peah701d6282016-10-25 05:42:20 -0700988 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700989 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700990 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700991 EchoControlMobileImpl::NumCancellersRequired(
992 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700993
peah701d6282016-10-25 05:42:20 -0700994 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700995 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700996
ivoc9f4a4a02016-10-28 05:39:16 -0700997 const size_t new_red_render_queue_element_max_size =
998 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
999
peaha0624602016-10-25 04:45:24 -07001000 // Reallocate the queues if the queue item sizes are too small to fit the
1001 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001002 if (aec_render_queue_element_max_size_ <
1003 new_aec_render_queue_element_max_size) {
1004 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001005
peaha0624602016-10-25 04:45:24 -07001006 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001007 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001008
peah701d6282016-10-25 05:42:20 -07001009 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001010 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1011 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001012 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001013 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001014
peah701d6282016-10-25 05:42:20 -07001015 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1016 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001017 } else {
peah701d6282016-10-25 05:42:20 -07001018 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001019 }
1020
peah701d6282016-10-25 05:42:20 -07001021 if (aecm_render_queue_element_max_size_ <
1022 new_aecm_render_queue_element_max_size) {
1023 aecm_render_queue_element_max_size_ =
1024 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001025
1026 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001027 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001028
peah701d6282016-10-25 05:42:20 -07001029 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001030 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1031 kMaxNumFramesToBuffer, template_queue_element,
1032 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001033 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001034
peah701d6282016-10-25 05:42:20 -07001035 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1036 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001037 } else {
peah701d6282016-10-25 05:42:20 -07001038 aecm_render_signal_queue_->Clear();
1039 }
1040
1041 if (agc_render_queue_element_max_size_ <
1042 new_agc_render_queue_element_max_size) {
1043 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1044
1045 std::vector<int16_t> template_queue_element(
1046 agc_render_queue_element_max_size_);
1047
1048 agc_render_signal_queue_.reset(
1049 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1050 kMaxNumFramesToBuffer, template_queue_element,
1051 RenderQueueItemVerifier<int16_t>(
1052 agc_render_queue_element_max_size_)));
1053
1054 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1055 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1056 } else {
1057 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001058 }
ivoc9f4a4a02016-10-28 05:39:16 -07001059
1060 if (red_render_queue_element_max_size_ <
1061 new_red_render_queue_element_max_size) {
1062 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1063
1064 std::vector<float> template_queue_element(
1065 red_render_queue_element_max_size_);
1066
1067 red_render_signal_queue_.reset(
1068 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1069 kMaxNumFramesToBuffer, template_queue_element,
1070 RenderQueueItemVerifier<float>(
1071 red_render_queue_element_max_size_)));
1072
1073 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1074 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1075 } else {
1076 red_render_signal_queue_->Clear();
1077 }
peah764e3642016-10-22 05:04:30 -07001078}
1079
1080void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1081 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001082 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001083 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001084 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001085 }
1086
peah701d6282016-10-25 05:42:20 -07001087 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001088 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001089 aecm_capture_queue_buffer_);
1090 }
1091
1092 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1093 public_submodules_->gain_control->ProcessRenderAudio(
1094 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001095 }
ivoc9f4a4a02016-10-28 05:39:16 -07001096
1097 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001098 RTC_DCHECK(private_submodules_->echo_detector);
1099 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001100 red_capture_queue_buffer_);
1101 }
peah764e3642016-10-22 05:04:30 -07001102}
1103
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001104int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001105 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001106 {
1107 // Acquire the capture lock in order to safely call the function
1108 // that retrieves the render side data. This function accesses apm
1109 // getters that need the capture lock held when being called.
1110 // The lock needs to be released as
1111 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1112 // as well.
1113 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001114 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001115 }
peahfa6228e2015-11-16 16:27:42 -08001116
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001117 if (!frame) {
1118 return kNullPointerError;
1119 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001120 // Must be a native rate.
1121 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1122 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001123 frame->sample_rate_hz_ != kSampleRate32kHz &&
1124 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001125 return kBadSampleRateError;
1126 }
peah192164e2015-11-17 02:16:45 -08001127
peahdf3efa82015-11-28 12:35:15 -08001128 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001129 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001130 {
1131 // Aquire lock for the access of api_format.
1132 // The lock is released immediately due to the conditional
1133 // reinitialization.
1134 rtc::CritScope cs_capture(&crit_capture_);
1135 // TODO(ajm): The input and output rates and channels are currently
1136 // constrained to be identical in the int16 interface.
1137 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001138
1139 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001140 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001141 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1142 processing_config.input_stream().set_num_channels(frame->num_channels_);
1143 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1144 processing_config.output_stream().set_num_channels(frame->num_channels_);
1145
peahdf3efa82015-11-28 12:35:15 -08001146 {
1147 // Do conditional reinitialization.
1148 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001149 RETURN_ON_ERR(
1150 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001151 }
1152 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001153 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001154 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001155 return kBadDataLengthError;
1156 }
1157
aleloi868f32f2017-05-23 07:20:05 -07001158 if (aec_dump_) {
1159 RecordUnprocessedCaptureStream(*frame);
1160 }
1161
peahdf3efa82015-11-28 12:35:15 -08001162 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001163 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001164 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001165 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1166 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001167
aleloi868f32f2017-05-23 07:20:05 -07001168 if (aec_dump_) {
1169 RecordProcessedCaptureStream(*frame);
1170 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001171
1172 return kNoError;
1173}
1174
peahde65ddc2016-09-16 15:02:15 -07001175int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001176 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001177
peahb58a1582016-03-15 09:34:24 -07001178 // Ensure that not both the AEC and AECM are active at the same time.
1179 // TODO(peah): Simplify once the public API Enable functions for these
1180 // are moved to APM.
1181 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1182 public_submodules_->echo_control_mobile->is_enabled()));
1183
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001184 MaybeUpdateHistograms();
1185
peahde65ddc2016-09-16 15:02:15 -07001186 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001187
Alex Loikob5c9a792018-04-16 16:31:22 +02001188 if (private_submodules_->pre_amplifier) {
1189 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1190 capture_buffer->channels_f(), capture_buffer->num_channels(),
1191 capture_buffer->num_frames()));
1192 }
1193
peah1b08dc32016-12-20 13:45:58 -08001194 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001195 capture_buffer->channels_const()[0],
1196 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001197 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1198 if (log_rms) {
1199 capture_rms_interval_counter_ = 0;
1200 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001201 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1202 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1203 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1204 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001205 }
1206
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001207 if (private_submodules_->echo_controller) {
Per Åhgren9aed31c2017-06-29 20:23:27 +02001208 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1209 // issues have been addressed.
1210 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001211 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001212 }
1213
peahbe615622016-02-13 16:40:47 -08001214 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001215 public_submodules_->gain_control->is_enabled()) {
1216 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001217 capture_buffer->channels()[0], capture_buffer->num_channels(),
1218 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001219 }
1220
peah2ace3f92016-09-10 04:42:27 -07001221 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1222 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001223 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1224 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001225 }
1226
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001227 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001228 // Force down-mixing of the number of channels after the detection of
1229 // capture signal saturation.
1230 // TODO(peah): Look into ensuring that this kind of tampering with the
1231 // AudioBuffer functionality should not be needed.
1232 capture_buffer->set_num_channels(1);
1233 }
1234
peahe0eae3c2016-12-14 01:16:23 -08001235 // TODO(peah): Move the AEC3 low-cut filter to this place.
1236 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001237 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001238 private_submodules_->low_cut_filter->Process(capture_buffer);
1239 }
peahde65ddc2016-09-16 15:02:15 -07001240 RETURN_ON_ERR(
1241 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1242 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001243
1244 // Ensure that the stream delay was set before the call to the
1245 // AEC ProcessCaptureAudio function.
1246 if (public_submodules_->echo_cancellation->is_enabled() &&
Per Åhgren0dfd3722018-05-06 18:16:01 +02001247 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001248 return AudioProcessing::kStreamParameterNotSetError;
1249 }
1250
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001251 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001252 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1253
Per Åhgrend0fa8202018-04-18 09:35:13 +02001254 if (was_stream_delay_set()) {
1255 private_submodules_->echo_controller->SetAudioBufferDelay(
1256 stream_delay_ms());
1257 }
1258
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001259 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001260 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001261 } else {
1262 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1263 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001264 }
1265
peahdf3efa82015-11-28 12:35:15 -08001266 if (public_submodules_->echo_control_mobile->is_enabled() &&
1267 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001268 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001269 }
peahde65ddc2016-09-16 15:02:15 -07001270 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001271#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001272 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001273 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001274 const int gain_db =
1275 public_submodules_->gain_control->is_enabled()
1276 ? public_submodules_->gain_control->compression_gain_db()
1277 : 0;
1278 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001279 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001280 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001281 }
peah1bcfce52016-08-26 07:16:04 -07001282#endif
peah253534d2016-03-15 04:32:28 -07001283
1284 // Ensure that the stream delay was set before the call to the
1285 // AECM ProcessCaptureAudio function.
1286 if (public_submodules_->echo_control_mobile->is_enabled() &&
1287 !was_stream_delay_set()) {
1288 return AudioProcessing::kStreamParameterNotSetError;
1289 }
1290
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001291 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001292 public_submodules_->echo_cancellation->is_enabled())) {
1293 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1294 capture_buffer, stream_delay_ms()));
1295 }
ivoc9f4a4a02016-10-28 05:39:16 -07001296
peahde65ddc2016-09-16 15:02:15 -07001297 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001298
peahbe615622016-02-13 16:40:47 -08001299 if (constants_.use_experimental_agc &&
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001300 public_submodules_->gain_control->is_enabled()) {
peahdf3efa82015-11-28 12:35:15 -08001301 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001302 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1303 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001304 }
peahb8fbb542016-03-15 02:28:08 -07001305 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001306 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001307
peah2ace3f92016-09-10 04:42:27 -07001308 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1309 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001310 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1311 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001312 }
1313
peah9e6a2902017-05-15 07:19:21 -07001314 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001315 RTC_DCHECK(private_submodules_->echo_detector);
1316 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001317 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1318 capture_buffer->num_frames()));
1319 }
1320
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001321 // TODO(aluebs): Investigate if the transient suppression placement should be
1322 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001323 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001324 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001325 private_submodules_->agc_manager.get()
1326 ? private_submodules_->agc_manager->voice_probability()
1327 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001328
peahdf3efa82015-11-28 12:35:15 -08001329 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001330 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1331 capture_buffer->num_channels(),
1332 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1333 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1334 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001335 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001336 }
1337
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001338 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001339 private_submodules_->gain_controller2->Process(capture_buffer);
1340 }
1341
Sam Zackrisson0beac582017-09-25 12:04:02 +02001342 if (private_submodules_->capture_post_processor) {
1343 private_submodules_->capture_post_processor->Process(capture_buffer);
1344 }
1345
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001346 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001347 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001348
peah1b08dc32016-12-20 13:45:58 -08001349 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1350 capture_buffer->channels_const()[0],
1351 capture_nonlocked_.capture_processing_format.num_frames()));
1352 if (log_rms) {
1353 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1354 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1355 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1356 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1357 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1358 }
1359
peahdf3efa82015-11-28 12:35:15 -08001360 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001361 return kNoError;
1362}
1363
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001364int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001365 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001366 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001367 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001368 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001369 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001370 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001371 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001372 };
1373 if (samples_per_channel != reverse_config.num_frames()) {
1374 return kBadDataLengthError;
1375 }
peahdf3efa82015-11-28 12:35:15 -08001376 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001377}
1378
peahde65ddc2016-09-16 15:02:15 -07001379int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1380 const StreamConfig& input_config,
1381 const StreamConfig& output_config,
1382 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001383 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001384 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001385 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001386 if (submodule_states_.RenderMultiBandProcessingActive() ||
1387 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001388 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1389 dest);
peah2ace3f92016-09-10 04:42:27 -07001390 } else if (formats_.api_format.reverse_input_stream() !=
1391 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001392 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1393 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001394 } else {
peahde65ddc2016-09-16 15:02:15 -07001395 CopyAudioIfNeeded(src, input_config.num_frames(),
1396 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001397 }
1398
1399 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001400}
1401
peahdf3efa82015-11-28 12:35:15 -08001402int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001403 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001404 const StreamConfig& input_config,
1405 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001406 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001407 return kNullPointerError;
1408 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001409
peahde65ddc2016-09-16 15:02:15 -07001410 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001411 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001412 }
1413
peahdf3efa82015-11-28 12:35:15 -08001414 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001415 processing_config.reverse_input_stream() = input_config;
1416 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001417
peahdf3efa82015-11-28 12:35:15 -08001418 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001419 RTC_DCHECK_EQ(input_config.num_frames(),
1420 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001421
aleloi868f32f2017-05-23 07:20:05 -07001422 if (aec_dump_) {
1423 const size_t channel_size =
1424 formats_.api_format.reverse_input_stream().num_frames();
1425 const size_t num_channels =
1426 formats_.api_format.reverse_input_stream().num_channels();
1427 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001428 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001429 }
peahdf3efa82015-11-28 12:35:15 -08001430 render_.render_audio->CopyFrom(src,
1431 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001432 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001433}
1434
1435int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001436 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001437 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001438 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001439 return kNullPointerError;
1440 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001441 // Must be a native rate.
1442 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1443 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001444 frame->sample_rate_hz_ != kSampleRate32kHz &&
1445 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001446 return kBadSampleRateError;
1447 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001448
Michael Graczyk86c6d332015-07-23 11:41:39 -07001449 if (frame->num_channels_ <= 0) {
1450 return kBadNumberChannelsError;
1451 }
1452
peahdf3efa82015-11-28 12:35:15 -08001453 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001454 processing_config.reverse_input_stream().set_sample_rate_hz(
1455 frame->sample_rate_hz_);
1456 processing_config.reverse_input_stream().set_num_channels(
1457 frame->num_channels_);
1458 processing_config.reverse_output_stream().set_sample_rate_hz(
1459 frame->sample_rate_hz_);
1460 processing_config.reverse_output_stream().set_num_channels(
1461 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001462
peahdf3efa82015-11-28 12:35:15 -08001463 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001464 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001465 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001466 return kBadDataLengthError;
1467 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001468
aleloi868f32f2017-05-23 07:20:05 -07001469 if (aec_dump_) {
1470 aec_dump_->WriteRenderStreamMessage(*frame);
1471 }
1472
peahdf3efa82015-11-28 12:35:15 -08001473 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001474 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001475 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001476 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1477 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001478 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001479}
niklase@google.com470e71d2011-07-07 08:21:25 +00001480
peahde65ddc2016-09-16 15:02:15 -07001481int AudioProcessingImpl::ProcessRenderStreamLocked() {
1482 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001483
1484 QueueNonbandedRenderAudio(render_buffer);
1485
Alex Loiko73ec0192018-05-15 10:52:28 +02001486 HandleRenderRuntimeSettings();
1487
Alex Loiko5825aa62017-12-18 16:02:40 +01001488 if (private_submodules_->render_pre_processor) {
1489 private_submodules_->render_pre_processor->Process(render_buffer);
1490 }
1491
peah2ace3f92016-09-10 04:42:27 -07001492 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001493 SampleRateSupportsMultiBand(
1494 formats_.render_processing_format.sample_rate_hz())) {
1495 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001496 }
1497
peah1bcfce52016-08-26 07:16:04 -07001498#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001499 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001500 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001501 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001502 }
peah1bcfce52016-08-26 07:16:04 -07001503#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001504
peahce4d9152017-05-19 01:28:05 -07001505 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1506 QueueBandedRenderAudio(render_buffer);
1507 }
1508
peahe0eae3c2016-12-14 01:16:23 -08001509 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001510 if (private_submodules_->echo_controller) {
1511 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001512 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001513
peah2ace3f92016-09-10 04:42:27 -07001514 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001515 SampleRateSupportsMultiBand(
1516 formats_.render_processing_format.sample_rate_hz())) {
1517 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001518 }
1519
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001520 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001521}
1522
1523int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001524 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001525 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001526 capture_.was_stream_delay_set = true;
1527 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001528
niklase@google.com470e71d2011-07-07 08:21:25 +00001529 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001530 delay = 0;
1531 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001532 }
1533
1534 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1535 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001536 delay = 500;
1537 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001538 }
1539
peahdf3efa82015-11-28 12:35:15 -08001540 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001541 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001542}
1543
1544int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001545 // Used as callback from submodules, hence locking is not allowed.
1546 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001547}
1548
1549bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001550 // Used as callback from submodules, hence locking is not allowed.
1551 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001552}
1553
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001554void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001555 rtc::CritScope cs(&crit_capture_);
1556 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001557}
1558
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001559void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001560 rtc::CritScope cs(&crit_capture_);
1561 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001562}
1563
1564int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001565 rtc::CritScope cs(&crit_capture_);
1566 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001567}
1568
aleloi868f32f2017-05-23 07:20:05 -07001569void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1570 RTC_DCHECK(aec_dump);
1571 rtc::CritScope cs_render(&crit_render_);
1572 rtc::CritScope cs_capture(&crit_capture_);
1573
1574 // The previously attached AecDump will be destroyed with the
1575 // 'aec_dump' parameter, which is after locks are released.
1576 aec_dump_.swap(aec_dump);
1577 WriteAecDumpConfigMessage(true);
Alex Loiko1aec5942018-05-15 13:13:22 +02001578 aec_dump_->WriteInitMessage(formats_.api_format);
aleloi868f32f2017-05-23 07:20:05 -07001579}
1580
1581void AudioProcessingImpl::DetachAecDump() {
1582 // The d-tor of a task-queue based AecDump blocks until all pending
1583 // tasks are done. This construction avoids blocking while holding
1584 // the render and capture locks.
1585 std::unique_ptr<AecDump> aec_dump = nullptr;
1586 {
1587 rtc::CritScope cs_render(&crit_render_);
1588 rtc::CritScope cs_capture(&crit_capture_);
1589 aec_dump = std::move(aec_dump_);
1590 }
1591}
1592
Sam Zackrisson4d364492018-03-02 16:03:21 +01001593void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1594 std::unique_ptr<AudioGenerator> audio_generator) {
1595 // TODO(bugs.webrtc.org/8882) Stub.
1596 // Reset internal audio generator with audio_generator.
1597}
1598
1599void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1600 // TODO(bugs.webrtc.org/8882) Stub.
1601 // Delete audio generator, if one is attached.
1602}
1603
ivoc4e477a12017-01-15 08:29:46 -08001604AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1605 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1606 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1607 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1608 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1609}
1610
1611AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1612 const AudioProcessingStatistics& other) = default;
1613
1614AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1615 default;
1616
ivoc3e9a5372016-10-28 07:55:33 -07001617// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1618AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1619 const {
1620 return AudioProcessingStatistics();
1621}
1622
Ivo Creusenae026092017-11-20 13:07:16 +01001623// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001624AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001625 bool has_remote_tracks) const {
1626 return AudioProcessingStats();
1627}
1628
ivoc3e9a5372016-10-28 07:55:33 -07001629AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1630 const {
1631 AudioProcessingStatistics stats;
1632 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001633 if (private_submodules_->echo_controller) {
1634 rtc::CritScope cs_capture(&crit_capture_);
1635 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1636 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1637 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1638 // Instant value will also be used for min, max and average.
1639 stats.echo_return_loss.Set(erl, erl, erl, erl);
1640 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1641 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1642 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001643 stats.a_nlp.Set(metrics.a_nlp);
1644 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1645 stats.echo_return_loss.Set(metrics.echo_return_loss);
1646 stats.echo_return_loss_enhancement.Set(
1647 metrics.echo_return_loss_enhancement);
1648 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1649 }
ivoc9c192b22017-03-16 04:22:14 -07001650 {
1651 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001652 RTC_DCHECK(private_submodules_->echo_detector);
1653 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1654 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001655 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001656 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001657 }
ivoc3e9a5372016-10-28 07:55:33 -07001658 public_submodules_->echo_cancellation->GetDelayMetrics(
1659 &stats.delay_median, &stats.delay_standard_deviation,
1660 &stats.fraction_poor_delays);
1661 return stats;
1662}
1663
Ivo Creusen56d46092017-11-24 17:29:59 +01001664AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001665 bool has_remote_tracks) const {
1666 AudioProcessingStats stats;
1667 if (has_remote_tracks) {
1668 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001669 if (private_submodules_->echo_controller) {
1670 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001671 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1672 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001673 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001674 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001675 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001676 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1677 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001678 if (metrics.divergent_filter_fraction != -1.0f) {
1679 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001680 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001681 }
1682 if (metrics.echo_return_loss.instant != -100) {
1683 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001684 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001685 }
1686 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001687 stats.echo_return_loss_enhancement = absl::optional<double>(
1688 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001689 }
1690 }
1691 if (config_.residual_echo_detector.enabled) {
1692 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001693 RTC_DCHECK(private_submodules_->echo_detector);
1694 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1695 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001696 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001697 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001698 }
1699 int delay_median, delay_std;
1700 float fraction_poor_delays;
1701 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1702 &delay_median, &delay_std, &fraction_poor_delays) ==
1703 Error::kNoError) {
1704 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001705 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001706 }
1707 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001708 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001709 }
1710 }
1711 }
1712 return stats;
1713}
1714
niklase@google.com470e71d2011-07-07 08:21:25 +00001715EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001716 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001717}
1718
1719EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001720 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001721}
1722
1723GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001724 if (constants_.use_experimental_agc) {
1725 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001726 }
peahbfa97112016-03-10 21:09:04 -08001727 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001728}
1729
1730HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001731 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001732}
1733
1734LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001735 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001736}
1737
1738NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001739 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001740}
1741
1742VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001743 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001744}
1745
peah8271d042016-11-22 07:24:52 -08001746void AudioProcessingImpl::MutateConfig(
1747 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1748 rtc::CritScope cs_render(&crit_render_);
1749 rtc::CritScope cs_capture(&crit_capture_);
1750 mutator(&config_);
1751 ApplyConfig(config_);
1752}
1753
1754AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1755 rtc::CritScope cs_render(&crit_render_);
1756 rtc::CritScope cs_capture(&crit_capture_);
1757 return config_;
1758}
1759
peah2ace3f92016-09-10 04:42:27 -07001760bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1761 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001762 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001763 public_submodules_->echo_cancellation->is_enabled(),
1764 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001765 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001766 public_submodules_->noise_suppression->is_enabled(),
1767 capture_nonlocked_.intelligibility_enabled,
peah2ace3f92016-09-10 04:42:27 -07001768 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001769 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001770 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001771 public_submodules_->voice_detection->is_enabled(),
1772 public_submodules_->level_estimator->is_enabled(),
1773 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001774}
1775
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001776
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001777void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001778 if (capture_.transient_suppressor_enabled) {
1779 if (!public_submodules_->transient_suppressor.get()) {
1780 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001781 }
peahdf3efa82015-11-28 12:35:15 -08001782 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001783 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1784 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001785 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001786}
1787
ekmeyerson60d9b332015-08-14 10:35:55 -07001788void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001789#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001790 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001791 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001792 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001793 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001794 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001795 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001796 }
peah1bcfce52016-08-26 07:16:04 -07001797#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001798}
1799
peah8271d042016-11-22 07:24:52 -08001800void AudioProcessingImpl::InitializeLowCutFilter() {
1801 if (config_.high_pass_filter.enabled) {
1802 private_submodules_->low_cut_filter.reset(
1803 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1804 } else {
1805 private_submodules_->low_cut_filter.reset();
1806 }
1807}
alessiob3ec96df2017-05-22 06:57:06 -07001808
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001809void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001810 if (echo_control_factory_) {
1811 private_submodules_->echo_controller =
1812 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001813 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001814 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001815 }
1816}
peah8271d042016-11-22 07:24:52 -08001817
alessiob3ec96df2017-05-22 06:57:06 -07001818void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001819 if (config_.gain_controller2.enabled) {
1820 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001821 }
1822}
1823
Alex Loikob5c9a792018-04-16 16:31:22 +02001824void AudioProcessingImpl::InitializePreAmplifier() {
1825 if (config_.pre_amplifier.enabled) {
1826 private_submodules_->pre_amplifier.reset(
1827 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1828 } else {
1829 private_submodules_->pre_amplifier.reset();
1830 }
1831}
1832
ivoc9f4a4a02016-10-28 05:39:16 -07001833void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001834 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001835 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001836 proc_sample_rate_hz(), 1,
1837 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001838}
1839
Sam Zackrisson0beac582017-09-25 12:04:02 +02001840void AudioProcessingImpl::InitializePostProcessor() {
1841 if (private_submodules_->capture_post_processor) {
1842 private_submodules_->capture_post_processor->Initialize(
1843 proc_sample_rate_hz(), num_proc_channels());
1844 }
1845}
1846
Alex Loiko5825aa62017-12-18 16:02:40 +01001847void AudioProcessingImpl::InitializePreProcessor() {
1848 if (private_submodules_->render_pre_processor) {
1849 private_submodules_->render_pre_processor->Initialize(
1850 formats_.render_processing_format.sample_rate_hz(),
1851 formats_.render_processing_format.num_channels());
1852 }
1853}
1854
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001855void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001856 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001857
1858 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001859 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001860 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001861 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001862 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001863 capture_.stream_delay_jumps = 0;
1864 }
1865 if (capture_.aec_system_delay_jumps == -1 &&
1866 echo_cancellation()->stream_has_echo()) {
1867 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001868 }
1869
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001870 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001871 const int diff_stream_delay_ms =
1872 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1873 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1874 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001875 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1876 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001877 if (capture_.stream_delay_jumps == -1) {
1878 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001879 }
peahdf3efa82015-11-28 12:35:15 -08001880 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001881 }
peahdf3efa82015-11-28 12:35:15 -08001882 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001883
1884 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001885 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001886 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001887 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001888 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001889 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1890 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001891 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001892 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001893 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001894 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001895 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1896 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1897 100);
peahdf3efa82015-11-28 12:35:15 -08001898 if (capture_.aec_system_delay_jumps == -1) {
1899 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001900 }
peahdf3efa82015-11-28 12:35:15 -08001901 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001902 }
peahdf3efa82015-11-28 12:35:15 -08001903 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001904 }
1905}
1906
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001907void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001908 // Run in a single-threaded manner.
1909 rtc::CritScope cs_render(&crit_render_);
1910 rtc::CritScope cs_capture(&crit_capture_);
1911
1912 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001913 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001914 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001915 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001916 }
peahdf3efa82015-11-28 12:35:15 -08001917 capture_.stream_delay_jumps = -1;
1918 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001919
peahdf3efa82015-11-28 12:35:15 -08001920 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001921 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1922 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001923 }
peahdf3efa82015-11-28 12:35:15 -08001924 capture_.aec_system_delay_jumps = -1;
1925 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001926}
1927
aleloi868f32f2017-05-23 07:20:05 -07001928void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1929 if (!aec_dump_) {
1930 return;
1931 }
1932 std::string experiments_description =
1933 public_submodules_->echo_cancellation->GetExperimentsDescription();
1934 // TODO(peah): Add semicolon-separated concatenations of experiment
1935 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001936 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1937 experiments_description += "AgcClippingLevelExperiment;";
1938 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001939 if (capture_nonlocked_.echo_controller_enabled) {
1940 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001941 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001942 if (config_.gain_controller2.enabled) {
1943 experiments_description += "GainController2;";
1944 }
aleloi868f32f2017-05-23 07:20:05 -07001945
1946 InternalAPMConfig apm_config;
1947
1948 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1949 apm_config.aec_delay_agnostic_enabled =
1950 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1951 apm_config.aec_drift_compensation_enabled =
1952 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1953 apm_config.aec_extended_filter_enabled =
1954 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1955 apm_config.aec_suppression_level = static_cast<int>(
1956 public_submodules_->echo_cancellation->suppression_level());
1957
1958 apm_config.aecm_enabled =
1959 public_submodules_->echo_control_mobile->is_enabled();
1960 apm_config.aecm_comfort_noise_enabled =
1961 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1962 apm_config.aecm_routing_mode =
1963 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1964
1965 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1966 apm_config.agc_mode =
1967 static_cast<int>(public_submodules_->gain_control->mode());
1968 apm_config.agc_limiter_enabled =
1969 public_submodules_->gain_control->is_limiter_enabled();
1970 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1971
1972 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1973
1974 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1975 apm_config.ns_level =
1976 static_cast<int>(public_submodules_->noise_suppression->level());
1977
1978 apm_config.transient_suppression_enabled =
1979 capture_.transient_suppressor_enabled;
1980 apm_config.intelligibility_enhancer_enabled =
1981 capture_nonlocked_.intelligibility_enabled;
1982 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001983 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1984 apm_config.pre_amplifier_fixed_gain_factor =
1985 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001986
1987 if (!forced && apm_config == apm_config_for_aec_dump_) {
1988 return;
1989 }
1990 aec_dump_->WriteConfig(apm_config);
1991 apm_config_for_aec_dump_ = apm_config;
1992}
1993
1994void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1995 const float* const* src) {
1996 RTC_DCHECK(aec_dump_);
1997 WriteAecDumpConfigMessage(false);
1998
1999 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2000 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2001 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002002 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002003 RecordAudioProcessingState();
2004}
2005
2006void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2007 const AudioFrame& capture_frame) {
2008 RTC_DCHECK(aec_dump_);
2009 WriteAecDumpConfigMessage(false);
2010
2011 aec_dump_->AddCaptureStreamInput(capture_frame);
2012 RecordAudioProcessingState();
2013}
2014
2015void AudioProcessingImpl::RecordProcessedCaptureStream(
2016 const float* const* processed_capture_stream) {
2017 RTC_DCHECK(aec_dump_);
2018
2019 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2020 const size_t num_channels =
2021 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002022 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2023 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002024 aec_dump_->WriteCaptureStreamMessage();
2025}
2026
2027void AudioProcessingImpl::RecordProcessedCaptureStream(
2028 const AudioFrame& processed_capture_frame) {
2029 RTC_DCHECK(aec_dump_);
2030
2031 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2032 aec_dump_->WriteCaptureStreamMessage();
2033}
2034
2035void AudioProcessingImpl::RecordAudioProcessingState() {
2036 RTC_DCHECK(aec_dump_);
2037 AecDump::AudioProcessingState audio_proc_state;
2038 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2039 audio_proc_state.drift =
2040 public_submodules_->echo_cancellation->stream_drift_samples();
2041 audio_proc_state.level = gain_control()->stream_analog_level();
2042 audio_proc_state.keypress = capture_.key_pressed;
2043 aec_dump_->AddAudioProcessingState(audio_proc_state);
2044}
2045
kwiberg83ffe452016-08-29 14:46:07 -07002046AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002047 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002048 : aec_system_delay_jumps(-1),
2049 delay_offset_ms(0),
2050 was_stream_delay_set(false),
2051 last_stream_delay_ms(0),
2052 last_aec_system_delay_ms(0),
2053 stream_delay_jumps(-1),
2054 output_will_be_muted(false),
2055 key_pressed(false),
2056 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002057 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002058 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002059 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002060
2061AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2062
2063AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2064
2065AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2066
niklase@google.com470e71d2011-07-07 08:21:25 +00002067} // namespace webrtc