blob: 28c796497dbca2606fdb3daf30b60de4289a1080 [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[];
aluebsdf6416a2016-03-16 18:26:35 -070069
Michael Graczyk86c6d332015-07-23 11:41:39 -070070namespace {
71
72static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
73 switch (layout) {
74 case AudioProcessing::kMono:
75 case AudioProcessing::kStereo:
76 return false;
77 case AudioProcessing::kMonoAndKeyboard:
78 case AudioProcessing::kStereoAndKeyboard:
79 return true;
80 }
81
kwiberg9e2be5f2016-09-14 05:23:22 -070082 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070083 return false;
84}
aluebsdf6416a2016-03-16 18:26:35 -070085
peah2ace3f92016-09-10 04:42:27 -070086bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070087 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
88 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
89}
90
peah2ace3f92016-09-10 04:42:27 -070091int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
92#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070093 constexpr int kMaxSplittingNativeProcessRate =
94 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070095#else
kwibergd59d3bb2016-09-13 07:49:33 -070096 constexpr int kMaxSplittingNativeProcessRate =
97 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070098#endif
kwibergd59d3bb2016-09-13 07:49:33 -070099 static_assert(
100 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
101 "");
peah2ace3f92016-09-10 04:42:27 -0700102 const int uppermost_native_rate = band_splitting_required
103 ? kMaxSplittingNativeProcessRate
104 : AudioProcessing::kSampleRate48kHz;
105
106 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
107 if (rate >= uppermost_native_rate) {
108 return uppermost_native_rate;
109 }
110 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700111 return rate;
112 }
113 }
peah2ace3f92016-09-10 04:42:27 -0700114 RTC_NOTREACHED();
115 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700116}
117
peah9e6a2902017-05-15 07:19:21 -0700118// Maximum lengths that frame of samples being passed from the render side to
119// the capture side can have (does not apply to AEC3).
120static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
121static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
122
peah764e3642016-10-22 05:04:30 -0700123// Maximum number of frames to buffer in the render queue.
124// TODO(peah): Decrease this once we properly handle hugely unbalanced
125// reverse and forward call numbers.
126static const size_t kMaxNumFramesToBuffer = 100;
127
peah8271d042016-11-22 07:24:52 -0800128class HighPassFilterImpl : public HighPassFilter {
129 public:
130 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
131 ~HighPassFilterImpl() override = default;
132
133 // HighPassFilter implementation.
134 int Enable(bool enable) override {
135 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
136 config->high_pass_filter.enabled = enable;
137 });
138
139 return AudioProcessing::kNoError;
140 }
141
142 bool is_enabled() const override {
143 return apm_->GetConfig().high_pass_filter.enabled;
144 }
145
146 private:
147 AudioProcessingImpl* apm_;
148 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
149};
150
aleloi868f32f2017-05-23 07:20:05 -0700151webrtc::InternalAPMStreamsConfig ToStreamsConfig(
152 const ProcessingConfig& api_format) {
153 webrtc::InternalAPMStreamsConfig result;
154 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
155 result.input_num_channels = api_format.input_stream().num_channels();
156 result.output_num_channels = api_format.output_stream().num_channels();
157 result.render_input_num_channels =
158 api_format.reverse_input_stream().num_channels();
159 result.render_input_sample_rate =
160 api_format.reverse_input_stream().sample_rate_hz();
161 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
162 result.render_output_sample_rate =
163 api_format.reverse_output_stream().sample_rate_hz();
164 result.render_output_num_channels =
165 api_format.reverse_output_stream().num_channels();
166 return result;
167}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700168} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000169
170// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000171static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000172
Sam Zackrisson0beac582017-09-25 12:04:02 +0200173AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100174 bool capture_post_processor_enabled,
175 bool render_pre_processor_enabled)
176 : capture_post_processor_enabled_(capture_post_processor_enabled),
177 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700178
179bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800180 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700181 bool echo_canceller_enabled,
182 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700183 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700184 bool noise_suppressor_enabled,
185 bool intelligibility_enhancer_enabled,
186 bool beamformer_enabled,
187 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700188 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200189 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200190 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700191 bool voice_activity_detector_enabled,
192 bool level_estimator_enabled,
193 bool transient_suppressor_enabled) {
194 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800195 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700196 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
197 changed |=
198 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700199 changed |=
200 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700201 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
202 changed |=
203 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
204 changed |= (beamformer_enabled != beamformer_enabled_);
205 changed |=
206 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700207 changed |=
208 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200209 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200210 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700211 changed |= (level_estimator_enabled != level_estimator_enabled_);
212 changed |=
213 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
214 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
215 if (changed) {
peah8271d042016-11-22 07:24:52 -0800216 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700217 echo_canceller_enabled_ = echo_canceller_enabled;
218 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700219 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700220 noise_suppressor_enabled_ = noise_suppressor_enabled;
221 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
222 beamformer_enabled_ = beamformer_enabled;
223 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700224 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200225 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200226 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700227 level_estimator_enabled_ = level_estimator_enabled;
228 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
229 transient_suppressor_enabled_ = transient_suppressor_enabled;
230 }
231
232 changed |= first_update_;
233 first_update_ = false;
234 return changed;
235}
236
237bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
238 const {
239#if WEBRTC_INTELLIGIBILITY_ENHANCER
240 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700241 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700242#else
peah52775842017-05-16 06:14:09 -0700243 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700244#endif
245}
246
247bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
248 const {
peah8271d042016-11-22 07:24:52 -0800249 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700250 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800251 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200252 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700253}
254
peah23ac8b42017-05-23 05:33:56 -0700255bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
256 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200257 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
258 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700259}
260
peah2ace3f92016-09-10 04:42:27 -0700261bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
262 const {
263 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800264 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200265 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700266}
267
Alex Loiko5825aa62017-12-18 16:02:40 +0100268bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
269 const {
270 return render_pre_processor_enabled_;
271}
272
peah2ace3f92016-09-10 04:42:27 -0700273bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
274 const {
275#if WEBRTC_INTELLIGIBILITY_ENHANCER
276 return intelligibility_enhancer_enabled_;
277#else
278 return false;
279#endif
280}
281
solenberg5e465c32015-12-08 13:22:33 -0800282struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800283 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800284 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800285 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800286 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800287 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800288 std::unique_ptr<LevelEstimatorImpl> level_estimator;
289 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
290 std::unique_ptr<VoiceDetectionImpl> voice_detection;
291 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800292 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800293
294 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800295 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700296#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800297 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700298#endif
solenberg5e465c32015-12-08 13:22:33 -0800299};
300
301struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200302 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100303 std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100304 std::unique_ptr<CustomProcessing> render_pre_processor,
305 std::unique_ptr<EchoDetector> echo_detector)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200306 : beamformer(beamformer),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100307 echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100308 capture_post_processor(std::move(capture_post_processor)),
309 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800310 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700311 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800312 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700313 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800314 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100315 std::unique_ptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200316 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100317 std::unique_ptr<CustomProcessing> capture_post_processor;
318 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200319 std::unique_ptr<GainApplier> pre_amplifier;
solenberg5e465c32015-12-08 13:22:33 -0800320};
321
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100322AudioProcessingBuilder::AudioProcessingBuilder() = default;
323AudioProcessingBuilder::~AudioProcessingBuilder() = default;
324
325AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
326 std::unique_ptr<CustomProcessing> capture_post_processing) {
327 capture_post_processing_ = std::move(capture_post_processing);
328 return *this;
329}
330
331AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
332 std::unique_ptr<CustomProcessing> render_pre_processing) {
333 render_pre_processing_ = std::move(render_pre_processing);
334 return *this;
335}
336
337AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
338 std::unique_ptr<EchoControlFactory> echo_control_factory) {
339 echo_control_factory_ = std::move(echo_control_factory);
340 return *this;
341}
342
343AudioProcessingBuilder& AudioProcessingBuilder::SetNonlinearBeamformer(
344 std::unique_ptr<NonlinearBeamformer> nonlinear_beamformer) {
345 nonlinear_beamformer_ = std::move(nonlinear_beamformer);
346 return *this;
347}
348
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100349AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
350 std::unique_ptr<EchoDetector> echo_detector) {
351 echo_detector_ = std::move(echo_detector);
352 return *this;
353}
354
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100355AudioProcessing* AudioProcessingBuilder::Create() {
356 webrtc::Config config;
357 return Create(config);
358}
359
360AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100361 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
362 config, std::move(capture_post_processing_),
363 std::move(render_pre_processing_), std::move(echo_control_factory_),
364 std::move(echo_detector_), nonlinear_beamformer_.release());
365 if (apm->Initialize() != AudioProcessing::kNoError) {
366 delete apm;
367 apm = nullptr;
368 }
369 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100370}
371
peah88ac8532016-09-12 16:47:25 -0700372AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100373 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
374}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000375
Per Åhgren13735822018-02-12 21:42:56 +0100376int AudioProcessingImpl::instance_count_ = 0;
377
Sam Zackrisson0beac582017-09-25 12:04:02 +0200378AudioProcessingImpl::AudioProcessingImpl(
379 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100380 std::unique_ptr<CustomProcessing> capture_post_processor,
381 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200382 std::unique_ptr<EchoControlFactory> echo_control_factory,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100383 std::unique_ptr<EchoDetector> echo_detector,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200384 NonlinearBeamformer* beamformer)
Per Åhgren13735822018-02-12 21:42:56 +0100385 : data_dumper_(
386 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200387 runtime_settings_(100),
388 runtime_settings_enqueuer_(&runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100389 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200390 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100391 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800392 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200393 private_submodules_(
394 new ApmPrivateSubmodules(beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100395 std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100396 std::move(render_pre_processor),
397 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800398 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800399 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000400#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700401 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000402#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700403 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000404#endif
andrew1c7075f2015-06-24 18:14:14 -0700405#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800406 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700407#else
aluebs2a346882016-01-11 18:04:30 -0800408 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700409#endif
aluebs2a346882016-01-11 18:04:30 -0800410 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800411 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700412 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700413 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800414 {
415 rtc::CritScope cs_render(&crit_render_);
416 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000417
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200418 // Mark Echo Controller enabled if a factory is injected.
419 capture_nonlocked_.echo_controller_enabled =
420 static_cast<bool>(echo_control_factory_);
421
peahb624d8c2016-03-05 03:01:14 -0800422 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700423 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800424 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700425 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800426 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700427 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800428 public_submodules_->level_estimator.reset(
429 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800430 public_submodules_->noise_suppression.reset(
431 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800432 public_submodules_->voice_detection.reset(
433 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800434 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800435 new GainControlForExperimentalAgc(
436 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100437
438 // If no echo detector is injected, use the ResidualEchoDetector.
439 if (!private_submodules_->echo_detector) {
440 private_submodules_->echo_detector.reset(new ResidualEchoDetector());
441 }
peahca4cac72016-06-29 15:26:12 -0700442
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200443 // TODO(alessiob): Move the injected gain controller once injection is
444 // implemented.
445 private_submodules_->gain_controller2.reset(new GainController2());
446
Mirko Bonadei675513b2017-11-09 11:09:25 +0100447 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100448 << !!private_submodules_->capture_post_processor
449 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100450 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800451 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000452
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000453 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000454}
455
456AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800457 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800458 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800459 private_submodules_->agc_manager.reset();
460 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800461 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000462}
463
niklase@google.com470e71d2011-07-07 08:21:25 +0000464int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800465 // Run in a single-threaded manner during initialization.
466 rtc::CritScope cs_render(&crit_render_);
467 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000468 return InitializeLocked();
469}
470
peahde65ddc2016-09-16 15:02:15 -0700471int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
472 int capture_output_sample_rate_hz,
473 int render_input_sample_rate_hz,
474 ChannelLayout capture_input_layout,
475 ChannelLayout capture_output_layout,
476 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700477 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700478 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
479 LayoutHasKeyboard(capture_input_layout)},
480 {capture_output_sample_rate_hz,
481 ChannelsFromLayout(capture_output_layout),
482 LayoutHasKeyboard(capture_output_layout)},
483 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
484 LayoutHasKeyboard(render_input_layout)},
485 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
486 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700487
488 return Initialize(processing_config);
489}
490
491int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800492 // Run in a single-threaded manner during initialization.
493 rtc::CritScope cs_render(&crit_render_);
494 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700495 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000496}
497
peahdf3efa82015-11-28 12:35:15 -0800498int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800499 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700500 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800501}
502
peahdf3efa82015-11-28 12:35:15 -0800503int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700504 const ProcessingConfig& processing_config,
505 bool force_initialization) {
506 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800507}
508
peah192164e2015-11-17 02:16:45 -0800509// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800510// their current values (needs to be called while holding the crit_render_lock).
511int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700512 const ProcessingConfig& processing_config,
513 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800514 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700515 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800516 return kNoError;
517 }
peahdf3efa82015-11-28 12:35:15 -0800518
519 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800520 return InitializeLocked(processing_config);
521}
522
niklase@google.com470e71d2011-07-07 08:21:25 +0000523int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200524 UpdateActiveSubmoduleStates();
525
peah522d71b2017-02-23 05:16:26 -0800526 const int capture_audiobuffer_num_channels =
527 capture_nonlocked_.beamformer_enabled
528 ? formats_.api_format.input_stream().num_channels()
529 : formats_.api_format.output_stream().num_channels();
530
peahde65ddc2016-09-16 15:02:15 -0700531 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800532 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700533 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800534 : formats_.api_format.reverse_output_stream().num_frames();
535 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
536 render_.render_audio.reset(new AudioBuffer(
537 formats_.api_format.reverse_input_stream().num_frames(),
538 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700539 formats_.render_processing_format.num_frames(),
540 formats_.render_processing_format.num_channels(),
541 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700542 if (formats_.api_format.reverse_input_stream() !=
543 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800544 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800545 formats_.api_format.reverse_input_stream().num_channels(),
546 formats_.api_format.reverse_input_stream().num_frames(),
547 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800548 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700549 } else {
peahdf3efa82015-11-28 12:35:15 -0800550 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700551 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700552 } else {
peahdf3efa82015-11-28 12:35:15 -0800553 render_.render_audio.reset(nullptr);
554 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700555 }
peahce4d9152017-05-19 01:28:05 -0700556
peahdf3efa82015-11-28 12:35:15 -0800557 capture_.capture_audio.reset(
558 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
559 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700560 capture_nonlocked_.capture_processing_format.num_frames(),
561 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800562 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000563
peahde65ddc2016-09-16 15:02:15 -0700564 public_submodules_->echo_cancellation->Initialize(
565 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
566 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700567 AllocateRenderQueue();
568
ivoc3e9a5372016-10-28 07:55:33 -0700569 int success = public_submodules_->echo_cancellation->enable_metrics(true);
570 RTC_DCHECK_EQ(0, success);
571 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
572 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700573 public_submodules_->echo_control_mobile->Initialize(
574 proc_split_sample_rate_hz(), num_reverse_channels(),
575 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700576
577 public_submodules_->gain_control->Initialize(num_proc_channels(),
578 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700579 if (constants_.use_experimental_agc) {
580 if (!private_submodules_->agc_manager.get()) {
581 private_submodules_->agc_manager.reset(new AgcManagerDirect(
582 public_submodules_->gain_control.get(),
583 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800584 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700585 }
586 private_submodules_->agc_manager->Initialize();
587 private_submodules_->agc_manager->SetCaptureMuted(
588 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700589 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700590 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200591 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000592 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700593#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700594 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700595#endif
peah8271d042016-11-22 07:24:52 -0800596 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700597 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
598 proc_sample_rate_hz());
599 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
600 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700601 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200602 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700603 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200604 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100605 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800606
aleloi868f32f2017-05-23 07:20:05 -0700607 if (aec_dump_) {
608 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
609 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000610 return kNoError;
611}
612
Michael Graczyk86c6d332015-07-23 11:41:39 -0700613int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200614 UpdateActiveSubmoduleStates();
615
Michael Graczyk86c6d332015-07-23 11:41:39 -0700616 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700617 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
618 return kBadSampleRateError;
619 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000620 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700621
Peter Kasting69558702016-01-12 16:26:35 -0800622 const size_t num_in_channels = config.input_stream().num_channels();
623 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700624
625 // Need at least one input channel.
626 // Need either one output channel or as many outputs as there are inputs.
627 if (num_in_channels == 0 ||
628 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700629 return kBadNumberChannelsError;
630 }
631
aluebsb2328d12016-01-11 20:32:29 -0800632 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800633 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700634 return kBadNumberChannelsError;
635 }
636
peahdf3efa82015-11-28 12:35:15 -0800637 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000638
peahde65ddc2016-09-16 15:02:15 -0700639 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700640 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700641 formats_.api_format.output_stream().sample_rate_hz()),
642 submodule_states_.CaptureMultiBandSubModulesActive() ||
643 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000644
peahde65ddc2016-09-16 15:02:15 -0700645 capture_nonlocked_.capture_processing_format =
646 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700647
peah2ce640f2017-04-07 03:57:48 -0700648 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200649 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700650 render_processing_rate = FindNativeProcessRateToUse(
651 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
652 formats_.api_format.reverse_output_stream().sample_rate_hz()),
653 submodule_states_.CaptureMultiBandSubModulesActive() ||
654 submodule_states_.RenderMultiBandSubModulesActive());
655 } else {
656 render_processing_rate = capture_processing_rate;
657 }
658
aluebseb3603b2016-04-20 15:27:58 -0700659 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
660 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700661 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200662 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700663 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
664 ? kSampleRate32kHz
665 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700666 }
peah2ce640f2017-04-07 03:57:48 -0700667
peahde65ddc2016-09-16 15:02:15 -0700668 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700669 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700670 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
671 kSampleRate8kHz) {
672 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000673 } else {
peahde65ddc2016-09-16 15:02:15 -0700674 render_processing_rate =
675 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000676 }
677
peahde65ddc2016-09-16 15:02:15 -0700678 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000679 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700680 if (submodule_states_.RenderMultiBandSubModulesActive()) {
681 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
682 } else {
683 formats_.render_processing_format = StreamConfig(
684 formats_.api_format.reverse_input_stream().sample_rate_hz(),
685 formats_.api_format.reverse_input_stream().num_channels());
686 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000687
peahde65ddc2016-09-16 15:02:15 -0700688 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
689 kSampleRate32kHz ||
690 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
691 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800692 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000693 } else {
peahdf3efa82015-11-28 12:35:15 -0800694 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700695 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000696 }
697
698 return InitializeLocked();
699}
700
peah88ac8532016-09-12 16:47:25 -0700701void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700702 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700703
peah88ac8532016-09-12 16:47:25 -0700704 // Run in a single-threaded manner when applying the settings.
705 rtc::CritScope cs_render(&crit_render_);
706 rtc::CritScope cs_capture(&crit_capture_);
707
peah8271d042016-11-22 07:24:52 -0800708 InitializeLowCutFilter();
709
Mirko Bonadei675513b2017-11-09 11:09:25 +0100710 RTC_LOG(LS_INFO) << "Highpass filter activated: "
711 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800712
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100713 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700714 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100715 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
716 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100717 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100718 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700719 config_.gain_controller2 = AudioProcessing::Config::GainController2();
720 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200721 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200722 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200723 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100724 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
725 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200726 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
727 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700728}
729
730void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800731 // Run in a single-threaded manner when setting the extra options.
732 rtc::CritScope cs_render(&crit_render_);
733 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000734
peahb624d8c2016-03-05 03:01:14 -0800735 public_submodules_->echo_cancellation->SetExtraOptions(config);
736
peahdf3efa82015-11-28 12:35:15 -0800737 if (capture_.transient_suppressor_enabled !=
738 config.Get<ExperimentalNs>().enabled) {
739 capture_.transient_suppressor_enabled =
740 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000741 InitializeTransient();
742 }
aluebs2a346882016-01-11 18:04:30 -0800743
peah1bcfce52016-08-26 07:16:04 -0700744#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700745 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700746 config.Get<Intelligibility>().enabled) {
747 capture_nonlocked_.intelligibility_enabled =
748 config.Get<Intelligibility>().enabled;
749 InitializeIntelligibility();
750 }
peah1bcfce52016-08-26 07:16:04 -0700751#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700752
aluebs2a346882016-01-11 18:04:30 -0800753#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800754 if (capture_nonlocked_.beamformer_enabled !=
755 config.Get<Beamforming>().enabled) {
756 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800757 if (config.Get<Beamforming>().array_geometry.size() > 1) {
758 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
759 }
760 capture_.target_direction = config.Get<Beamforming>().target_direction;
761 InitializeBeamformer();
762 }
763#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000764}
765
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000766int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800767 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700768 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000769}
770
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000771int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800772 // Used as callback from submodules, hence locking is not allowed.
773 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000774}
775
Peter Kasting69558702016-01-12 16:26:35 -0800776size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800777 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700778 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000779}
780
Peter Kasting69558702016-01-12 16:26:35 -0800781size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800782 // Used as callback from submodules, hence locking is not allowed.
783 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000784}
785
Peter Kasting69558702016-01-12 16:26:35 -0800786size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800787 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700788 return (capture_nonlocked_.beamformer_enabled ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200789 capture_nonlocked_.echo_controller_enabled)
peahedddac52017-05-16 01:08:58 -0700790 ? 1
791 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800792}
793
Peter Kasting69558702016-01-12 16:26:35 -0800794size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800795 // Used as callback from submodules, hence locking is not allowed.
796 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000797}
798
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000799void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800800 rtc::CritScope cs(&crit_capture_);
801 capture_.output_will_be_muted = muted;
802 if (private_submodules_->agc_manager.get()) {
803 private_submodules_->agc_manager->SetCaptureMuted(
804 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000805 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000806}
807
Alessio Bazzicac054e782018-04-16 12:10:09 +0200808void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
809 RTC_DCHECK(setting.type() != RuntimeSetting::Type::kNotSpecified);
810 runtime_settings_enqueuer_.Enqueue(setting);
811}
812
813AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
814 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200815 : runtime_settings_(*runtime_settings) {
816 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200817}
818
819AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
820 default;
821
822void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
823 RuntimeSetting setting) {
824 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200825 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200826 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200827 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200828 RTC_LOG(LS_ERROR)
829 << "The runtime settings queue is full. Oldest setting discarded.";
830 }
831 if (remaining_attempts == 0)
832 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
833}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000834
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000835int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700836 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000837 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000838 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000839 int output_sample_rate_hz,
840 ChannelLayout output_layout,
841 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800842 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800843 StreamConfig input_stream;
844 StreamConfig output_stream;
845 {
846 // Access the formats_.api_format.input_stream beneath the capture lock.
847 // The lock must be released as it is later required in the call
848 // to ProcessStream(,,,);
849 rtc::CritScope cs(&crit_capture_);
850 input_stream = formats_.api_format.input_stream();
851 output_stream = formats_.api_format.output_stream();
852 }
853
Michael Graczyk86c6d332015-07-23 11:41:39 -0700854 input_stream.set_sample_rate_hz(input_sample_rate_hz);
855 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
856 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700857 output_stream.set_sample_rate_hz(output_sample_rate_hz);
858 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
859 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
860
861 if (samples_per_channel != input_stream.num_frames()) {
862 return kBadDataLengthError;
863 }
864 return ProcessStream(src, input_stream, output_stream, dest);
865}
866
867int AudioProcessingImpl::ProcessStream(const float* const* src,
868 const StreamConfig& input_config,
869 const StreamConfig& output_config,
870 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800871 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800872 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700873 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800874 {
875 // Acquire the capture lock in order to safely call the function
876 // that retrieves the render side data. This function accesses apm
877 // getters that need the capture lock held when being called.
878 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700879 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800880
881 if (!src || !dest) {
882 return kNullPointerError;
883 }
884
885 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700886 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000887 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000888
Michael Graczyk86c6d332015-07-23 11:41:39 -0700889 processing_config.input_stream() = input_config;
890 processing_config.output_stream() = output_config;
891
peahdf3efa82015-11-28 12:35:15 -0800892 {
893 // Do conditional reinitialization.
894 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700895 RETURN_ON_ERR(
896 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800897 }
898 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700899 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
900 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000901
aleloi868f32f2017-05-23 07:20:05 -0700902 if (aec_dump_) {
903 RecordUnprocessedCaptureStream(src);
904 }
905
peahdf3efa82015-11-28 12:35:15 -0800906 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700907 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800908 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000909
aleloi868f32f2017-05-23 07:20:05 -0700910 if (aec_dump_) {
911 RecordProcessedCaptureStream(dest);
912 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000913 return kNoError;
914}
915
Alessio Bazzicac054e782018-04-16 12:10:09 +0200916void AudioProcessingImpl::HandleRuntimeSettings() {
917 RuntimeSetting setting;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200918 while (runtime_settings_.Remove(&setting)) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200919 switch (setting.type()) {
920 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200921 if (config_.pre_amplifier.enabled) {
922 float value;
923 setting.GetFloat(&value);
924 private_submodules_->pre_amplifier->SetGainFactor(value);
925 }
926 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200927 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200928 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200929 RTC_NOTREACHED();
930 break;
931 }
932 }
933}
934
peah9e6a2902017-05-15 07:19:21 -0700935void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700936 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
937 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700938 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700939
kwibergaf476c72016-11-28 15:21:39 -0800940 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700941
942 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700943 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700944 // The data queue is full and needs to be emptied.
945 EmptyQueuedRenderAudio();
946
947 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700948 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700949 RTC_DCHECK(result);
950 }
951
952 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
953 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700954 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700955
956 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700957 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700958 // The data queue is full and needs to be emptied.
959 EmptyQueuedRenderAudio();
960
961 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700962 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700963 RTC_DCHECK(result);
964 }
peah701d6282016-10-25 05:42:20 -0700965
966 if (!constants_.use_experimental_agc) {
967 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
968 // Insert the samples into the queue.
969 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
970 // The data queue is full and needs to be emptied.
971 EmptyQueuedRenderAudio();
972
973 // Retry the insert (should always work).
974 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
975 RTC_DCHECK(result);
976 }
977 }
peah9e6a2902017-05-15 07:19:21 -0700978}
ivoc9f4a4a02016-10-28 05:39:16 -0700979
peah9e6a2902017-05-15 07:19:21 -0700980void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700981 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
982
983 // Insert the samples into the queue.
984 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
985 // The data queue is full and needs to be emptied.
986 EmptyQueuedRenderAudio();
987
988 // Retry the insert (should always work).
989 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
990 RTC_DCHECK(result);
991 }
peah764e3642016-10-22 05:04:30 -0700992}
993
994void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700995 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700996 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700997 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700998 EchoCancellationImpl::NumCancellersRequired(
999 num_output_channels(), num_reverse_channels()));
1000
peah701d6282016-10-25 05:42:20 -07001001 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001002 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001003 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001004 EchoControlMobileImpl::NumCancellersRequired(
1005 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001006
peah701d6282016-10-25 05:42:20 -07001007 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001008 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001009
ivoc9f4a4a02016-10-28 05:39:16 -07001010 const size_t new_red_render_queue_element_max_size =
1011 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1012
peaha0624602016-10-25 04:45:24 -07001013 // Reallocate the queues if the queue item sizes are too small to fit the
1014 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001015 if (aec_render_queue_element_max_size_ <
1016 new_aec_render_queue_element_max_size) {
1017 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001018
peaha0624602016-10-25 04:45:24 -07001019 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001020 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001021
peah701d6282016-10-25 05:42:20 -07001022 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001023 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1024 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001025 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001026 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001027
peah701d6282016-10-25 05:42:20 -07001028 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1029 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001030 } else {
peah701d6282016-10-25 05:42:20 -07001031 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001032 }
1033
peah701d6282016-10-25 05:42:20 -07001034 if (aecm_render_queue_element_max_size_ <
1035 new_aecm_render_queue_element_max_size) {
1036 aecm_render_queue_element_max_size_ =
1037 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001038
1039 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001040 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001041
peah701d6282016-10-25 05:42:20 -07001042 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001043 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1044 kMaxNumFramesToBuffer, template_queue_element,
1045 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001046 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001047
peah701d6282016-10-25 05:42:20 -07001048 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1049 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001050 } else {
peah701d6282016-10-25 05:42:20 -07001051 aecm_render_signal_queue_->Clear();
1052 }
1053
1054 if (agc_render_queue_element_max_size_ <
1055 new_agc_render_queue_element_max_size) {
1056 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1057
1058 std::vector<int16_t> template_queue_element(
1059 agc_render_queue_element_max_size_);
1060
1061 agc_render_signal_queue_.reset(
1062 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1063 kMaxNumFramesToBuffer, template_queue_element,
1064 RenderQueueItemVerifier<int16_t>(
1065 agc_render_queue_element_max_size_)));
1066
1067 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1068 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1069 } else {
1070 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001071 }
ivoc9f4a4a02016-10-28 05:39:16 -07001072
1073 if (red_render_queue_element_max_size_ <
1074 new_red_render_queue_element_max_size) {
1075 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1076
1077 std::vector<float> template_queue_element(
1078 red_render_queue_element_max_size_);
1079
1080 red_render_signal_queue_.reset(
1081 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1082 kMaxNumFramesToBuffer, template_queue_element,
1083 RenderQueueItemVerifier<float>(
1084 red_render_queue_element_max_size_)));
1085
1086 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1087 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1088 } else {
1089 red_render_signal_queue_->Clear();
1090 }
peah764e3642016-10-22 05:04:30 -07001091}
1092
1093void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1094 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001095 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001096 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001097 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001098 }
1099
peah701d6282016-10-25 05:42:20 -07001100 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001101 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001102 aecm_capture_queue_buffer_);
1103 }
1104
1105 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1106 public_submodules_->gain_control->ProcessRenderAudio(
1107 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001108 }
ivoc9f4a4a02016-10-28 05:39:16 -07001109
1110 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001111 RTC_DCHECK(private_submodules_->echo_detector);
1112 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001113 red_capture_queue_buffer_);
1114 }
peah764e3642016-10-22 05:04:30 -07001115}
1116
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001117int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001118 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001119 {
1120 // Acquire the capture lock in order to safely call the function
1121 // that retrieves the render side data. This function accesses apm
1122 // getters that need the capture lock held when being called.
1123 // The lock needs to be released as
1124 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1125 // as well.
1126 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001127 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001128 }
peahfa6228e2015-11-16 16:27:42 -08001129
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001130 if (!frame) {
1131 return kNullPointerError;
1132 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001133 // Must be a native rate.
1134 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1135 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001136 frame->sample_rate_hz_ != kSampleRate32kHz &&
1137 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001138 return kBadSampleRateError;
1139 }
peah192164e2015-11-17 02:16:45 -08001140
peahdf3efa82015-11-28 12:35:15 -08001141 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001142 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001143 {
1144 // Aquire lock for the access of api_format.
1145 // The lock is released immediately due to the conditional
1146 // reinitialization.
1147 rtc::CritScope cs_capture(&crit_capture_);
1148 // TODO(ajm): The input and output rates and channels are currently
1149 // constrained to be identical in the int16 interface.
1150 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001151
1152 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001153 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001154 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1155 processing_config.input_stream().set_num_channels(frame->num_channels_);
1156 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1157 processing_config.output_stream().set_num_channels(frame->num_channels_);
1158
peahdf3efa82015-11-28 12:35:15 -08001159 {
1160 // Do conditional reinitialization.
1161 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001162 RETURN_ON_ERR(
1163 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001164 }
1165 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001166 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001167 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001168 return kBadDataLengthError;
1169 }
1170
aleloi868f32f2017-05-23 07:20:05 -07001171 if (aec_dump_) {
1172 RecordUnprocessedCaptureStream(*frame);
1173 }
1174
peahdf3efa82015-11-28 12:35:15 -08001175 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001176 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001177 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001178 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1179 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001180
aleloi868f32f2017-05-23 07:20:05 -07001181 if (aec_dump_) {
1182 RecordProcessedCaptureStream(*frame);
1183 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001184
1185 return kNoError;
1186}
1187
peahde65ddc2016-09-16 15:02:15 -07001188int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001189 HandleRuntimeSettings();
1190
peahb58a1582016-03-15 09:34:24 -07001191 // Ensure that not both the AEC and AECM are active at the same time.
1192 // TODO(peah): Simplify once the public API Enable functions for these
1193 // are moved to APM.
1194 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1195 public_submodules_->echo_control_mobile->is_enabled()));
1196
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001197 MaybeUpdateHistograms();
1198
peahde65ddc2016-09-16 15:02:15 -07001199 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001200
Alex Loikob5c9a792018-04-16 16:31:22 +02001201 if (private_submodules_->pre_amplifier) {
1202 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1203 capture_buffer->channels_f(), capture_buffer->num_channels(),
1204 capture_buffer->num_frames()));
1205 }
1206
peah1b08dc32016-12-20 13:45:58 -08001207 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001208 capture_buffer->channels_const()[0],
1209 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001210 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1211 if (log_rms) {
1212 capture_rms_interval_counter_ = 0;
1213 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001214 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1215 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1216 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1217 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001218 }
1219
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001220 if (private_submodules_->echo_controller) {
Per Åhgren9aed31c2017-06-29 20:23:27 +02001221 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1222 // issues have been addressed.
1223 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001224 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001225 }
1226
peahbe615622016-02-13 16:40:47 -08001227 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001228 public_submodules_->gain_control->is_enabled()) {
1229 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001230 capture_buffer->channels()[0], capture_buffer->num_channels(),
1231 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001232 }
1233
peah2ace3f92016-09-10 04:42:27 -07001234 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1235 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001236 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1237 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001238 }
1239
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001240 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001241 // Force down-mixing of the number of channels after the detection of
1242 // capture signal saturation.
1243 // TODO(peah): Look into ensuring that this kind of tampering with the
1244 // AudioBuffer functionality should not be needed.
1245 capture_buffer->set_num_channels(1);
1246 }
1247
aluebsb2328d12016-01-11 20:32:29 -08001248 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001249 private_submodules_->beamformer->AnalyzeChunk(
1250 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001251 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001252 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001253 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001254
peahe0eae3c2016-12-14 01:16:23 -08001255 // TODO(peah): Move the AEC3 low-cut filter to this place.
1256 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001257 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001258 private_submodules_->low_cut_filter->Process(capture_buffer);
1259 }
peahde65ddc2016-09-16 15:02:15 -07001260 RETURN_ON_ERR(
1261 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1262 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001263
1264 // Ensure that the stream delay was set before the call to the
1265 // AEC ProcessCaptureAudio function.
1266 if (public_submodules_->echo_cancellation->is_enabled() &&
Per Åhgren0dfd3722018-05-06 18:16:01 +02001267 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001268 return AudioProcessing::kStreamParameterNotSetError;
1269 }
1270
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001271 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001272 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1273
Per Åhgrend0fa8202018-04-18 09:35:13 +02001274 if (was_stream_delay_set()) {
1275 private_submodules_->echo_controller->SetAudioBufferDelay(
1276 stream_delay_ms());
1277 }
1278
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001279 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001280 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001281 } else {
1282 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1283 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001284 }
1285
peahdf3efa82015-11-28 12:35:15 -08001286 if (public_submodules_->echo_control_mobile->is_enabled() &&
1287 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001288 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001289 }
peahde65ddc2016-09-16 15:02:15 -07001290 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001291#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001292 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001293 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001294 const int gain_db =
1295 public_submodules_->gain_control->is_enabled()
1296 ? public_submodules_->gain_control->compression_gain_db()
1297 : 0;
1298 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001299 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001300 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001301 }
peah1bcfce52016-08-26 07:16:04 -07001302#endif
peah253534d2016-03-15 04:32:28 -07001303
1304 // Ensure that the stream delay was set before the call to the
1305 // AECM ProcessCaptureAudio function.
1306 if (public_submodules_->echo_control_mobile->is_enabled() &&
1307 !was_stream_delay_set()) {
1308 return AudioProcessing::kStreamParameterNotSetError;
1309 }
1310
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001311 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001312 public_submodules_->echo_cancellation->is_enabled())) {
1313 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1314 capture_buffer, stream_delay_ms()));
1315 }
ivoc9f4a4a02016-10-28 05:39:16 -07001316
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001317 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001318 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001319 }
1320
peahde65ddc2016-09-16 15:02:15 -07001321 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001322
peahbe615622016-02-13 16:40:47 -08001323 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001324 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001325 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001326 private_submodules_->beamformer->is_target_present())) {
1327 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001328 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1329 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001330 }
peahb8fbb542016-03-15 02:28:08 -07001331 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001332 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001333
peah2ace3f92016-09-10 04:42:27 -07001334 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1335 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001336 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1337 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001338 }
1339
peah9e6a2902017-05-15 07:19:21 -07001340 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001341 RTC_DCHECK(private_submodules_->echo_detector);
1342 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001343 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1344 capture_buffer->num_frames()));
1345 }
1346
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001347 // TODO(aluebs): Investigate if the transient suppression placement should be
1348 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001349 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001350 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001351 private_submodules_->agc_manager.get()
1352 ? private_submodules_->agc_manager->voice_probability()
1353 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001354
peahdf3efa82015-11-28 12:35:15 -08001355 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001356 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1357 capture_buffer->num_channels(),
1358 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1359 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1360 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001361 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001362 }
1363
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001364 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001365 private_submodules_->gain_controller2->Process(capture_buffer);
1366 }
1367
Sam Zackrisson0beac582017-09-25 12:04:02 +02001368 if (private_submodules_->capture_post_processor) {
1369 private_submodules_->capture_post_processor->Process(capture_buffer);
1370 }
1371
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001372 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001373 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001374
peah1b08dc32016-12-20 13:45:58 -08001375 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1376 capture_buffer->channels_const()[0],
1377 capture_nonlocked_.capture_processing_format.num_frames()));
1378 if (log_rms) {
1379 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1380 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1381 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1382 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1383 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1384 }
1385
peahdf3efa82015-11-28 12:35:15 -08001386 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001387 return kNoError;
1388}
1389
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001390int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001391 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001392 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001393 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001394 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001395 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001396 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001397 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001398 };
1399 if (samples_per_channel != reverse_config.num_frames()) {
1400 return kBadDataLengthError;
1401 }
peahdf3efa82015-11-28 12:35:15 -08001402 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001403}
1404
peahde65ddc2016-09-16 15:02:15 -07001405int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1406 const StreamConfig& input_config,
1407 const StreamConfig& output_config,
1408 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001409 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001410 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001411 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001412 if (submodule_states_.RenderMultiBandProcessingActive() ||
1413 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001414 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1415 dest);
peah2ace3f92016-09-10 04:42:27 -07001416 } else if (formats_.api_format.reverse_input_stream() !=
1417 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001418 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1419 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001420 } else {
peahde65ddc2016-09-16 15:02:15 -07001421 CopyAudioIfNeeded(src, input_config.num_frames(),
1422 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001423 }
1424
1425 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001426}
1427
peahdf3efa82015-11-28 12:35:15 -08001428int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001429 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001430 const StreamConfig& input_config,
1431 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001432 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001433 return kNullPointerError;
1434 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001435
peahde65ddc2016-09-16 15:02:15 -07001436 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001437 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001438 }
1439
peahdf3efa82015-11-28 12:35:15 -08001440 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001441 processing_config.reverse_input_stream() = input_config;
1442 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001443
peahdf3efa82015-11-28 12:35:15 -08001444 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001445 RTC_DCHECK_EQ(input_config.num_frames(),
1446 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001447
aleloi868f32f2017-05-23 07:20:05 -07001448 if (aec_dump_) {
1449 const size_t channel_size =
1450 formats_.api_format.reverse_input_stream().num_frames();
1451 const size_t num_channels =
1452 formats_.api_format.reverse_input_stream().num_channels();
1453 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001454 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001455 }
peahdf3efa82015-11-28 12:35:15 -08001456 render_.render_audio->CopyFrom(src,
1457 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001458 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001459}
1460
1461int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001462 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001463 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001464 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001465 return kNullPointerError;
1466 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001467 // Must be a native rate.
1468 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1469 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001470 frame->sample_rate_hz_ != kSampleRate32kHz &&
1471 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001472 return kBadSampleRateError;
1473 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001474
Michael Graczyk86c6d332015-07-23 11:41:39 -07001475 if (frame->num_channels_ <= 0) {
1476 return kBadNumberChannelsError;
1477 }
1478
peahdf3efa82015-11-28 12:35:15 -08001479 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001480 processing_config.reverse_input_stream().set_sample_rate_hz(
1481 frame->sample_rate_hz_);
1482 processing_config.reverse_input_stream().set_num_channels(
1483 frame->num_channels_);
1484 processing_config.reverse_output_stream().set_sample_rate_hz(
1485 frame->sample_rate_hz_);
1486 processing_config.reverse_output_stream().set_num_channels(
1487 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001488
peahdf3efa82015-11-28 12:35:15 -08001489 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001490 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001491 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001492 return kBadDataLengthError;
1493 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001494
aleloi868f32f2017-05-23 07:20:05 -07001495 if (aec_dump_) {
1496 aec_dump_->WriteRenderStreamMessage(*frame);
1497 }
1498
peahdf3efa82015-11-28 12:35:15 -08001499 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001500 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001501 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001502 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1503 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001504 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001505}
niklase@google.com470e71d2011-07-07 08:21:25 +00001506
peahde65ddc2016-09-16 15:02:15 -07001507int AudioProcessingImpl::ProcessRenderStreamLocked() {
1508 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001509
1510 QueueNonbandedRenderAudio(render_buffer);
1511
Alex Loiko5825aa62017-12-18 16:02:40 +01001512 if (private_submodules_->render_pre_processor) {
1513 private_submodules_->render_pre_processor->Process(render_buffer);
1514 }
1515
peah2ace3f92016-09-10 04:42:27 -07001516 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001517 SampleRateSupportsMultiBand(
1518 formats_.render_processing_format.sample_rate_hz())) {
1519 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001520 }
1521
peah1bcfce52016-08-26 07:16:04 -07001522#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001523 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001524 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001525 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001526 }
peah1bcfce52016-08-26 07:16:04 -07001527#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001528
peahce4d9152017-05-19 01:28:05 -07001529 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1530 QueueBandedRenderAudio(render_buffer);
1531 }
1532
peahe0eae3c2016-12-14 01:16:23 -08001533 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001534 if (private_submodules_->echo_controller) {
1535 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001536 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001537
peah2ace3f92016-09-10 04:42:27 -07001538 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001539 SampleRateSupportsMultiBand(
1540 formats_.render_processing_format.sample_rate_hz())) {
1541 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001542 }
1543
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001544 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001545}
1546
1547int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001548 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001549 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001550 capture_.was_stream_delay_set = true;
1551 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001552
niklase@google.com470e71d2011-07-07 08:21:25 +00001553 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001554 delay = 0;
1555 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001556 }
1557
1558 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1559 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001560 delay = 500;
1561 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001562 }
1563
peahdf3efa82015-11-28 12:35:15 -08001564 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001565 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001566}
1567
1568int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001569 // Used as callback from submodules, hence locking is not allowed.
1570 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001571}
1572
1573bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001574 // Used as callback from submodules, hence locking is not allowed.
1575 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001576}
1577
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001578void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001579 rtc::CritScope cs(&crit_capture_);
1580 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001581}
1582
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001583void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001584 rtc::CritScope cs(&crit_capture_);
1585 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001586}
1587
1588int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001589 rtc::CritScope cs(&crit_capture_);
1590 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001591}
1592
aleloi868f32f2017-05-23 07:20:05 -07001593void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1594 RTC_DCHECK(aec_dump);
1595 rtc::CritScope cs_render(&crit_render_);
1596 rtc::CritScope cs_capture(&crit_capture_);
1597
1598 // The previously attached AecDump will be destroyed with the
1599 // 'aec_dump' parameter, which is after locks are released.
1600 aec_dump_.swap(aec_dump);
1601 WriteAecDumpConfigMessage(true);
1602 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1603}
1604
1605void AudioProcessingImpl::DetachAecDump() {
1606 // The d-tor of a task-queue based AecDump blocks until all pending
1607 // tasks are done. This construction avoids blocking while holding
1608 // the render and capture locks.
1609 std::unique_ptr<AecDump> aec_dump = nullptr;
1610 {
1611 rtc::CritScope cs_render(&crit_render_);
1612 rtc::CritScope cs_capture(&crit_capture_);
1613 aec_dump = std::move(aec_dump_);
1614 }
1615}
1616
Sam Zackrisson4d364492018-03-02 16:03:21 +01001617void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1618 std::unique_ptr<AudioGenerator> audio_generator) {
1619 // TODO(bugs.webrtc.org/8882) Stub.
1620 // Reset internal audio generator with audio_generator.
1621}
1622
1623void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1624 // TODO(bugs.webrtc.org/8882) Stub.
1625 // Delete audio generator, if one is attached.
1626}
1627
ivoc4e477a12017-01-15 08:29:46 -08001628AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1629 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1630 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1631 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1632 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1633}
1634
1635AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1636 const AudioProcessingStatistics& other) = default;
1637
1638AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1639 default;
1640
ivoc3e9a5372016-10-28 07:55:33 -07001641// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1642AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1643 const {
1644 return AudioProcessingStatistics();
1645}
1646
Ivo Creusenae026092017-11-20 13:07:16 +01001647// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001648AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001649 bool has_remote_tracks) const {
1650 return AudioProcessingStats();
1651}
1652
ivoc3e9a5372016-10-28 07:55:33 -07001653AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1654 const {
1655 AudioProcessingStatistics stats;
1656 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001657 if (private_submodules_->echo_controller) {
1658 rtc::CritScope cs_capture(&crit_capture_);
1659 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1660 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1661 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1662 // Instant value will also be used for min, max and average.
1663 stats.echo_return_loss.Set(erl, erl, erl, erl);
1664 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1665 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1666 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001667 stats.a_nlp.Set(metrics.a_nlp);
1668 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1669 stats.echo_return_loss.Set(metrics.echo_return_loss);
1670 stats.echo_return_loss_enhancement.Set(
1671 metrics.echo_return_loss_enhancement);
1672 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1673 }
ivoc9c192b22017-03-16 04:22:14 -07001674 {
1675 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001676 RTC_DCHECK(private_submodules_->echo_detector);
1677 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1678 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001679 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001680 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001681 }
ivoc3e9a5372016-10-28 07:55:33 -07001682 public_submodules_->echo_cancellation->GetDelayMetrics(
1683 &stats.delay_median, &stats.delay_standard_deviation,
1684 &stats.fraction_poor_delays);
1685 return stats;
1686}
1687
Ivo Creusen56d46092017-11-24 17:29:59 +01001688AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001689 bool has_remote_tracks) const {
1690 AudioProcessingStats stats;
1691 if (has_remote_tracks) {
1692 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001693 if (private_submodules_->echo_controller) {
1694 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001695 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1696 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001697 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001698 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001699 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001700 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1701 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001702 if (metrics.divergent_filter_fraction != -1.0f) {
1703 stats.divergent_filter_fraction =
1704 rtc::Optional<double>(metrics.divergent_filter_fraction);
1705 }
1706 if (metrics.echo_return_loss.instant != -100) {
1707 stats.echo_return_loss =
1708 rtc::Optional<double>(metrics.echo_return_loss.instant);
1709 }
1710 if (metrics.echo_return_loss_enhancement.instant != -100) {
1711 stats.echo_return_loss_enhancement =
1712 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1713 }
1714 }
1715 if (config_.residual_echo_detector.enabled) {
1716 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001717 RTC_DCHECK(private_submodules_->echo_detector);
1718 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1719 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001720 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001721 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001722 }
1723 int delay_median, delay_std;
1724 float fraction_poor_delays;
1725 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1726 &delay_median, &delay_std, &fraction_poor_delays) ==
1727 Error::kNoError) {
1728 if (delay_median >= 0) {
1729 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1730 }
1731 if (delay_std >= 0) {
1732 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1733 }
1734 }
1735 }
1736 return stats;
1737}
1738
niklase@google.com470e71d2011-07-07 08:21:25 +00001739EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001740 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001741}
1742
1743EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001744 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001745}
1746
1747GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001748 if (constants_.use_experimental_agc) {
1749 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001750 }
peahbfa97112016-03-10 21:09:04 -08001751 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001752}
1753
1754HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001755 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001756}
1757
1758LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001759 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001760}
1761
1762NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001763 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001764}
1765
1766VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001767 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001768}
1769
peah8271d042016-11-22 07:24:52 -08001770void AudioProcessingImpl::MutateConfig(
1771 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1772 rtc::CritScope cs_render(&crit_render_);
1773 rtc::CritScope cs_capture(&crit_capture_);
1774 mutator(&config_);
1775 ApplyConfig(config_);
1776}
1777
1778AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1779 rtc::CritScope cs_render(&crit_render_);
1780 rtc::CritScope cs_capture(&crit_capture_);
1781 return config_;
1782}
1783
peah2ace3f92016-09-10 04:42:27 -07001784bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1785 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001786 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001787 public_submodules_->echo_cancellation->is_enabled(),
1788 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001789 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001790 public_submodules_->noise_suppression->is_enabled(),
1791 capture_nonlocked_.intelligibility_enabled,
1792 capture_nonlocked_.beamformer_enabled,
1793 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001794 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001795 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001796 public_submodules_->voice_detection->is_enabled(),
1797 public_submodules_->level_estimator->is_enabled(),
1798 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001799}
1800
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001801
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001802void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001803 if (capture_.transient_suppressor_enabled) {
1804 if (!public_submodules_->transient_suppressor.get()) {
1805 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001806 }
peahdf3efa82015-11-28 12:35:15 -08001807 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001808 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1809 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001810 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001811}
1812
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001813void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001814 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001815 if (!private_submodules_->beamformer) {
1816 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001817 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001818 }
peahdf3efa82015-11-28 12:35:15 -08001819 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1820 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001821 }
1822}
1823
ekmeyerson60d9b332015-08-14 10:35:55 -07001824void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001825#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001826 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001827 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001828 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001829 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001830 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001831 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001832 }
peah1bcfce52016-08-26 07:16:04 -07001833#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001834}
1835
peah8271d042016-11-22 07:24:52 -08001836void AudioProcessingImpl::InitializeLowCutFilter() {
1837 if (config_.high_pass_filter.enabled) {
1838 private_submodules_->low_cut_filter.reset(
1839 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1840 } else {
1841 private_submodules_->low_cut_filter.reset();
1842 }
1843}
alessiob3ec96df2017-05-22 06:57:06 -07001844
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001845void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001846 if (echo_control_factory_) {
1847 private_submodules_->echo_controller =
1848 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001849 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001850 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001851 }
1852}
peah8271d042016-11-22 07:24:52 -08001853
alessiob3ec96df2017-05-22 06:57:06 -07001854void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001855 if (config_.gain_controller2.enabled) {
1856 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001857 }
1858}
1859
Alex Loikob5c9a792018-04-16 16:31:22 +02001860void AudioProcessingImpl::InitializePreAmplifier() {
1861 if (config_.pre_amplifier.enabled) {
1862 private_submodules_->pre_amplifier.reset(
1863 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1864 } else {
1865 private_submodules_->pre_amplifier.reset();
1866 }
1867}
1868
ivoc9f4a4a02016-10-28 05:39:16 -07001869void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001870 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001871 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001872 proc_sample_rate_hz(), 1,
1873 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001874}
1875
Sam Zackrisson0beac582017-09-25 12:04:02 +02001876void AudioProcessingImpl::InitializePostProcessor() {
1877 if (private_submodules_->capture_post_processor) {
1878 private_submodules_->capture_post_processor->Initialize(
1879 proc_sample_rate_hz(), num_proc_channels());
1880 }
1881}
1882
Alex Loiko5825aa62017-12-18 16:02:40 +01001883void AudioProcessingImpl::InitializePreProcessor() {
1884 if (private_submodules_->render_pre_processor) {
1885 private_submodules_->render_pre_processor->Initialize(
1886 formats_.render_processing_format.sample_rate_hz(),
1887 formats_.render_processing_format.num_channels());
1888 }
1889}
1890
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001891void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001892 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001893
1894 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001895 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001896 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001897 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001898 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001899 capture_.stream_delay_jumps = 0;
1900 }
1901 if (capture_.aec_system_delay_jumps == -1 &&
1902 echo_cancellation()->stream_has_echo()) {
1903 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001904 }
1905
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001906 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001907 const int diff_stream_delay_ms =
1908 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1909 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1910 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001911 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1912 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001913 if (capture_.stream_delay_jumps == -1) {
1914 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001915 }
peahdf3efa82015-11-28 12:35:15 -08001916 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001917 }
peahdf3efa82015-11-28 12:35:15 -08001918 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001919
1920 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001921 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001922 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001923 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001924 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001925 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1926 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001927 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001928 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001929 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001930 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001931 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1932 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1933 100);
peahdf3efa82015-11-28 12:35:15 -08001934 if (capture_.aec_system_delay_jumps == -1) {
1935 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001936 }
peahdf3efa82015-11-28 12:35:15 -08001937 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001938 }
peahdf3efa82015-11-28 12:35:15 -08001939 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001940 }
1941}
1942
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001943void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001944 // Run in a single-threaded manner.
1945 rtc::CritScope cs_render(&crit_render_);
1946 rtc::CritScope cs_capture(&crit_capture_);
1947
1948 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001949 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001950 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001951 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001952 }
peahdf3efa82015-11-28 12:35:15 -08001953 capture_.stream_delay_jumps = -1;
1954 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001955
peahdf3efa82015-11-28 12:35:15 -08001956 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001957 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1958 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001959 }
peahdf3efa82015-11-28 12:35:15 -08001960 capture_.aec_system_delay_jumps = -1;
1961 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001962}
1963
aleloi868f32f2017-05-23 07:20:05 -07001964void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1965 if (!aec_dump_) {
1966 return;
1967 }
1968 std::string experiments_description =
1969 public_submodules_->echo_cancellation->GetExperimentsDescription();
1970 // TODO(peah): Add semicolon-separated concatenations of experiment
1971 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001972 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1973 experiments_description += "AgcClippingLevelExperiment;";
1974 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001975 if (capture_nonlocked_.echo_controller_enabled) {
1976 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001977 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001978 if (config_.gain_controller2.enabled) {
1979 experiments_description += "GainController2;";
1980 }
aleloi868f32f2017-05-23 07:20:05 -07001981
1982 InternalAPMConfig apm_config;
1983
1984 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1985 apm_config.aec_delay_agnostic_enabled =
1986 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1987 apm_config.aec_drift_compensation_enabled =
1988 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1989 apm_config.aec_extended_filter_enabled =
1990 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1991 apm_config.aec_suppression_level = static_cast<int>(
1992 public_submodules_->echo_cancellation->suppression_level());
1993
1994 apm_config.aecm_enabled =
1995 public_submodules_->echo_control_mobile->is_enabled();
1996 apm_config.aecm_comfort_noise_enabled =
1997 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1998 apm_config.aecm_routing_mode =
1999 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
2000
2001 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2002 apm_config.agc_mode =
2003 static_cast<int>(public_submodules_->gain_control->mode());
2004 apm_config.agc_limiter_enabled =
2005 public_submodules_->gain_control->is_limiter_enabled();
2006 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2007
2008 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2009
2010 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2011 apm_config.ns_level =
2012 static_cast<int>(public_submodules_->noise_suppression->level());
2013
2014 apm_config.transient_suppression_enabled =
2015 capture_.transient_suppressor_enabled;
2016 apm_config.intelligibility_enhancer_enabled =
2017 capture_nonlocked_.intelligibility_enabled;
2018 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002019 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2020 apm_config.pre_amplifier_fixed_gain_factor =
2021 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002022
2023 if (!forced && apm_config == apm_config_for_aec_dump_) {
2024 return;
2025 }
2026 aec_dump_->WriteConfig(apm_config);
2027 apm_config_for_aec_dump_ = apm_config;
2028}
2029
2030void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2031 const float* const* src) {
2032 RTC_DCHECK(aec_dump_);
2033 WriteAecDumpConfigMessage(false);
2034
2035 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2036 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2037 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002038 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002039 RecordAudioProcessingState();
2040}
2041
2042void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2043 const AudioFrame& capture_frame) {
2044 RTC_DCHECK(aec_dump_);
2045 WriteAecDumpConfigMessage(false);
2046
2047 aec_dump_->AddCaptureStreamInput(capture_frame);
2048 RecordAudioProcessingState();
2049}
2050
2051void AudioProcessingImpl::RecordProcessedCaptureStream(
2052 const float* const* processed_capture_stream) {
2053 RTC_DCHECK(aec_dump_);
2054
2055 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2056 const size_t num_channels =
2057 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002058 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2059 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002060 aec_dump_->WriteCaptureStreamMessage();
2061}
2062
2063void AudioProcessingImpl::RecordProcessedCaptureStream(
2064 const AudioFrame& processed_capture_frame) {
2065 RTC_DCHECK(aec_dump_);
2066
2067 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2068 aec_dump_->WriteCaptureStreamMessage();
2069}
2070
2071void AudioProcessingImpl::RecordAudioProcessingState() {
2072 RTC_DCHECK(aec_dump_);
2073 AecDump::AudioProcessingState audio_proc_state;
2074 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2075 audio_proc_state.drift =
2076 public_submodules_->echo_cancellation->stream_drift_samples();
2077 audio_proc_state.level = gain_control()->stream_analog_level();
2078 audio_proc_state.keypress = capture_.key_pressed;
2079 aec_dump_->AddAudioProcessingState(audio_proc_state);
2080}
2081
kwiberg83ffe452016-08-29 14:46:07 -07002082AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2083 bool transient_suppressor_enabled,
2084 const std::vector<Point>& array_geometry,
2085 SphericalPointf target_direction)
2086 : aec_system_delay_jumps(-1),
2087 delay_offset_ms(0),
2088 was_stream_delay_set(false),
2089 last_stream_delay_ms(0),
2090 last_aec_system_delay_ms(0),
2091 stream_delay_jumps(-1),
2092 output_will_be_muted(false),
2093 key_pressed(false),
2094 transient_suppressor_enabled(transient_suppressor_enabled),
2095 array_geometry(array_geometry),
2096 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002097 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002098 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002099 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002100
2101AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2102
2103AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2104
2105AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2106
niklase@google.com470e71d2011-07-07 08:21:25 +00002107} // namespace webrtc