blob: 2c292f7a05305053407d91ef002d1b1d813bae04 [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"
23#include "modules/audio_processing/agc2/gain_controller2.h"
24#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"
Per Åhgren13735822018-02-12 21:42:56 +010031#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
33#include "rtc_base/logging.h"
34#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020035#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070037#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070039#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "modules/audio_processing/level_controller/level_controller.h"
41#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"
47#include "modules/include/module_common_types.h"
Per Åhgren13735822018-02-12 21:42:56 +010048#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "system_wrappers/include/file_wrapper.h"
50#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000051
peah1bcfce52016-08-26 07:16:04 -070052// Check to verify that the define for the intelligibility enhancer is properly
53// set.
54#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
55 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
56 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
57#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
58#endif
59
Michael Graczyk86c6d332015-07-23 11:41:39 -070060#define RETURN_ON_ERR(expr) \
61 do { \
62 int err = (expr); \
63 if (err != kNoError) { \
64 return err; \
65 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000066 } while (0)
67
niklase@google.com470e71d2011-07-07 08:21:25 +000068namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070069
kwibergd59d3bb2016-09-13 07:49:33 -070070constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070071
Michael Graczyk86c6d332015-07-23 11:41:39 -070072namespace {
73
74static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
75 switch (layout) {
76 case AudioProcessing::kMono:
77 case AudioProcessing::kStereo:
78 return false;
79 case AudioProcessing::kMonoAndKeyboard:
80 case AudioProcessing::kStereoAndKeyboard:
81 return true;
82 }
83
kwiberg9e2be5f2016-09-14 05:23:22 -070084 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070085 return false;
86}
aluebsdf6416a2016-03-16 18:26:35 -070087
peah2ace3f92016-09-10 04:42:27 -070088bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070089 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
90 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
91}
92
peah2ace3f92016-09-10 04:42:27 -070093int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
94#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070095 constexpr int kMaxSplittingNativeProcessRate =
96 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070097#else
kwibergd59d3bb2016-09-13 07:49:33 -070098 constexpr int kMaxSplittingNativeProcessRate =
99 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700100#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700101 static_assert(
102 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
103 "");
peah2ace3f92016-09-10 04:42:27 -0700104 const int uppermost_native_rate = band_splitting_required
105 ? kMaxSplittingNativeProcessRate
106 : AudioProcessing::kSampleRate48kHz;
107
108 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
109 if (rate >= uppermost_native_rate) {
110 return uppermost_native_rate;
111 }
112 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700113 return rate;
114 }
115 }
peah2ace3f92016-09-10 04:42:27 -0700116 RTC_NOTREACHED();
117 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700118}
119
peah9e6a2902017-05-15 07:19:21 -0700120// Maximum lengths that frame of samples being passed from the render side to
121// the capture side can have (does not apply to AEC3).
122static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
123static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
124
peah764e3642016-10-22 05:04:30 -0700125// Maximum number of frames to buffer in the render queue.
126// TODO(peah): Decrease this once we properly handle hugely unbalanced
127// reverse and forward call numbers.
128static const size_t kMaxNumFramesToBuffer = 100;
129
peah8271d042016-11-22 07:24:52 -0800130class HighPassFilterImpl : public HighPassFilter {
131 public:
132 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
133 ~HighPassFilterImpl() override = default;
134
135 // HighPassFilter implementation.
136 int Enable(bool enable) override {
137 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
138 config->high_pass_filter.enabled = enable;
139 });
140
141 return AudioProcessing::kNoError;
142 }
143
144 bool is_enabled() const override {
145 return apm_->GetConfig().high_pass_filter.enabled;
146 }
147
148 private:
149 AudioProcessingImpl* apm_;
150 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
151};
152
aleloi868f32f2017-05-23 07:20:05 -0700153webrtc::InternalAPMStreamsConfig ToStreamsConfig(
154 const ProcessingConfig& api_format) {
155 webrtc::InternalAPMStreamsConfig result;
156 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
157 result.input_num_channels = api_format.input_stream().num_channels();
158 result.output_num_channels = api_format.output_stream().num_channels();
159 result.render_input_num_channels =
160 api_format.reverse_input_stream().num_channels();
161 result.render_input_sample_rate =
162 api_format.reverse_input_stream().sample_rate_hz();
163 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
164 result.render_output_sample_rate =
165 api_format.reverse_output_stream().sample_rate_hz();
166 result.render_output_num_channels =
167 api_format.reverse_output_stream().num_channels();
168 return result;
169}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700170} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000171
172// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000173static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000174
Sam Zackrisson0beac582017-09-25 12:04:02 +0200175AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100176 bool capture_post_processor_enabled,
177 bool render_pre_processor_enabled)
178 : capture_post_processor_enabled_(capture_post_processor_enabled),
179 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700180
181bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800182 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700183 bool echo_canceller_enabled,
184 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700185 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700186 bool noise_suppressor_enabled,
187 bool intelligibility_enhancer_enabled,
188 bool beamformer_enabled,
189 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700190 bool gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -0700191 bool level_controller_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200192 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700193 bool voice_activity_detector_enabled,
194 bool level_estimator_enabled,
195 bool transient_suppressor_enabled) {
196 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800197 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700198 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
199 changed |=
200 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700201 changed |=
202 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700203 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
204 changed |=
205 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
206 changed |= (beamformer_enabled != beamformer_enabled_);
207 changed |=
208 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700209 changed |=
210 (gain_controller2_enabled != gain_controller2_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700211 changed |= (level_controller_enabled != level_controller_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200212 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700213 changed |= (level_estimator_enabled != level_estimator_enabled_);
214 changed |=
215 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
216 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
217 if (changed) {
peah8271d042016-11-22 07:24:52 -0800218 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700219 echo_canceller_enabled_ = echo_canceller_enabled;
220 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700221 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700222 noise_suppressor_enabled_ = noise_suppressor_enabled;
223 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
224 beamformer_enabled_ = beamformer_enabled;
225 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700226 gain_controller2_enabled_ = gain_controller2_enabled;
peah2ace3f92016-09-10 04:42:27 -0700227 level_controller_enabled_ = level_controller_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200228 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700229 level_estimator_enabled_ = level_estimator_enabled;
230 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
231 transient_suppressor_enabled_ = transient_suppressor_enabled;
232 }
233
234 changed |= first_update_;
235 first_update_ = false;
236 return changed;
237}
238
239bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
240 const {
241#if WEBRTC_INTELLIGIBILITY_ENHANCER
242 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700243 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700244#else
peah52775842017-05-16 06:14:09 -0700245 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700246#endif
247}
248
249bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
250 const {
peah8271d042016-11-22 07:24:52 -0800251 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700252 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800253 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200254 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700255}
256
peah23ac8b42017-05-23 05:33:56 -0700257bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
258 const {
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200259 return level_controller_enabled_ || gain_controller2_enabled_ ||
260 capture_post_processor_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700261}
262
peah2ace3f92016-09-10 04:42:27 -0700263bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
264 const {
265 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800266 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200267 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700268}
269
Alex Loiko5825aa62017-12-18 16:02:40 +0100270bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
271 const {
272 return render_pre_processor_enabled_;
273}
274
peah2ace3f92016-09-10 04:42:27 -0700275bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
276 const {
277#if WEBRTC_INTELLIGIBILITY_ENHANCER
278 return intelligibility_enhancer_enabled_;
279#else
280 return false;
281#endif
282}
283
solenberg5e465c32015-12-08 13:22:33 -0800284struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800285 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800286 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800287 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800288 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800289 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800290 std::unique_ptr<LevelEstimatorImpl> level_estimator;
291 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
292 std::unique_ptr<VoiceDetectionImpl> voice_detection;
293 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800294 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800295
296 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800297 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700298#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800299 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700300#endif
solenberg5e465c32015-12-08 13:22:33 -0800301};
302
303struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200304 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100305 std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100306 std::unique_ptr<CustomProcessing> render_pre_processor,
307 std::unique_ptr<EchoDetector> echo_detector)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200308 : beamformer(beamformer),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100309 echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100310 capture_post_processor(std::move(capture_post_processor)),
311 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800312 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700313 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800314 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700315 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800316 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700317 std::unique_ptr<LevelController> level_controller;
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100318 std::unique_ptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200319 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100320 std::unique_ptr<CustomProcessing> capture_post_processor;
321 std::unique_ptr<CustomProcessing> render_pre_processor;
solenberg5e465c32015-12-08 13:22:33 -0800322};
323
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100324AudioProcessingBuilder::AudioProcessingBuilder() = default;
325AudioProcessingBuilder::~AudioProcessingBuilder() = default;
326
327AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
328 std::unique_ptr<CustomProcessing> capture_post_processing) {
329 capture_post_processing_ = std::move(capture_post_processing);
330 return *this;
331}
332
333AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
334 std::unique_ptr<CustomProcessing> render_pre_processing) {
335 render_pre_processing_ = std::move(render_pre_processing);
336 return *this;
337}
338
339AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
340 std::unique_ptr<EchoControlFactory> echo_control_factory) {
341 echo_control_factory_ = std::move(echo_control_factory);
342 return *this;
343}
344
345AudioProcessingBuilder& AudioProcessingBuilder::SetNonlinearBeamformer(
346 std::unique_ptr<NonlinearBeamformer> nonlinear_beamformer) {
347 nonlinear_beamformer_ = std::move(nonlinear_beamformer);
348 return *this;
349}
350
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100351AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
352 std::unique_ptr<EchoDetector> echo_detector) {
353 echo_detector_ = std::move(echo_detector);
354 return *this;
355}
356
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100357AudioProcessing* AudioProcessingBuilder::Create() {
358 webrtc::Config config;
359 return Create(config);
360}
361
362AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100363 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
364 config, std::move(capture_post_processing_),
365 std::move(render_pre_processing_), std::move(echo_control_factory_),
366 std::move(echo_detector_), nonlinear_beamformer_.release());
367 if (apm->Initialize() != AudioProcessing::kNoError) {
368 delete apm;
369 apm = nullptr;
370 }
371 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100372}
373
peah88ac8532016-09-12 16:47:25 -0700374AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100375 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
376}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000377
Per Åhgren13735822018-02-12 21:42:56 +0100378int AudioProcessingImpl::instance_count_ = 0;
379
Sam Zackrisson0beac582017-09-25 12:04:02 +0200380AudioProcessingImpl::AudioProcessingImpl(
381 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100382 std::unique_ptr<CustomProcessing> capture_post_processor,
383 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200384 std::unique_ptr<EchoControlFactory> echo_control_factory,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100385 std::unique_ptr<EchoDetector> echo_detector,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200386 NonlinearBeamformer* beamformer)
Per Åhgren13735822018-02-12 21:42:56 +0100387 : data_dumper_(
388 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
389 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
peahc19f3122016-10-07 14:54:10 -0700443 // TODO(peah): Move this creation to happen only when the level controller
444 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700445 private_submodules_->level_controller.reset(new LevelController());
Sam Zackrisson0beac582017-09-25 12:04:02 +0200446
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200447 // TODO(alessiob): Move the injected gain controller once injection is
448 // implemented.
449 private_submodules_->gain_controller2.reset(new GainController2());
450
Mirko Bonadei675513b2017-11-09 11:09:25 +0100451 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100452 << !!private_submodules_->capture_post_processor
453 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100454 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800455 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000456
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000457 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000458}
459
460AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800461 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800462 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800463 private_submodules_->agc_manager.reset();
464 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800465 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000466}
467
niklase@google.com470e71d2011-07-07 08:21:25 +0000468int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800469 // Run in a single-threaded manner during initialization.
470 rtc::CritScope cs_render(&crit_render_);
471 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000472 return InitializeLocked();
473}
474
peahde65ddc2016-09-16 15:02:15 -0700475int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
476 int capture_output_sample_rate_hz,
477 int render_input_sample_rate_hz,
478 ChannelLayout capture_input_layout,
479 ChannelLayout capture_output_layout,
480 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700481 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700482 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
483 LayoutHasKeyboard(capture_input_layout)},
484 {capture_output_sample_rate_hz,
485 ChannelsFromLayout(capture_output_layout),
486 LayoutHasKeyboard(capture_output_layout)},
487 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
488 LayoutHasKeyboard(render_input_layout)},
489 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
490 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700491
492 return Initialize(processing_config);
493}
494
495int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800496 // Run in a single-threaded manner during initialization.
497 rtc::CritScope cs_render(&crit_render_);
498 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700499 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000500}
501
peahdf3efa82015-11-28 12:35:15 -0800502int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800503 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700504 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800505}
506
peahdf3efa82015-11-28 12:35:15 -0800507int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700508 const ProcessingConfig& processing_config,
509 bool force_initialization) {
510 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800511}
512
peah192164e2015-11-17 02:16:45 -0800513// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800514// their current values (needs to be called while holding the crit_render_lock).
515int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700516 const ProcessingConfig& processing_config,
517 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800518 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700519 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800520 return kNoError;
521 }
peahdf3efa82015-11-28 12:35:15 -0800522
523 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800524 return InitializeLocked(processing_config);
525}
526
niklase@google.com470e71d2011-07-07 08:21:25 +0000527int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200528 UpdateActiveSubmoduleStates();
529
peah522d71b2017-02-23 05:16:26 -0800530 const int capture_audiobuffer_num_channels =
531 capture_nonlocked_.beamformer_enabled
532 ? formats_.api_format.input_stream().num_channels()
533 : formats_.api_format.output_stream().num_channels();
534
peahde65ddc2016-09-16 15:02:15 -0700535 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800536 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700537 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800538 : formats_.api_format.reverse_output_stream().num_frames();
539 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
540 render_.render_audio.reset(new AudioBuffer(
541 formats_.api_format.reverse_input_stream().num_frames(),
542 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700543 formats_.render_processing_format.num_frames(),
544 formats_.render_processing_format.num_channels(),
545 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700546 if (formats_.api_format.reverse_input_stream() !=
547 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800548 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800549 formats_.api_format.reverse_input_stream().num_channels(),
550 formats_.api_format.reverse_input_stream().num_frames(),
551 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800552 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700553 } else {
peahdf3efa82015-11-28 12:35:15 -0800554 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700555 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700556 } else {
peahdf3efa82015-11-28 12:35:15 -0800557 render_.render_audio.reset(nullptr);
558 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700559 }
peahce4d9152017-05-19 01:28:05 -0700560
peahdf3efa82015-11-28 12:35:15 -0800561 capture_.capture_audio.reset(
562 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
563 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700564 capture_nonlocked_.capture_processing_format.num_frames(),
565 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800566 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000567
peahde65ddc2016-09-16 15:02:15 -0700568 public_submodules_->echo_cancellation->Initialize(
569 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
570 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700571 AllocateRenderQueue();
572
ivoc3e9a5372016-10-28 07:55:33 -0700573 int success = public_submodules_->echo_cancellation->enable_metrics(true);
574 RTC_DCHECK_EQ(0, success);
575 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
576 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700577 public_submodules_->echo_control_mobile->Initialize(
578 proc_split_sample_rate_hz(), num_reverse_channels(),
579 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700580
581 public_submodules_->gain_control->Initialize(num_proc_channels(),
582 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700583 if (constants_.use_experimental_agc) {
584 if (!private_submodules_->agc_manager.get()) {
585 private_submodules_->agc_manager.reset(new AgcManagerDirect(
586 public_submodules_->gain_control.get(),
587 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800588 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700589 }
590 private_submodules_->agc_manager->Initialize();
591 private_submodules_->agc_manager->SetCaptureMuted(
592 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700593 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700594 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200595 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000596 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700597#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700598 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700599#endif
peah8271d042016-11-22 07:24:52 -0800600 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700601 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
602 proc_sample_rate_hz());
603 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
604 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700605 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700606 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200607 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700608 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200609 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100610 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800611
aleloi868f32f2017-05-23 07:20:05 -0700612 if (aec_dump_) {
613 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
614 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000615 return kNoError;
616}
617
Michael Graczyk86c6d332015-07-23 11:41:39 -0700618int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200619 UpdateActiveSubmoduleStates();
620
Michael Graczyk86c6d332015-07-23 11:41:39 -0700621 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700622 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
623 return kBadSampleRateError;
624 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000625 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700626
Peter Kasting69558702016-01-12 16:26:35 -0800627 const size_t num_in_channels = config.input_stream().num_channels();
628 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700629
630 // Need at least one input channel.
631 // Need either one output channel or as many outputs as there are inputs.
632 if (num_in_channels == 0 ||
633 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700634 return kBadNumberChannelsError;
635 }
636
aluebsb2328d12016-01-11 20:32:29 -0800637 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800638 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700639 return kBadNumberChannelsError;
640 }
641
peahdf3efa82015-11-28 12:35:15 -0800642 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000643
peahde65ddc2016-09-16 15:02:15 -0700644 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700645 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700646 formats_.api_format.output_stream().sample_rate_hz()),
647 submodule_states_.CaptureMultiBandSubModulesActive() ||
648 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000649
peahde65ddc2016-09-16 15:02:15 -0700650 capture_nonlocked_.capture_processing_format =
651 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700652
peah2ce640f2017-04-07 03:57:48 -0700653 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200654 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700655 render_processing_rate = FindNativeProcessRateToUse(
656 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
657 formats_.api_format.reverse_output_stream().sample_rate_hz()),
658 submodule_states_.CaptureMultiBandSubModulesActive() ||
659 submodule_states_.RenderMultiBandSubModulesActive());
660 } else {
661 render_processing_rate = capture_processing_rate;
662 }
663
aluebseb3603b2016-04-20 15:27:58 -0700664 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
665 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700666 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200667 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700668 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
669 ? kSampleRate32kHz
670 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700671 }
peah2ce640f2017-04-07 03:57:48 -0700672
peahde65ddc2016-09-16 15:02:15 -0700673 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700674 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700675 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
676 kSampleRate8kHz) {
677 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000678 } else {
peahde65ddc2016-09-16 15:02:15 -0700679 render_processing_rate =
680 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000681 }
682
peahde65ddc2016-09-16 15:02:15 -0700683 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000684 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700685 if (submodule_states_.RenderMultiBandSubModulesActive()) {
686 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
687 } else {
688 formats_.render_processing_format = StreamConfig(
689 formats_.api_format.reverse_input_stream().sample_rate_hz(),
690 formats_.api_format.reverse_input_stream().num_channels());
691 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000692
peahde65ddc2016-09-16 15:02:15 -0700693 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
694 kSampleRate32kHz ||
695 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
696 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800697 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000698 } else {
peahdf3efa82015-11-28 12:35:15 -0800699 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700700 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000701 }
702
703 return InitializeLocked();
704}
705
peah88ac8532016-09-12 16:47:25 -0700706void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700707 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700708
peahc19f3122016-10-07 14:54:10 -0700709 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700710 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100711 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
712 "level_controller: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100713 << LevelController::ToString(config_.level_controller)
Jonas Olsson645b0272018-02-15 15:16:27 +0100714 << "\nReverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700715 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700716 }
717
718 // Run in a single-threaded manner when applying the settings.
719 rtc::CritScope cs_render(&crit_render_);
720 rtc::CritScope cs_capture(&crit_capture_);
721
peahc19f3122016-10-07 14:54:10 -0700722 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
723 // with the value in config_ everywhere in the code.
724 if (capture_nonlocked_.level_controller_enabled !=
725 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700726 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700727 config_.level_controller.enabled;
728 // TODO(peah): Remove the conditional initialization to always initialize
729 // the level controller regardless of whether it is enabled or not.
730 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700731 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100732 RTC_LOG(LS_INFO) << "Level controller activated: "
733 << capture_nonlocked_.level_controller_enabled;
peahc19f3122016-10-07 14:54:10 -0700734
735 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800736
737 InitializeLowCutFilter();
738
Mirko Bonadei675513b2017-11-09 11:09:25 +0100739 RTC_LOG(LS_INFO) << "Highpass filter activated: "
740 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800741
alessiob3ec96df2017-05-22 06:57:06 -0700742 config_ok = GainController2::Validate(config_.gain_controller2);
743 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100744 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
745 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100746 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100747 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700748 config_.gain_controller2 = AudioProcessing::Config::GainController2();
749 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200750 InitializeGainController2();
751 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100752 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
753 << config_.gain_controller2.enabled;
peah88ac8532016-09-12 16:47:25 -0700754}
755
756void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800757 // Run in a single-threaded manner when setting the extra options.
758 rtc::CritScope cs_render(&crit_render_);
759 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000760
peahb624d8c2016-03-05 03:01:14 -0800761 public_submodules_->echo_cancellation->SetExtraOptions(config);
762
peahdf3efa82015-11-28 12:35:15 -0800763 if (capture_.transient_suppressor_enabled !=
764 config.Get<ExperimentalNs>().enabled) {
765 capture_.transient_suppressor_enabled =
766 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000767 InitializeTransient();
768 }
aluebs2a346882016-01-11 18:04:30 -0800769
peah1bcfce52016-08-26 07:16:04 -0700770#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700771 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700772 config.Get<Intelligibility>().enabled) {
773 capture_nonlocked_.intelligibility_enabled =
774 config.Get<Intelligibility>().enabled;
775 InitializeIntelligibility();
776 }
peah1bcfce52016-08-26 07:16:04 -0700777#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700778
aluebs2a346882016-01-11 18:04:30 -0800779#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800780 if (capture_nonlocked_.beamformer_enabled !=
781 config.Get<Beamforming>().enabled) {
782 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800783 if (config.Get<Beamforming>().array_geometry.size() > 1) {
784 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
785 }
786 capture_.target_direction = config.Get<Beamforming>().target_direction;
787 InitializeBeamformer();
788 }
789#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000790}
791
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000792int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800793 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700794 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000795}
796
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000797int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800798 // Used as callback from submodules, hence locking is not allowed.
799 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000800}
801
Peter Kasting69558702016-01-12 16:26:35 -0800802size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800803 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700804 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000805}
806
Peter Kasting69558702016-01-12 16:26:35 -0800807size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800808 // Used as callback from submodules, hence locking is not allowed.
809 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000810}
811
Peter Kasting69558702016-01-12 16:26:35 -0800812size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800813 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700814 return (capture_nonlocked_.beamformer_enabled ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200815 capture_nonlocked_.echo_controller_enabled)
peahedddac52017-05-16 01:08:58 -0700816 ? 1
817 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800818}
819
Peter Kasting69558702016-01-12 16:26:35 -0800820size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800821 // Used as callback from submodules, hence locking is not allowed.
822 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000823}
824
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000825void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800826 rtc::CritScope cs(&crit_capture_);
827 capture_.output_will_be_muted = muted;
828 if (private_submodules_->agc_manager.get()) {
829 private_submodules_->agc_manager->SetCaptureMuted(
830 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000831 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000832}
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
peah9e6a2902017-05-15 07:19:21 -0700916void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700917 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
918 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700919 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700920
kwibergaf476c72016-11-28 15:21:39 -0800921 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700922
923 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700924 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700925 // The data queue is full and needs to be emptied.
926 EmptyQueuedRenderAudio();
927
928 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700929 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700930 RTC_DCHECK(result);
931 }
932
933 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
934 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700935 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700936
937 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700938 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700939 // The data queue is full and needs to be emptied.
940 EmptyQueuedRenderAudio();
941
942 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700943 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700944 RTC_DCHECK(result);
945 }
peah701d6282016-10-25 05:42:20 -0700946
947 if (!constants_.use_experimental_agc) {
948 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
949 // Insert the samples into the queue.
950 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
951 // The data queue is full and needs to be emptied.
952 EmptyQueuedRenderAudio();
953
954 // Retry the insert (should always work).
955 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
956 RTC_DCHECK(result);
957 }
958 }
peah9e6a2902017-05-15 07:19:21 -0700959}
ivoc9f4a4a02016-10-28 05:39:16 -0700960
peah9e6a2902017-05-15 07:19:21 -0700961void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700962 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
963
964 // Insert the samples into the queue.
965 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
966 // The data queue is full and needs to be emptied.
967 EmptyQueuedRenderAudio();
968
969 // Retry the insert (should always work).
970 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
971 RTC_DCHECK(result);
972 }
peah764e3642016-10-22 05:04:30 -0700973}
974
975void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700976 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700977 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700978 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700979 EchoCancellationImpl::NumCancellersRequired(
980 num_output_channels(), num_reverse_channels()));
981
peah701d6282016-10-25 05:42:20 -0700982 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700983 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700984 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700985 EchoControlMobileImpl::NumCancellersRequired(
986 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700987
peah701d6282016-10-25 05:42:20 -0700988 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700989 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700990
ivoc9f4a4a02016-10-28 05:39:16 -0700991 const size_t new_red_render_queue_element_max_size =
992 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
993
peaha0624602016-10-25 04:45:24 -0700994 // Reallocate the queues if the queue item sizes are too small to fit the
995 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700996 if (aec_render_queue_element_max_size_ <
997 new_aec_render_queue_element_max_size) {
998 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700999
peaha0624602016-10-25 04:45:24 -07001000 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001001 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001002
peah701d6282016-10-25 05:42:20 -07001003 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001004 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1005 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001006 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001007 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001008
peah701d6282016-10-25 05:42:20 -07001009 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1010 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001011 } else {
peah701d6282016-10-25 05:42:20 -07001012 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001013 }
1014
peah701d6282016-10-25 05:42:20 -07001015 if (aecm_render_queue_element_max_size_ <
1016 new_aecm_render_queue_element_max_size) {
1017 aecm_render_queue_element_max_size_ =
1018 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001019
1020 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001021 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001022
peah701d6282016-10-25 05:42:20 -07001023 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001024 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1025 kMaxNumFramesToBuffer, template_queue_element,
1026 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001027 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001028
peah701d6282016-10-25 05:42:20 -07001029 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1030 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001031 } else {
peah701d6282016-10-25 05:42:20 -07001032 aecm_render_signal_queue_->Clear();
1033 }
1034
1035 if (agc_render_queue_element_max_size_ <
1036 new_agc_render_queue_element_max_size) {
1037 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1038
1039 std::vector<int16_t> template_queue_element(
1040 agc_render_queue_element_max_size_);
1041
1042 agc_render_signal_queue_.reset(
1043 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1044 kMaxNumFramesToBuffer, template_queue_element,
1045 RenderQueueItemVerifier<int16_t>(
1046 agc_render_queue_element_max_size_)));
1047
1048 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1049 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1050 } else {
1051 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001052 }
ivoc9f4a4a02016-10-28 05:39:16 -07001053
1054 if (red_render_queue_element_max_size_ <
1055 new_red_render_queue_element_max_size) {
1056 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1057
1058 std::vector<float> template_queue_element(
1059 red_render_queue_element_max_size_);
1060
1061 red_render_signal_queue_.reset(
1062 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1063 kMaxNumFramesToBuffer, template_queue_element,
1064 RenderQueueItemVerifier<float>(
1065 red_render_queue_element_max_size_)));
1066
1067 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1068 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1069 } else {
1070 red_render_signal_queue_->Clear();
1071 }
peah764e3642016-10-22 05:04:30 -07001072}
1073
1074void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1075 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001076 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001077 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001078 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001079 }
1080
peah701d6282016-10-25 05:42:20 -07001081 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001082 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001083 aecm_capture_queue_buffer_);
1084 }
1085
1086 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1087 public_submodules_->gain_control->ProcessRenderAudio(
1088 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001089 }
ivoc9f4a4a02016-10-28 05:39:16 -07001090
1091 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001092 RTC_DCHECK(private_submodules_->echo_detector);
1093 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001094 red_capture_queue_buffer_);
1095 }
peah764e3642016-10-22 05:04:30 -07001096}
1097
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001098int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001099 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001100 {
1101 // Acquire the capture lock in order to safely call the function
1102 // that retrieves the render side data. This function accesses apm
1103 // getters that need the capture lock held when being called.
1104 // The lock needs to be released as
1105 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1106 // as well.
1107 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001108 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001109 }
peahfa6228e2015-11-16 16:27:42 -08001110
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001111 if (!frame) {
1112 return kNullPointerError;
1113 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001114 // Must be a native rate.
1115 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1116 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001117 frame->sample_rate_hz_ != kSampleRate32kHz &&
1118 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001119 return kBadSampleRateError;
1120 }
peah192164e2015-11-17 02:16:45 -08001121
peahdf3efa82015-11-28 12:35:15 -08001122 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001123 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001124 {
1125 // Aquire lock for the access of api_format.
1126 // The lock is released immediately due to the conditional
1127 // reinitialization.
1128 rtc::CritScope cs_capture(&crit_capture_);
1129 // TODO(ajm): The input and output rates and channels are currently
1130 // constrained to be identical in the int16 interface.
1131 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001132
1133 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001134 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001135 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1136 processing_config.input_stream().set_num_channels(frame->num_channels_);
1137 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1138 processing_config.output_stream().set_num_channels(frame->num_channels_);
1139
peahdf3efa82015-11-28 12:35:15 -08001140 {
1141 // Do conditional reinitialization.
1142 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001143 RETURN_ON_ERR(
1144 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001145 }
1146 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001147 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001148 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001149 return kBadDataLengthError;
1150 }
1151
aleloi868f32f2017-05-23 07:20:05 -07001152 if (aec_dump_) {
1153 RecordUnprocessedCaptureStream(*frame);
1154 }
1155
peahdf3efa82015-11-28 12:35:15 -08001156 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001157 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001158 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001159 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1160 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001161
aleloi868f32f2017-05-23 07:20:05 -07001162 if (aec_dump_) {
1163 RecordProcessedCaptureStream(*frame);
1164 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001165
1166 return kNoError;
1167}
1168
peahde65ddc2016-09-16 15:02:15 -07001169int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001170 // Ensure that not both the AEC and AECM are active at the same time.
1171 // TODO(peah): Simplify once the public API Enable functions for these
1172 // are moved to APM.
1173 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1174 public_submodules_->echo_control_mobile->is_enabled()));
1175
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001176 MaybeUpdateHistograms();
1177
peahde65ddc2016-09-16 15:02:15 -07001178 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001179
peah1b08dc32016-12-20 13:45:58 -08001180 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001181 capture_buffer->channels_const()[0],
1182 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001183 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1184 if (log_rms) {
1185 capture_rms_interval_counter_ = 0;
1186 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001187 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1188 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1189 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1190 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001191 }
1192
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001193 if (private_submodules_->echo_controller) {
Per Åhgren9aed31c2017-06-29 20:23:27 +02001194 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1195 // issues have been addressed.
1196 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001197 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001198 }
1199
peahbe615622016-02-13 16:40:47 -08001200 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001201 public_submodules_->gain_control->is_enabled()) {
1202 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001203 capture_buffer->channels()[0], capture_buffer->num_channels(),
1204 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001205 }
1206
peah2ace3f92016-09-10 04:42:27 -07001207 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1208 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001209 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1210 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001211 }
1212
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001213 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001214 // Force down-mixing of the number of channels after the detection of
1215 // capture signal saturation.
1216 // TODO(peah): Look into ensuring that this kind of tampering with the
1217 // AudioBuffer functionality should not be needed.
1218 capture_buffer->set_num_channels(1);
1219 }
1220
aluebsb2328d12016-01-11 20:32:29 -08001221 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001222 private_submodules_->beamformer->AnalyzeChunk(
1223 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001224 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001225 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001226 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001227
peahe0eae3c2016-12-14 01:16:23 -08001228 // TODO(peah): Move the AEC3 low-cut filter to this place.
1229 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001230 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001231 private_submodules_->low_cut_filter->Process(capture_buffer);
1232 }
peahde65ddc2016-09-16 15:02:15 -07001233 RETURN_ON_ERR(
1234 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1235 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001236
1237 // Ensure that the stream delay was set before the call to the
1238 // AEC ProcessCaptureAudio function.
1239 if (public_submodules_->echo_cancellation->is_enabled() &&
1240 !was_stream_delay_set()) {
1241 return AudioProcessing::kStreamParameterNotSetError;
1242 }
1243
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001244 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001245 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1246
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001247 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001248 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001249 } else {
1250 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1251 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001252 }
1253
peahdf3efa82015-11-28 12:35:15 -08001254 if (public_submodules_->echo_control_mobile->is_enabled() &&
1255 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001256 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001257 }
peahde65ddc2016-09-16 15:02:15 -07001258 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001259#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001260 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001261 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001262 int gain_db = public_submodules_->gain_control->is_enabled() ?
1263 public_submodules_->gain_control->compression_gain_db() :
1264 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001265 float gain = std::pow(10.f, gain_db / 20.f);
1266 gain *= capture_nonlocked_.level_controller_enabled ?
1267 private_submodules_->level_controller->GetLastGain() :
1268 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001269 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001270 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001271 }
peah1bcfce52016-08-26 07:16:04 -07001272#endif
peah253534d2016-03-15 04:32:28 -07001273
1274 // Ensure that the stream delay was set before the call to the
1275 // AECM ProcessCaptureAudio function.
1276 if (public_submodules_->echo_control_mobile->is_enabled() &&
1277 !was_stream_delay_set()) {
1278 return AudioProcessing::kStreamParameterNotSetError;
1279 }
1280
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001281 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001282 public_submodules_->echo_cancellation->is_enabled())) {
1283 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1284 capture_buffer, stream_delay_ms()));
1285 }
ivoc9f4a4a02016-10-28 05:39:16 -07001286
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001287 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001288 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001289 }
1290
peahde65ddc2016-09-16 15:02:15 -07001291 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001292
peahbe615622016-02-13 16:40:47 -08001293 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001294 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001295 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001296 private_submodules_->beamformer->is_target_present())) {
1297 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001298 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1299 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001300 }
peahb8fbb542016-03-15 02:28:08 -07001301 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001302 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001303
peah2ace3f92016-09-10 04:42:27 -07001304 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1305 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001306 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1307 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001308 }
1309
peah9e6a2902017-05-15 07:19:21 -07001310 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001311 RTC_DCHECK(private_submodules_->echo_detector);
1312 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001313 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1314 capture_buffer->num_frames()));
1315 }
1316
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001317 // TODO(aluebs): Investigate if the transient suppression placement should be
1318 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001319 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001320 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001321 private_submodules_->agc_manager.get()
1322 ? private_submodules_->agc_manager->voice_probability()
1323 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001324
peahdf3efa82015-11-28 12:35:15 -08001325 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001326 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1327 capture_buffer->num_channels(),
1328 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1329 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1330 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001331 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001332 }
1333
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001334 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001335 private_submodules_->gain_controller2->Process(capture_buffer);
1336 }
1337
peahca4cac72016-06-29 15:26:12 -07001338 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001339 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001340 }
1341
Sam Zackrisson0beac582017-09-25 12:04:02 +02001342 if (private_submodules_->capture_post_processor) {
1343 private_submodules_->capture_post_processor->Process(capture_buffer);
1344 }
1345
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001346 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001347 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001348
peah1b08dc32016-12-20 13:45:58 -08001349 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1350 capture_buffer->channels_const()[0],
1351 capture_nonlocked_.capture_processing_format.num_frames()));
1352 if (log_rms) {
1353 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1354 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1355 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1356 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1357 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1358 }
1359
peahdf3efa82015-11-28 12:35:15 -08001360 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001361 return kNoError;
1362}
1363
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001364int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001365 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001366 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001367 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001368 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001369 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001370 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001371 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001372 };
1373 if (samples_per_channel != reverse_config.num_frames()) {
1374 return kBadDataLengthError;
1375 }
peahdf3efa82015-11-28 12:35:15 -08001376 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001377}
1378
peahde65ddc2016-09-16 15:02:15 -07001379int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1380 const StreamConfig& input_config,
1381 const StreamConfig& output_config,
1382 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001383 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001384 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001385 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001386 if (submodule_states_.RenderMultiBandProcessingActive() ||
1387 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001388 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1389 dest);
peah2ace3f92016-09-10 04:42:27 -07001390 } else if (formats_.api_format.reverse_input_stream() !=
1391 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001392 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1393 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001394 } else {
peahde65ddc2016-09-16 15:02:15 -07001395 CopyAudioIfNeeded(src, input_config.num_frames(),
1396 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001397 }
1398
1399 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001400}
1401
peahdf3efa82015-11-28 12:35:15 -08001402int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001403 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001404 const StreamConfig& input_config,
1405 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001406 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001407 return kNullPointerError;
1408 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001409
peahde65ddc2016-09-16 15:02:15 -07001410 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001411 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001412 }
1413
peahdf3efa82015-11-28 12:35:15 -08001414 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001415 processing_config.reverse_input_stream() = input_config;
1416 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001417
peahdf3efa82015-11-28 12:35:15 -08001418 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001419 assert(input_config.num_frames() ==
1420 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001421
aleloi868f32f2017-05-23 07:20:05 -07001422 if (aec_dump_) {
1423 const size_t channel_size =
1424 formats_.api_format.reverse_input_stream().num_frames();
1425 const size_t num_channels =
1426 formats_.api_format.reverse_input_stream().num_channels();
1427 aec_dump_->WriteRenderStreamMessage(
1428 FloatAudioFrame(src, num_channels, channel_size));
1429 }
peahdf3efa82015-11-28 12:35:15 -08001430 render_.render_audio->CopyFrom(src,
1431 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001432 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001433}
1434
1435int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001436 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001437 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001438 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001439 return kNullPointerError;
1440 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001441 // Must be a native rate.
1442 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1443 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001444 frame->sample_rate_hz_ != kSampleRate32kHz &&
1445 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001446 return kBadSampleRateError;
1447 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001448
Michael Graczyk86c6d332015-07-23 11:41:39 -07001449 if (frame->num_channels_ <= 0) {
1450 return kBadNumberChannelsError;
1451 }
1452
peahdf3efa82015-11-28 12:35:15 -08001453 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001454 processing_config.reverse_input_stream().set_sample_rate_hz(
1455 frame->sample_rate_hz_);
1456 processing_config.reverse_input_stream().set_num_channels(
1457 frame->num_channels_);
1458 processing_config.reverse_output_stream().set_sample_rate_hz(
1459 frame->sample_rate_hz_);
1460 processing_config.reverse_output_stream().set_num_channels(
1461 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001462
peahdf3efa82015-11-28 12:35:15 -08001463 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001464 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001465 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001466 return kBadDataLengthError;
1467 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001468
aleloi868f32f2017-05-23 07:20:05 -07001469 if (aec_dump_) {
1470 aec_dump_->WriteRenderStreamMessage(*frame);
1471 }
1472
peahdf3efa82015-11-28 12:35:15 -08001473 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001474 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001475 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001476 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1477 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001478 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001479}
niklase@google.com470e71d2011-07-07 08:21:25 +00001480
peahde65ddc2016-09-16 15:02:15 -07001481int AudioProcessingImpl::ProcessRenderStreamLocked() {
1482 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001483
1484 QueueNonbandedRenderAudio(render_buffer);
1485
Alex Loiko5825aa62017-12-18 16:02:40 +01001486 if (private_submodules_->render_pre_processor) {
1487 private_submodules_->render_pre_processor->Process(render_buffer);
1488 }
1489
peah2ace3f92016-09-10 04:42:27 -07001490 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001491 SampleRateSupportsMultiBand(
1492 formats_.render_processing_format.sample_rate_hz())) {
1493 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001494 }
1495
peah1bcfce52016-08-26 07:16:04 -07001496#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001497 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001498 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001499 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001500 }
peah1bcfce52016-08-26 07:16:04 -07001501#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001502
peahce4d9152017-05-19 01:28:05 -07001503 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1504 QueueBandedRenderAudio(render_buffer);
1505 }
1506
peahe0eae3c2016-12-14 01:16:23 -08001507 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001508 if (private_submodules_->echo_controller) {
1509 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001510 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001511
peah2ace3f92016-09-10 04:42:27 -07001512 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001513 SampleRateSupportsMultiBand(
1514 formats_.render_processing_format.sample_rate_hz())) {
1515 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001516 }
1517
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001518 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001519}
1520
1521int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001522 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001523 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001524 capture_.was_stream_delay_set = true;
1525 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001526
niklase@google.com470e71d2011-07-07 08:21:25 +00001527 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001528 delay = 0;
1529 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001530 }
1531
1532 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1533 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001534 delay = 500;
1535 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001536 }
1537
peahdf3efa82015-11-28 12:35:15 -08001538 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001539 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001540}
1541
1542int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001543 // Used as callback from submodules, hence locking is not allowed.
1544 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001545}
1546
1547bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001548 // Used as callback from submodules, hence locking is not allowed.
1549 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001550}
1551
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001552void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001553 rtc::CritScope cs(&crit_capture_);
1554 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001555}
1556
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001557void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001558 rtc::CritScope cs(&crit_capture_);
1559 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001560}
1561
1562int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001563 rtc::CritScope cs(&crit_capture_);
1564 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001565}
1566
aleloi868f32f2017-05-23 07:20:05 -07001567void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1568 RTC_DCHECK(aec_dump);
1569 rtc::CritScope cs_render(&crit_render_);
1570 rtc::CritScope cs_capture(&crit_capture_);
1571
1572 // The previously attached AecDump will be destroyed with the
1573 // 'aec_dump' parameter, which is after locks are released.
1574 aec_dump_.swap(aec_dump);
1575 WriteAecDumpConfigMessage(true);
1576 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1577}
1578
1579void AudioProcessingImpl::DetachAecDump() {
1580 // The d-tor of a task-queue based AecDump blocks until all pending
1581 // tasks are done. This construction avoids blocking while holding
1582 // the render and capture locks.
1583 std::unique_ptr<AecDump> aec_dump = nullptr;
1584 {
1585 rtc::CritScope cs_render(&crit_render_);
1586 rtc::CritScope cs_capture(&crit_capture_);
1587 aec_dump = std::move(aec_dump_);
1588 }
1589}
1590
ivoc4e477a12017-01-15 08:29:46 -08001591AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1592 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1593 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1594 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1595 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1596}
1597
1598AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1599 const AudioProcessingStatistics& other) = default;
1600
1601AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1602 default;
1603
ivoc3e9a5372016-10-28 07:55:33 -07001604// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1605AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1606 const {
1607 return AudioProcessingStatistics();
1608}
1609
Ivo Creusenae026092017-11-20 13:07:16 +01001610// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001611AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001612 bool has_remote_tracks) const {
1613 return AudioProcessingStats();
1614}
1615
ivoc3e9a5372016-10-28 07:55:33 -07001616AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1617 const {
1618 AudioProcessingStatistics stats;
1619 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001620 if (private_submodules_->echo_controller) {
1621 rtc::CritScope cs_capture(&crit_capture_);
1622 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1623 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1624 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1625 // Instant value will also be used for min, max and average.
1626 stats.echo_return_loss.Set(erl, erl, erl, erl);
1627 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1628 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1629 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001630 stats.a_nlp.Set(metrics.a_nlp);
1631 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1632 stats.echo_return_loss.Set(metrics.echo_return_loss);
1633 stats.echo_return_loss_enhancement.Set(
1634 metrics.echo_return_loss_enhancement);
1635 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1636 }
ivoc9c192b22017-03-16 04:22:14 -07001637 {
1638 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001639 RTC_DCHECK(private_submodules_->echo_detector);
1640 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1641 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001642 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001643 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001644 }
ivoc3e9a5372016-10-28 07:55:33 -07001645 public_submodules_->echo_cancellation->GetDelayMetrics(
1646 &stats.delay_median, &stats.delay_standard_deviation,
1647 &stats.fraction_poor_delays);
1648 return stats;
1649}
1650
Ivo Creusen56d46092017-11-24 17:29:59 +01001651AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001652 bool has_remote_tracks) const {
1653 AudioProcessingStats stats;
1654 if (has_remote_tracks) {
1655 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001656 if (private_submodules_->echo_controller) {
1657 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001658 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1659 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001660 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001661 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001662 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001663 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1664 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001665 if (metrics.divergent_filter_fraction != -1.0f) {
1666 stats.divergent_filter_fraction =
1667 rtc::Optional<double>(metrics.divergent_filter_fraction);
1668 }
1669 if (metrics.echo_return_loss.instant != -100) {
1670 stats.echo_return_loss =
1671 rtc::Optional<double>(metrics.echo_return_loss.instant);
1672 }
1673 if (metrics.echo_return_loss_enhancement.instant != -100) {
1674 stats.echo_return_loss_enhancement =
1675 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1676 }
1677 }
1678 if (config_.residual_echo_detector.enabled) {
1679 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001680 RTC_DCHECK(private_submodules_->echo_detector);
1681 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1682 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001683 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001684 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001685 }
1686 int delay_median, delay_std;
1687 float fraction_poor_delays;
1688 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1689 &delay_median, &delay_std, &fraction_poor_delays) ==
1690 Error::kNoError) {
1691 if (delay_median >= 0) {
1692 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1693 }
1694 if (delay_std >= 0) {
1695 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1696 }
1697 }
1698 }
1699 return stats;
1700}
1701
niklase@google.com470e71d2011-07-07 08:21:25 +00001702EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001703 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001704}
1705
1706EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001707 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001708}
1709
1710GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001711 if (constants_.use_experimental_agc) {
1712 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001713 }
peahbfa97112016-03-10 21:09:04 -08001714 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001715}
1716
1717HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001718 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001719}
1720
1721LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001722 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001723}
1724
1725NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001726 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001727}
1728
1729VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001730 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001731}
1732
peah8271d042016-11-22 07:24:52 -08001733void AudioProcessingImpl::MutateConfig(
1734 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1735 rtc::CritScope cs_render(&crit_render_);
1736 rtc::CritScope cs_capture(&crit_capture_);
1737 mutator(&config_);
1738 ApplyConfig(config_);
1739}
1740
1741AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1742 rtc::CritScope cs_render(&crit_render_);
1743 rtc::CritScope cs_capture(&crit_capture_);
1744 return config_;
1745}
1746
peah2ace3f92016-09-10 04:42:27 -07001747bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1748 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001749 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001750 public_submodules_->echo_cancellation->is_enabled(),
1751 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001752 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001753 public_submodules_->noise_suppression->is_enabled(),
1754 capture_nonlocked_.intelligibility_enabled,
1755 capture_nonlocked_.beamformer_enabled,
1756 public_submodules_->gain_control->is_enabled(),
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001757 config_.gain_controller2.enabled,
peah2ace3f92016-09-10 04:42:27 -07001758 capture_nonlocked_.level_controller_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001759 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001760 public_submodules_->voice_detection->is_enabled(),
1761 public_submodules_->level_estimator->is_enabled(),
1762 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001763}
1764
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001765
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001766void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001767 if (capture_.transient_suppressor_enabled) {
1768 if (!public_submodules_->transient_suppressor.get()) {
1769 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001770 }
peahdf3efa82015-11-28 12:35:15 -08001771 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001772 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1773 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001774 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001775}
1776
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001777void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001778 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001779 if (!private_submodules_->beamformer) {
1780 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001781 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001782 }
peahdf3efa82015-11-28 12:35:15 -08001783 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1784 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001785 }
1786}
1787
ekmeyerson60d9b332015-08-14 10:35:55 -07001788void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001789#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001790 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001791 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001792 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001793 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001794 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001795 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001796 }
peah1bcfce52016-08-26 07:16:04 -07001797#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001798}
1799
peah8271d042016-11-22 07:24:52 -08001800void AudioProcessingImpl::InitializeLowCutFilter() {
1801 if (config_.high_pass_filter.enabled) {
1802 private_submodules_->low_cut_filter.reset(
1803 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1804 } else {
1805 private_submodules_->low_cut_filter.reset();
1806 }
1807}
alessiob3ec96df2017-05-22 06:57:06 -07001808
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001809void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001810 if (echo_control_factory_) {
1811 private_submodules_->echo_controller =
1812 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001813 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001814 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001815 }
1816}
peah8271d042016-11-22 07:24:52 -08001817
alessiob3ec96df2017-05-22 06:57:06 -07001818void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001819 if (config_.gain_controller2.enabled) {
1820 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001821 }
1822}
1823
peahca4cac72016-06-29 15:26:12 -07001824void AudioProcessingImpl::InitializeLevelController() {
1825 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1826}
1827
ivoc9f4a4a02016-10-28 05:39:16 -07001828void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001829 RTC_DCHECK(private_submodules_->echo_detector);
1830 private_submodules_->echo_detector->Initialize(proc_sample_rate_hz(),
1831 num_proc_channels());
ivoc9f4a4a02016-10-28 05:39:16 -07001832}
1833
Sam Zackrisson0beac582017-09-25 12:04:02 +02001834void AudioProcessingImpl::InitializePostProcessor() {
1835 if (private_submodules_->capture_post_processor) {
1836 private_submodules_->capture_post_processor->Initialize(
1837 proc_sample_rate_hz(), num_proc_channels());
1838 }
1839}
1840
Alex Loiko5825aa62017-12-18 16:02:40 +01001841void AudioProcessingImpl::InitializePreProcessor() {
1842 if (private_submodules_->render_pre_processor) {
1843 private_submodules_->render_pre_processor->Initialize(
1844 formats_.render_processing_format.sample_rate_hz(),
1845 formats_.render_processing_format.num_channels());
1846 }
1847}
1848
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001849void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001850 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001851
1852 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001853 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001854 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001855 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001856 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001857 capture_.stream_delay_jumps = 0;
1858 }
1859 if (capture_.aec_system_delay_jumps == -1 &&
1860 echo_cancellation()->stream_has_echo()) {
1861 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001862 }
1863
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001864 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001865 const int diff_stream_delay_ms =
1866 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1867 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1868 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001869 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1870 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001871 if (capture_.stream_delay_jumps == -1) {
1872 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001873 }
peahdf3efa82015-11-28 12:35:15 -08001874 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001875 }
peahdf3efa82015-11-28 12:35:15 -08001876 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001877
1878 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001879 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001880 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001881 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001882 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001883 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1884 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001885 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001886 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001887 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001888 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001889 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1890 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1891 100);
peahdf3efa82015-11-28 12:35:15 -08001892 if (capture_.aec_system_delay_jumps == -1) {
1893 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001894 }
peahdf3efa82015-11-28 12:35:15 -08001895 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001896 }
peahdf3efa82015-11-28 12:35:15 -08001897 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001898 }
1899}
1900
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001901void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001902 // Run in a single-threaded manner.
1903 rtc::CritScope cs_render(&crit_render_);
1904 rtc::CritScope cs_capture(&crit_capture_);
1905
1906 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001907 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001908 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001909 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001910 }
peahdf3efa82015-11-28 12:35:15 -08001911 capture_.stream_delay_jumps = -1;
1912 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001913
peahdf3efa82015-11-28 12:35:15 -08001914 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001915 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1916 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001917 }
peahdf3efa82015-11-28 12:35:15 -08001918 capture_.aec_system_delay_jumps = -1;
1919 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001920}
1921
aleloi868f32f2017-05-23 07:20:05 -07001922void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1923 if (!aec_dump_) {
1924 return;
1925 }
1926 std::string experiments_description =
1927 public_submodules_->echo_cancellation->GetExperimentsDescription();
1928 // TODO(peah): Add semicolon-separated concatenations of experiment
1929 // descriptions for other submodules.
1930 if (capture_nonlocked_.level_controller_enabled) {
1931 experiments_description += "LevelController;";
1932 }
1933 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1934 experiments_description += "AgcClippingLevelExperiment;";
1935 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001936 if (capture_nonlocked_.echo_controller_enabled) {
1937 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001938 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001939 if (config_.gain_controller2.enabled) {
1940 experiments_description += "GainController2;";
1941 }
aleloi868f32f2017-05-23 07:20:05 -07001942
1943 InternalAPMConfig apm_config;
1944
1945 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1946 apm_config.aec_delay_agnostic_enabled =
1947 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1948 apm_config.aec_drift_compensation_enabled =
1949 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1950 apm_config.aec_extended_filter_enabled =
1951 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1952 apm_config.aec_suppression_level = static_cast<int>(
1953 public_submodules_->echo_cancellation->suppression_level());
1954
1955 apm_config.aecm_enabled =
1956 public_submodules_->echo_control_mobile->is_enabled();
1957 apm_config.aecm_comfort_noise_enabled =
1958 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1959 apm_config.aecm_routing_mode =
1960 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1961
1962 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1963 apm_config.agc_mode =
1964 static_cast<int>(public_submodules_->gain_control->mode());
1965 apm_config.agc_limiter_enabled =
1966 public_submodules_->gain_control->is_limiter_enabled();
1967 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1968
1969 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1970
1971 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1972 apm_config.ns_level =
1973 static_cast<int>(public_submodules_->noise_suppression->level());
1974
1975 apm_config.transient_suppression_enabled =
1976 capture_.transient_suppressor_enabled;
1977 apm_config.intelligibility_enhancer_enabled =
1978 capture_nonlocked_.intelligibility_enabled;
1979 apm_config.experiments_description = experiments_description;
1980
1981 if (!forced && apm_config == apm_config_for_aec_dump_) {
1982 return;
1983 }
1984 aec_dump_->WriteConfig(apm_config);
1985 apm_config_for_aec_dump_ = apm_config;
1986}
1987
1988void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1989 const float* const* src) {
1990 RTC_DCHECK(aec_dump_);
1991 WriteAecDumpConfigMessage(false);
1992
1993 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1994 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1995 aec_dump_->AddCaptureStreamInput(
1996 FloatAudioFrame(src, num_channels, channel_size));
1997 RecordAudioProcessingState();
1998}
1999
2000void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2001 const AudioFrame& capture_frame) {
2002 RTC_DCHECK(aec_dump_);
2003 WriteAecDumpConfigMessage(false);
2004
2005 aec_dump_->AddCaptureStreamInput(capture_frame);
2006 RecordAudioProcessingState();
2007}
2008
2009void AudioProcessingImpl::RecordProcessedCaptureStream(
2010 const float* const* processed_capture_stream) {
2011 RTC_DCHECK(aec_dump_);
2012
2013 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2014 const size_t num_channels =
2015 formats_.api_format.output_stream().num_channels();
2016 aec_dump_->AddCaptureStreamOutput(
2017 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
2018 aec_dump_->WriteCaptureStreamMessage();
2019}
2020
2021void AudioProcessingImpl::RecordProcessedCaptureStream(
2022 const AudioFrame& processed_capture_frame) {
2023 RTC_DCHECK(aec_dump_);
2024
2025 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2026 aec_dump_->WriteCaptureStreamMessage();
2027}
2028
2029void AudioProcessingImpl::RecordAudioProcessingState() {
2030 RTC_DCHECK(aec_dump_);
2031 AecDump::AudioProcessingState audio_proc_state;
2032 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2033 audio_proc_state.drift =
2034 public_submodules_->echo_cancellation->stream_drift_samples();
2035 audio_proc_state.level = gain_control()->stream_analog_level();
2036 audio_proc_state.keypress = capture_.key_pressed;
2037 aec_dump_->AddAudioProcessingState(audio_proc_state);
2038}
2039
kwiberg83ffe452016-08-29 14:46:07 -07002040AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2041 bool transient_suppressor_enabled,
2042 const std::vector<Point>& array_geometry,
2043 SphericalPointf target_direction)
2044 : aec_system_delay_jumps(-1),
2045 delay_offset_ms(0),
2046 was_stream_delay_set(false),
2047 last_stream_delay_ms(0),
2048 last_aec_system_delay_ms(0),
2049 stream_delay_jumps(-1),
2050 output_will_be_muted(false),
2051 key_pressed(false),
2052 transient_suppressor_enabled(transient_suppressor_enabled),
2053 array_geometry(array_geometry),
2054 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002055 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002056 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002057 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002058
2059AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2060
2061AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2062
2063AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2064
niklase@google.com470e71d2011-07-07 08:21:25 +00002065} // namespace webrtc