blob: 240d663a612554a54addd98a78e750562afca925 [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: "
452 << !!private_submodules_->capture_post_processor;
Alex Loiko5825aa62017-12-18 16:02:40 +0100453
454 RTC_LOG(LS_INFO) << "Render pre processor activated: "
455 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800456 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000457
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000458 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000459}
460
461AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800462 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800463 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800464 private_submodules_->agc_manager.reset();
465 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800466 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000467}
468
niklase@google.com470e71d2011-07-07 08:21:25 +0000469int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800470 // Run in a single-threaded manner during initialization.
471 rtc::CritScope cs_render(&crit_render_);
472 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000473 return InitializeLocked();
474}
475
peahde65ddc2016-09-16 15:02:15 -0700476int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
477 int capture_output_sample_rate_hz,
478 int render_input_sample_rate_hz,
479 ChannelLayout capture_input_layout,
480 ChannelLayout capture_output_layout,
481 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700482 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700483 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
484 LayoutHasKeyboard(capture_input_layout)},
485 {capture_output_sample_rate_hz,
486 ChannelsFromLayout(capture_output_layout),
487 LayoutHasKeyboard(capture_output_layout)},
488 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
489 LayoutHasKeyboard(render_input_layout)},
490 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
491 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700492
493 return Initialize(processing_config);
494}
495
496int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800497 // Run in a single-threaded manner during initialization.
498 rtc::CritScope cs_render(&crit_render_);
499 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700500 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000501}
502
peahdf3efa82015-11-28 12:35:15 -0800503int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800504 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700505 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800506}
507
peahdf3efa82015-11-28 12:35:15 -0800508int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700509 const ProcessingConfig& processing_config,
510 bool force_initialization) {
511 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800512}
513
peah192164e2015-11-17 02:16:45 -0800514// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800515// their current values (needs to be called while holding the crit_render_lock).
516int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700517 const ProcessingConfig& processing_config,
518 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800519 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700520 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800521 return kNoError;
522 }
peahdf3efa82015-11-28 12:35:15 -0800523
524 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800525 return InitializeLocked(processing_config);
526}
527
niklase@google.com470e71d2011-07-07 08:21:25 +0000528int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200529 UpdateActiveSubmoduleStates();
530
peah522d71b2017-02-23 05:16:26 -0800531 const int capture_audiobuffer_num_channels =
532 capture_nonlocked_.beamformer_enabled
533 ? formats_.api_format.input_stream().num_channels()
534 : formats_.api_format.output_stream().num_channels();
535
peahde65ddc2016-09-16 15:02:15 -0700536 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800537 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700538 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800539 : formats_.api_format.reverse_output_stream().num_frames();
540 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
541 render_.render_audio.reset(new AudioBuffer(
542 formats_.api_format.reverse_input_stream().num_frames(),
543 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700544 formats_.render_processing_format.num_frames(),
545 formats_.render_processing_format.num_channels(),
546 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700547 if (formats_.api_format.reverse_input_stream() !=
548 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800549 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800550 formats_.api_format.reverse_input_stream().num_channels(),
551 formats_.api_format.reverse_input_stream().num_frames(),
552 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800553 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700554 } else {
peahdf3efa82015-11-28 12:35:15 -0800555 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700556 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700557 } else {
peahdf3efa82015-11-28 12:35:15 -0800558 render_.render_audio.reset(nullptr);
559 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700560 }
peahce4d9152017-05-19 01:28:05 -0700561
peahdf3efa82015-11-28 12:35:15 -0800562 capture_.capture_audio.reset(
563 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
564 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700565 capture_nonlocked_.capture_processing_format.num_frames(),
566 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800567 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000568
peahde65ddc2016-09-16 15:02:15 -0700569 public_submodules_->echo_cancellation->Initialize(
570 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
571 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700572 AllocateRenderQueue();
573
ivoc3e9a5372016-10-28 07:55:33 -0700574 int success = public_submodules_->echo_cancellation->enable_metrics(true);
575 RTC_DCHECK_EQ(0, success);
576 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
577 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700578 public_submodules_->echo_control_mobile->Initialize(
579 proc_split_sample_rate_hz(), num_reverse_channels(),
580 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700581
582 public_submodules_->gain_control->Initialize(num_proc_channels(),
583 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700584 if (constants_.use_experimental_agc) {
585 if (!private_submodules_->agc_manager.get()) {
586 private_submodules_->agc_manager.reset(new AgcManagerDirect(
587 public_submodules_->gain_control.get(),
588 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800589 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700590 }
591 private_submodules_->agc_manager->Initialize();
592 private_submodules_->agc_manager->SetCaptureMuted(
593 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700594 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700595 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200596 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000597 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700598#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700599 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700600#endif
peah8271d042016-11-22 07:24:52 -0800601 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700602 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
603 proc_sample_rate_hz());
604 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
605 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700606 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700607 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200608 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700609 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200610 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100611 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800612
aleloi868f32f2017-05-23 07:20:05 -0700613 if (aec_dump_) {
614 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
615 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000616 return kNoError;
617}
618
Michael Graczyk86c6d332015-07-23 11:41:39 -0700619int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200620 UpdateActiveSubmoduleStates();
621
Michael Graczyk86c6d332015-07-23 11:41:39 -0700622 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700623 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
624 return kBadSampleRateError;
625 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000626 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700627
Peter Kasting69558702016-01-12 16:26:35 -0800628 const size_t num_in_channels = config.input_stream().num_channels();
629 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700630
631 // Need at least one input channel.
632 // Need either one output channel or as many outputs as there are inputs.
633 if (num_in_channels == 0 ||
634 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700635 return kBadNumberChannelsError;
636 }
637
aluebsb2328d12016-01-11 20:32:29 -0800638 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800639 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700640 return kBadNumberChannelsError;
641 }
642
peahdf3efa82015-11-28 12:35:15 -0800643 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000644
peahde65ddc2016-09-16 15:02:15 -0700645 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700646 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700647 formats_.api_format.output_stream().sample_rate_hz()),
648 submodule_states_.CaptureMultiBandSubModulesActive() ||
649 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000650
peahde65ddc2016-09-16 15:02:15 -0700651 capture_nonlocked_.capture_processing_format =
652 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700653
peah2ce640f2017-04-07 03:57:48 -0700654 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200655 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700656 render_processing_rate = FindNativeProcessRateToUse(
657 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
658 formats_.api_format.reverse_output_stream().sample_rate_hz()),
659 submodule_states_.CaptureMultiBandSubModulesActive() ||
660 submodule_states_.RenderMultiBandSubModulesActive());
661 } else {
662 render_processing_rate = capture_processing_rate;
663 }
664
aluebseb3603b2016-04-20 15:27:58 -0700665 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
666 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700667 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200668 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700669 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
670 ? kSampleRate32kHz
671 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700672 }
peah2ce640f2017-04-07 03:57:48 -0700673
peahde65ddc2016-09-16 15:02:15 -0700674 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700675 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700676 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
677 kSampleRate8kHz) {
678 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000679 } else {
peahde65ddc2016-09-16 15:02:15 -0700680 render_processing_rate =
681 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000682 }
683
peahde65ddc2016-09-16 15:02:15 -0700684 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000685 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700686 if (submodule_states_.RenderMultiBandSubModulesActive()) {
687 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
688 } else {
689 formats_.render_processing_format = StreamConfig(
690 formats_.api_format.reverse_input_stream().sample_rate_hz(),
691 formats_.api_format.reverse_input_stream().num_channels());
692 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000693
peahde65ddc2016-09-16 15:02:15 -0700694 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
695 kSampleRate32kHz ||
696 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
697 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800698 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000699 } else {
peahdf3efa82015-11-28 12:35:15 -0800700 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700701 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000702 }
703
704 return InitializeLocked();
705}
706
peah88ac8532016-09-12 16:47:25 -0700707void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700708 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700709
peahc19f3122016-10-07 14:54:10 -0700710 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700711 if (!config_ok) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100712 RTC_LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
713 << "level_controller: "
714 << LevelController::ToString(config_.level_controller)
715 << std::endl
716 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700717 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700718 }
719
720 // Run in a single-threaded manner when applying the settings.
721 rtc::CritScope cs_render(&crit_render_);
722 rtc::CritScope cs_capture(&crit_capture_);
723
peahc19f3122016-10-07 14:54:10 -0700724 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
725 // with the value in config_ everywhere in the code.
726 if (capture_nonlocked_.level_controller_enabled !=
727 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700728 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700729 config_.level_controller.enabled;
730 // TODO(peah): Remove the conditional initialization to always initialize
731 // the level controller regardless of whether it is enabled or not.
732 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700733 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100734 RTC_LOG(LS_INFO) << "Level controller activated: "
735 << capture_nonlocked_.level_controller_enabled;
peahc19f3122016-10-07 14:54:10 -0700736
737 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800738
739 InitializeLowCutFilter();
740
Mirko Bonadei675513b2017-11-09 11:09:25 +0100741 RTC_LOG(LS_INFO) << "Highpass filter activated: "
742 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800743
alessiob3ec96df2017-05-22 06:57:06 -0700744 config_ok = GainController2::Validate(config_.gain_controller2);
745 if (!config_ok) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100746 RTC_LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
747 << "Gain Controller 2: "
748 << GainController2::ToString(config_.gain_controller2)
749 << std::endl
750 << "Reverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700751 config_.gain_controller2 = AudioProcessing::Config::GainController2();
752 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200753 InitializeGainController2();
754 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100755 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
756 << config_.gain_controller2.enabled;
peah88ac8532016-09-12 16:47:25 -0700757}
758
759void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800760 // Run in a single-threaded manner when setting the extra options.
761 rtc::CritScope cs_render(&crit_render_);
762 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000763
peahb624d8c2016-03-05 03:01:14 -0800764 public_submodules_->echo_cancellation->SetExtraOptions(config);
765
peahdf3efa82015-11-28 12:35:15 -0800766 if (capture_.transient_suppressor_enabled !=
767 config.Get<ExperimentalNs>().enabled) {
768 capture_.transient_suppressor_enabled =
769 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000770 InitializeTransient();
771 }
aluebs2a346882016-01-11 18:04:30 -0800772
peah1bcfce52016-08-26 07:16:04 -0700773#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700774 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700775 config.Get<Intelligibility>().enabled) {
776 capture_nonlocked_.intelligibility_enabled =
777 config.Get<Intelligibility>().enabled;
778 InitializeIntelligibility();
779 }
peah1bcfce52016-08-26 07:16:04 -0700780#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700781
aluebs2a346882016-01-11 18:04:30 -0800782#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800783 if (capture_nonlocked_.beamformer_enabled !=
784 config.Get<Beamforming>().enabled) {
785 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800786 if (config.Get<Beamforming>().array_geometry.size() > 1) {
787 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
788 }
789 capture_.target_direction = config.Get<Beamforming>().target_direction;
790 InitializeBeamformer();
791 }
792#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000793}
794
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000795int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800796 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700797 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000798}
799
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000800int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800801 // Used as callback from submodules, hence locking is not allowed.
802 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000803}
804
Peter Kasting69558702016-01-12 16:26:35 -0800805size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800806 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700807 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000808}
809
Peter Kasting69558702016-01-12 16:26:35 -0800810size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800811 // Used as callback from submodules, hence locking is not allowed.
812 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000813}
814
Peter Kasting69558702016-01-12 16:26:35 -0800815size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800816 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700817 return (capture_nonlocked_.beamformer_enabled ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200818 capture_nonlocked_.echo_controller_enabled)
peahedddac52017-05-16 01:08:58 -0700819 ? 1
820 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800821}
822
Peter Kasting69558702016-01-12 16:26:35 -0800823size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800824 // Used as callback from submodules, hence locking is not allowed.
825 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000826}
827
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000828void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800829 rtc::CritScope cs(&crit_capture_);
830 capture_.output_will_be_muted = muted;
831 if (private_submodules_->agc_manager.get()) {
832 private_submodules_->agc_manager->SetCaptureMuted(
833 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000834 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000835}
836
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000837
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000838int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700839 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000840 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000841 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000842 int output_sample_rate_hz,
843 ChannelLayout output_layout,
844 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800845 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800846 StreamConfig input_stream;
847 StreamConfig output_stream;
848 {
849 // Access the formats_.api_format.input_stream beneath the capture lock.
850 // The lock must be released as it is later required in the call
851 // to ProcessStream(,,,);
852 rtc::CritScope cs(&crit_capture_);
853 input_stream = formats_.api_format.input_stream();
854 output_stream = formats_.api_format.output_stream();
855 }
856
Michael Graczyk86c6d332015-07-23 11:41:39 -0700857 input_stream.set_sample_rate_hz(input_sample_rate_hz);
858 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
859 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700860 output_stream.set_sample_rate_hz(output_sample_rate_hz);
861 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
862 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
863
864 if (samples_per_channel != input_stream.num_frames()) {
865 return kBadDataLengthError;
866 }
867 return ProcessStream(src, input_stream, output_stream, dest);
868}
869
870int AudioProcessingImpl::ProcessStream(const float* const* src,
871 const StreamConfig& input_config,
872 const StreamConfig& output_config,
873 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800874 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800875 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700876 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800877 {
878 // Acquire the capture lock in order to safely call the function
879 // that retrieves the render side data. This function accesses apm
880 // getters that need the capture lock held when being called.
881 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700882 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800883
884 if (!src || !dest) {
885 return kNullPointerError;
886 }
887
888 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700889 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000890 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000891
Michael Graczyk86c6d332015-07-23 11:41:39 -0700892 processing_config.input_stream() = input_config;
893 processing_config.output_stream() = output_config;
894
peahdf3efa82015-11-28 12:35:15 -0800895 {
896 // Do conditional reinitialization.
897 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700898 RETURN_ON_ERR(
899 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800900 }
901 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700902 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
903 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000904
aleloi868f32f2017-05-23 07:20:05 -0700905 if (aec_dump_) {
906 RecordUnprocessedCaptureStream(src);
907 }
908
peahdf3efa82015-11-28 12:35:15 -0800909 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700910 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800911 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000912
aleloi868f32f2017-05-23 07:20:05 -0700913 if (aec_dump_) {
914 RecordProcessedCaptureStream(dest);
915 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000916 return kNoError;
917}
918
peah9e6a2902017-05-15 07:19:21 -0700919void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700920 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
921 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700922 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700923
kwibergaf476c72016-11-28 15:21:39 -0800924 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700925
926 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700927 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700928 // The data queue is full and needs to be emptied.
929 EmptyQueuedRenderAudio();
930
931 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700932 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700933 RTC_DCHECK(result);
934 }
935
936 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
937 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700938 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700939
940 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700941 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700942 // The data queue is full and needs to be emptied.
943 EmptyQueuedRenderAudio();
944
945 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700946 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700947 RTC_DCHECK(result);
948 }
peah701d6282016-10-25 05:42:20 -0700949
950 if (!constants_.use_experimental_agc) {
951 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
952 // Insert the samples into the queue.
953 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
954 // The data queue is full and needs to be emptied.
955 EmptyQueuedRenderAudio();
956
957 // Retry the insert (should always work).
958 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
959 RTC_DCHECK(result);
960 }
961 }
peah9e6a2902017-05-15 07:19:21 -0700962}
ivoc9f4a4a02016-10-28 05:39:16 -0700963
peah9e6a2902017-05-15 07:19:21 -0700964void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700965 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
966
967 // Insert the samples into the queue.
968 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
969 // The data queue is full and needs to be emptied.
970 EmptyQueuedRenderAudio();
971
972 // Retry the insert (should always work).
973 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
974 RTC_DCHECK(result);
975 }
peah764e3642016-10-22 05:04:30 -0700976}
977
978void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700979 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700980 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700981 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700982 EchoCancellationImpl::NumCancellersRequired(
983 num_output_channels(), num_reverse_channels()));
984
peah701d6282016-10-25 05:42:20 -0700985 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700986 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700987 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700988 EchoControlMobileImpl::NumCancellersRequired(
989 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700990
peah701d6282016-10-25 05:42:20 -0700991 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700992 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700993
ivoc9f4a4a02016-10-28 05:39:16 -0700994 const size_t new_red_render_queue_element_max_size =
995 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
996
peaha0624602016-10-25 04:45:24 -0700997 // Reallocate the queues if the queue item sizes are too small to fit the
998 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700999 if (aec_render_queue_element_max_size_ <
1000 new_aec_render_queue_element_max_size) {
1001 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001002
peaha0624602016-10-25 04:45:24 -07001003 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001004 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001005
peah701d6282016-10-25 05:42:20 -07001006 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001007 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1008 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001009 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001010 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001011
peah701d6282016-10-25 05:42:20 -07001012 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1013 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001014 } else {
peah701d6282016-10-25 05:42:20 -07001015 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001016 }
1017
peah701d6282016-10-25 05:42:20 -07001018 if (aecm_render_queue_element_max_size_ <
1019 new_aecm_render_queue_element_max_size) {
1020 aecm_render_queue_element_max_size_ =
1021 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001022
1023 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001024 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001025
peah701d6282016-10-25 05:42:20 -07001026 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001027 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1028 kMaxNumFramesToBuffer, template_queue_element,
1029 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001030 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001031
peah701d6282016-10-25 05:42:20 -07001032 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1033 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001034 } else {
peah701d6282016-10-25 05:42:20 -07001035 aecm_render_signal_queue_->Clear();
1036 }
1037
1038 if (agc_render_queue_element_max_size_ <
1039 new_agc_render_queue_element_max_size) {
1040 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1041
1042 std::vector<int16_t> template_queue_element(
1043 agc_render_queue_element_max_size_);
1044
1045 agc_render_signal_queue_.reset(
1046 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1047 kMaxNumFramesToBuffer, template_queue_element,
1048 RenderQueueItemVerifier<int16_t>(
1049 agc_render_queue_element_max_size_)));
1050
1051 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1052 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1053 } else {
1054 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001055 }
ivoc9f4a4a02016-10-28 05:39:16 -07001056
1057 if (red_render_queue_element_max_size_ <
1058 new_red_render_queue_element_max_size) {
1059 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1060
1061 std::vector<float> template_queue_element(
1062 red_render_queue_element_max_size_);
1063
1064 red_render_signal_queue_.reset(
1065 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1066 kMaxNumFramesToBuffer, template_queue_element,
1067 RenderQueueItemVerifier<float>(
1068 red_render_queue_element_max_size_)));
1069
1070 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1071 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1072 } else {
1073 red_render_signal_queue_->Clear();
1074 }
peah764e3642016-10-22 05:04:30 -07001075}
1076
1077void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1078 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001079 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001080 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001081 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001082 }
1083
peah701d6282016-10-25 05:42:20 -07001084 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001085 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001086 aecm_capture_queue_buffer_);
1087 }
1088
1089 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1090 public_submodules_->gain_control->ProcessRenderAudio(
1091 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001092 }
ivoc9f4a4a02016-10-28 05:39:16 -07001093
1094 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001095 RTC_DCHECK(private_submodules_->echo_detector);
1096 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001097 red_capture_queue_buffer_);
1098 }
peah764e3642016-10-22 05:04:30 -07001099}
1100
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001101int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001102 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001103 {
1104 // Acquire the capture lock in order to safely call the function
1105 // that retrieves the render side data. This function accesses apm
1106 // getters that need the capture lock held when being called.
1107 // The lock needs to be released as
1108 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1109 // as well.
1110 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001111 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001112 }
peahfa6228e2015-11-16 16:27:42 -08001113
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001114 if (!frame) {
1115 return kNullPointerError;
1116 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001117 // Must be a native rate.
1118 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1119 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001120 frame->sample_rate_hz_ != kSampleRate32kHz &&
1121 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001122 return kBadSampleRateError;
1123 }
peah192164e2015-11-17 02:16:45 -08001124
peahdf3efa82015-11-28 12:35:15 -08001125 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001126 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001127 {
1128 // Aquire lock for the access of api_format.
1129 // The lock is released immediately due to the conditional
1130 // reinitialization.
1131 rtc::CritScope cs_capture(&crit_capture_);
1132 // TODO(ajm): The input and output rates and channels are currently
1133 // constrained to be identical in the int16 interface.
1134 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001135
1136 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001137 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001138 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1139 processing_config.input_stream().set_num_channels(frame->num_channels_);
1140 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1141 processing_config.output_stream().set_num_channels(frame->num_channels_);
1142
peahdf3efa82015-11-28 12:35:15 -08001143 {
1144 // Do conditional reinitialization.
1145 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001146 RETURN_ON_ERR(
1147 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001148 }
1149 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001150 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001151 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001152 return kBadDataLengthError;
1153 }
1154
aleloi868f32f2017-05-23 07:20:05 -07001155 if (aec_dump_) {
1156 RecordUnprocessedCaptureStream(*frame);
1157 }
1158
peahdf3efa82015-11-28 12:35:15 -08001159 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001160 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001161 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001162 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1163 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001164
aleloi868f32f2017-05-23 07:20:05 -07001165 if (aec_dump_) {
1166 RecordProcessedCaptureStream(*frame);
1167 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001168
1169 return kNoError;
1170}
1171
peahde65ddc2016-09-16 15:02:15 -07001172int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001173 // Ensure that not both the AEC and AECM are active at the same time.
1174 // TODO(peah): Simplify once the public API Enable functions for these
1175 // are moved to APM.
1176 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1177 public_submodules_->echo_control_mobile->is_enabled()));
1178
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001179 MaybeUpdateHistograms();
1180
peahde65ddc2016-09-16 15:02:15 -07001181 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001182
peah1b08dc32016-12-20 13:45:58 -08001183 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001184 capture_buffer->channels_const()[0],
1185 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001186 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1187 if (log_rms) {
1188 capture_rms_interval_counter_ = 0;
1189 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001190 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1191 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1192 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1193 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001194 }
1195
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001196 if (private_submodules_->echo_controller) {
Per Åhgren9aed31c2017-06-29 20:23:27 +02001197 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1198 // issues have been addressed.
1199 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001200 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001201 }
1202
peahbe615622016-02-13 16:40:47 -08001203 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001204 public_submodules_->gain_control->is_enabled()) {
1205 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001206 capture_buffer->channels()[0], capture_buffer->num_channels(),
1207 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001208 }
1209
peah2ace3f92016-09-10 04:42:27 -07001210 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1211 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001212 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1213 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001214 }
1215
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001216 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001217 // Force down-mixing of the number of channels after the detection of
1218 // capture signal saturation.
1219 // TODO(peah): Look into ensuring that this kind of tampering with the
1220 // AudioBuffer functionality should not be needed.
1221 capture_buffer->set_num_channels(1);
1222 }
1223
aluebsb2328d12016-01-11 20:32:29 -08001224 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001225 private_submodules_->beamformer->AnalyzeChunk(
1226 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001227 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001228 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001229 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001230
peahe0eae3c2016-12-14 01:16:23 -08001231 // TODO(peah): Move the AEC3 low-cut filter to this place.
1232 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001233 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001234 private_submodules_->low_cut_filter->Process(capture_buffer);
1235 }
peahde65ddc2016-09-16 15:02:15 -07001236 RETURN_ON_ERR(
1237 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1238 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001239
1240 // Ensure that the stream delay was set before the call to the
1241 // AEC ProcessCaptureAudio function.
1242 if (public_submodules_->echo_cancellation->is_enabled() &&
1243 !was_stream_delay_set()) {
1244 return AudioProcessing::kStreamParameterNotSetError;
1245 }
1246
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001247 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001248 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1249
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001250 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001251 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001252 } else {
1253 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1254 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001255 }
1256
peahdf3efa82015-11-28 12:35:15 -08001257 if (public_submodules_->echo_control_mobile->is_enabled() &&
1258 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001259 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001260 }
peahde65ddc2016-09-16 15:02:15 -07001261 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001262#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001263 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001264 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001265 int gain_db = public_submodules_->gain_control->is_enabled() ?
1266 public_submodules_->gain_control->compression_gain_db() :
1267 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001268 float gain = std::pow(10.f, gain_db / 20.f);
1269 gain *= capture_nonlocked_.level_controller_enabled ?
1270 private_submodules_->level_controller->GetLastGain() :
1271 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001272 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001273 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001274 }
peah1bcfce52016-08-26 07:16:04 -07001275#endif
peah253534d2016-03-15 04:32:28 -07001276
1277 // Ensure that the stream delay was set before the call to the
1278 // AECM ProcessCaptureAudio function.
1279 if (public_submodules_->echo_control_mobile->is_enabled() &&
1280 !was_stream_delay_set()) {
1281 return AudioProcessing::kStreamParameterNotSetError;
1282 }
1283
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001284 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001285 public_submodules_->echo_cancellation->is_enabled())) {
1286 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1287 capture_buffer, stream_delay_ms()));
1288 }
ivoc9f4a4a02016-10-28 05:39:16 -07001289
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001290 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001291 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001292 }
1293
peahde65ddc2016-09-16 15:02:15 -07001294 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001295
peahbe615622016-02-13 16:40:47 -08001296 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001297 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001298 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001299 private_submodules_->beamformer->is_target_present())) {
1300 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001301 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1302 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001303 }
peahb8fbb542016-03-15 02:28:08 -07001304 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001305 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001306
peah2ace3f92016-09-10 04:42:27 -07001307 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1308 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001309 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1310 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001311 }
1312
peah9e6a2902017-05-15 07:19:21 -07001313 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001314 RTC_DCHECK(private_submodules_->echo_detector);
1315 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001316 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1317 capture_buffer->num_frames()));
1318 }
1319
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001320 // TODO(aluebs): Investigate if the transient suppression placement should be
1321 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001322 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001323 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001324 private_submodules_->agc_manager.get()
1325 ? private_submodules_->agc_manager->voice_probability()
1326 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001327
peahdf3efa82015-11-28 12:35:15 -08001328 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001329 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1330 capture_buffer->num_channels(),
1331 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1332 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1333 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001334 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001335 }
1336
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001337 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001338 private_submodules_->gain_controller2->Process(capture_buffer);
1339 }
1340
peahca4cac72016-06-29 15:26:12 -07001341 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001342 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001343 }
1344
Sam Zackrisson0beac582017-09-25 12:04:02 +02001345 if (private_submodules_->capture_post_processor) {
1346 private_submodules_->capture_post_processor->Process(capture_buffer);
1347 }
1348
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001349 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001350 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001351
peah1b08dc32016-12-20 13:45:58 -08001352 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1353 capture_buffer->channels_const()[0],
1354 capture_nonlocked_.capture_processing_format.num_frames()));
1355 if (log_rms) {
1356 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1357 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1358 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1359 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1360 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1361 }
1362
peahdf3efa82015-11-28 12:35:15 -08001363 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001364 return kNoError;
1365}
1366
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001367int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001368 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001369 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001370 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001371 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001372 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001373 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001374 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001375 };
1376 if (samples_per_channel != reverse_config.num_frames()) {
1377 return kBadDataLengthError;
1378 }
peahdf3efa82015-11-28 12:35:15 -08001379 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001380}
1381
peahde65ddc2016-09-16 15:02:15 -07001382int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1383 const StreamConfig& input_config,
1384 const StreamConfig& output_config,
1385 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001386 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001387 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001388 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001389 if (submodule_states_.RenderMultiBandProcessingActive() ||
1390 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001391 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1392 dest);
peah2ace3f92016-09-10 04:42:27 -07001393 } else if (formats_.api_format.reverse_input_stream() !=
1394 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001395 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1396 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001397 } else {
peahde65ddc2016-09-16 15:02:15 -07001398 CopyAudioIfNeeded(src, input_config.num_frames(),
1399 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001400 }
1401
1402 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001403}
1404
peahdf3efa82015-11-28 12:35:15 -08001405int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001406 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001407 const StreamConfig& input_config,
1408 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001409 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001410 return kNullPointerError;
1411 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001412
peahde65ddc2016-09-16 15:02:15 -07001413 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001414 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001415 }
1416
peahdf3efa82015-11-28 12:35:15 -08001417 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001418 processing_config.reverse_input_stream() = input_config;
1419 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001420
peahdf3efa82015-11-28 12:35:15 -08001421 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001422 assert(input_config.num_frames() ==
1423 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001424
aleloi868f32f2017-05-23 07:20:05 -07001425 if (aec_dump_) {
1426 const size_t channel_size =
1427 formats_.api_format.reverse_input_stream().num_frames();
1428 const size_t num_channels =
1429 formats_.api_format.reverse_input_stream().num_channels();
1430 aec_dump_->WriteRenderStreamMessage(
1431 FloatAudioFrame(src, num_channels, channel_size));
1432 }
peahdf3efa82015-11-28 12:35:15 -08001433 render_.render_audio->CopyFrom(src,
1434 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001435 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001436}
1437
1438int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001439 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001440 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001441 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001442 return kNullPointerError;
1443 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001444 // Must be a native rate.
1445 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1446 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001447 frame->sample_rate_hz_ != kSampleRate32kHz &&
1448 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001449 return kBadSampleRateError;
1450 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001451
Michael Graczyk86c6d332015-07-23 11:41:39 -07001452 if (frame->num_channels_ <= 0) {
1453 return kBadNumberChannelsError;
1454 }
1455
peahdf3efa82015-11-28 12:35:15 -08001456 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001457 processing_config.reverse_input_stream().set_sample_rate_hz(
1458 frame->sample_rate_hz_);
1459 processing_config.reverse_input_stream().set_num_channels(
1460 frame->num_channels_);
1461 processing_config.reverse_output_stream().set_sample_rate_hz(
1462 frame->sample_rate_hz_);
1463 processing_config.reverse_output_stream().set_num_channels(
1464 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001465
peahdf3efa82015-11-28 12:35:15 -08001466 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001467 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001468 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001469 return kBadDataLengthError;
1470 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001471
aleloi868f32f2017-05-23 07:20:05 -07001472 if (aec_dump_) {
1473 aec_dump_->WriteRenderStreamMessage(*frame);
1474 }
1475
peahdf3efa82015-11-28 12:35:15 -08001476 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001477 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001478 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001479 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1480 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001481 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001482}
niklase@google.com470e71d2011-07-07 08:21:25 +00001483
peahde65ddc2016-09-16 15:02:15 -07001484int AudioProcessingImpl::ProcessRenderStreamLocked() {
1485 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001486
1487 QueueNonbandedRenderAudio(render_buffer);
1488
Alex Loiko5825aa62017-12-18 16:02:40 +01001489 if (private_submodules_->render_pre_processor) {
1490 private_submodules_->render_pre_processor->Process(render_buffer);
1491 }
1492
peah2ace3f92016-09-10 04:42:27 -07001493 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001494 SampleRateSupportsMultiBand(
1495 formats_.render_processing_format.sample_rate_hz())) {
1496 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001497 }
1498
peah1bcfce52016-08-26 07:16:04 -07001499#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001500 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001501 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001502 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001503 }
peah1bcfce52016-08-26 07:16:04 -07001504#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001505
peahce4d9152017-05-19 01:28:05 -07001506 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1507 QueueBandedRenderAudio(render_buffer);
1508 }
1509
peahe0eae3c2016-12-14 01:16:23 -08001510 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001511 if (private_submodules_->echo_controller) {
1512 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001513 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001514
peah2ace3f92016-09-10 04:42:27 -07001515 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001516 SampleRateSupportsMultiBand(
1517 formats_.render_processing_format.sample_rate_hz())) {
1518 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001519 }
1520
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001521 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001522}
1523
1524int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001525 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001526 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001527 capture_.was_stream_delay_set = true;
1528 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001529
niklase@google.com470e71d2011-07-07 08:21:25 +00001530 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001531 delay = 0;
1532 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001533 }
1534
1535 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1536 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001537 delay = 500;
1538 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001539 }
1540
peahdf3efa82015-11-28 12:35:15 -08001541 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001542 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001543}
1544
1545int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001546 // Used as callback from submodules, hence locking is not allowed.
1547 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001548}
1549
1550bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001551 // Used as callback from submodules, hence locking is not allowed.
1552 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001553}
1554
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001555void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001556 rtc::CritScope cs(&crit_capture_);
1557 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001558}
1559
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001560void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001561 rtc::CritScope cs(&crit_capture_);
1562 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001563}
1564
1565int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001566 rtc::CritScope cs(&crit_capture_);
1567 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001568}
1569
aleloi868f32f2017-05-23 07:20:05 -07001570void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1571 RTC_DCHECK(aec_dump);
1572 rtc::CritScope cs_render(&crit_render_);
1573 rtc::CritScope cs_capture(&crit_capture_);
1574
1575 // The previously attached AecDump will be destroyed with the
1576 // 'aec_dump' parameter, which is after locks are released.
1577 aec_dump_.swap(aec_dump);
1578 WriteAecDumpConfigMessage(true);
1579 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1580}
1581
1582void AudioProcessingImpl::DetachAecDump() {
1583 // The d-tor of a task-queue based AecDump blocks until all pending
1584 // tasks are done. This construction avoids blocking while holding
1585 // the render and capture locks.
1586 std::unique_ptr<AecDump> aec_dump = nullptr;
1587 {
1588 rtc::CritScope cs_render(&crit_render_);
1589 rtc::CritScope cs_capture(&crit_capture_);
1590 aec_dump = std::move(aec_dump_);
1591 }
1592}
1593
ivoc4e477a12017-01-15 08:29:46 -08001594AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1595 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1596 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1597 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1598 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1599}
1600
1601AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1602 const AudioProcessingStatistics& other) = default;
1603
1604AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1605 default;
1606
ivoc3e9a5372016-10-28 07:55:33 -07001607// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1608AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1609 const {
1610 return AudioProcessingStatistics();
1611}
1612
Ivo Creusenae026092017-11-20 13:07:16 +01001613// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001614AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001615 bool has_remote_tracks) const {
1616 return AudioProcessingStats();
1617}
1618
ivoc3e9a5372016-10-28 07:55:33 -07001619AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1620 const {
1621 AudioProcessingStatistics stats;
1622 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001623 if (private_submodules_->echo_controller) {
1624 rtc::CritScope cs_capture(&crit_capture_);
1625 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1626 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1627 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1628 // Instant value will also be used for min, max and average.
1629 stats.echo_return_loss.Set(erl, erl, erl, erl);
1630 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1631 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1632 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001633 stats.a_nlp.Set(metrics.a_nlp);
1634 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1635 stats.echo_return_loss.Set(metrics.echo_return_loss);
1636 stats.echo_return_loss_enhancement.Set(
1637 metrics.echo_return_loss_enhancement);
1638 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1639 }
ivoc9c192b22017-03-16 04:22:14 -07001640 {
1641 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001642 RTC_DCHECK(private_submodules_->echo_detector);
1643 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1644 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001645 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001646 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001647 }
ivoc3e9a5372016-10-28 07:55:33 -07001648 public_submodules_->echo_cancellation->GetDelayMetrics(
1649 &stats.delay_median, &stats.delay_standard_deviation,
1650 &stats.fraction_poor_delays);
1651 return stats;
1652}
1653
Ivo Creusen56d46092017-11-24 17:29:59 +01001654AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001655 bool has_remote_tracks) const {
1656 AudioProcessingStats stats;
1657 if (has_remote_tracks) {
1658 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001659 if (private_submodules_->echo_controller) {
1660 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001661 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1662 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001663 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001664 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001665 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001666 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1667 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001668 if (metrics.divergent_filter_fraction != -1.0f) {
1669 stats.divergent_filter_fraction =
1670 rtc::Optional<double>(metrics.divergent_filter_fraction);
1671 }
1672 if (metrics.echo_return_loss.instant != -100) {
1673 stats.echo_return_loss =
1674 rtc::Optional<double>(metrics.echo_return_loss.instant);
1675 }
1676 if (metrics.echo_return_loss_enhancement.instant != -100) {
1677 stats.echo_return_loss_enhancement =
1678 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1679 }
1680 }
1681 if (config_.residual_echo_detector.enabled) {
1682 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001683 RTC_DCHECK(private_submodules_->echo_detector);
1684 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1685 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001686 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001687 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001688 }
1689 int delay_median, delay_std;
1690 float fraction_poor_delays;
1691 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1692 &delay_median, &delay_std, &fraction_poor_delays) ==
1693 Error::kNoError) {
1694 if (delay_median >= 0) {
1695 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1696 }
1697 if (delay_std >= 0) {
1698 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1699 }
1700 }
1701 }
1702 return stats;
1703}
1704
niklase@google.com470e71d2011-07-07 08:21:25 +00001705EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001706 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001707}
1708
1709EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001710 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001711}
1712
1713GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001714 if (constants_.use_experimental_agc) {
1715 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001716 }
peahbfa97112016-03-10 21:09:04 -08001717 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001718}
1719
1720HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001721 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001722}
1723
1724LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001725 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001726}
1727
1728NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001729 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001730}
1731
1732VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001733 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001734}
1735
peah8271d042016-11-22 07:24:52 -08001736void AudioProcessingImpl::MutateConfig(
1737 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1738 rtc::CritScope cs_render(&crit_render_);
1739 rtc::CritScope cs_capture(&crit_capture_);
1740 mutator(&config_);
1741 ApplyConfig(config_);
1742}
1743
1744AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1745 rtc::CritScope cs_render(&crit_render_);
1746 rtc::CritScope cs_capture(&crit_capture_);
1747 return config_;
1748}
1749
peah2ace3f92016-09-10 04:42:27 -07001750bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1751 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001752 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001753 public_submodules_->echo_cancellation->is_enabled(),
1754 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001755 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001756 public_submodules_->noise_suppression->is_enabled(),
1757 capture_nonlocked_.intelligibility_enabled,
1758 capture_nonlocked_.beamformer_enabled,
1759 public_submodules_->gain_control->is_enabled(),
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001760 config_.gain_controller2.enabled,
peah2ace3f92016-09-10 04:42:27 -07001761 capture_nonlocked_.level_controller_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001762 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001763 public_submodules_->voice_detection->is_enabled(),
1764 public_submodules_->level_estimator->is_enabled(),
1765 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001766}
1767
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001768
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001769void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001770 if (capture_.transient_suppressor_enabled) {
1771 if (!public_submodules_->transient_suppressor.get()) {
1772 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001773 }
peahdf3efa82015-11-28 12:35:15 -08001774 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001775 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1776 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001777 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001778}
1779
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001780void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001781 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001782 if (!private_submodules_->beamformer) {
1783 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001784 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001785 }
peahdf3efa82015-11-28 12:35:15 -08001786 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1787 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001788 }
1789}
1790
ekmeyerson60d9b332015-08-14 10:35:55 -07001791void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001792#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001793 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001794 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001795 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001796 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001797 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001798 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001799 }
peah1bcfce52016-08-26 07:16:04 -07001800#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001801}
1802
peah8271d042016-11-22 07:24:52 -08001803void AudioProcessingImpl::InitializeLowCutFilter() {
1804 if (config_.high_pass_filter.enabled) {
1805 private_submodules_->low_cut_filter.reset(
1806 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1807 } else {
1808 private_submodules_->low_cut_filter.reset();
1809 }
1810}
alessiob3ec96df2017-05-22 06:57:06 -07001811
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001812void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001813 if (echo_control_factory_) {
1814 private_submodules_->echo_controller =
1815 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001816 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001817 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001818 }
1819}
peah8271d042016-11-22 07:24:52 -08001820
alessiob3ec96df2017-05-22 06:57:06 -07001821void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001822 if (config_.gain_controller2.enabled) {
1823 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001824 }
1825}
1826
peahca4cac72016-06-29 15:26:12 -07001827void AudioProcessingImpl::InitializeLevelController() {
1828 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1829}
1830
ivoc9f4a4a02016-10-28 05:39:16 -07001831void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001832 RTC_DCHECK(private_submodules_->echo_detector);
1833 private_submodules_->echo_detector->Initialize(proc_sample_rate_hz(),
1834 num_proc_channels());
ivoc9f4a4a02016-10-28 05:39:16 -07001835}
1836
Sam Zackrisson0beac582017-09-25 12:04:02 +02001837void AudioProcessingImpl::InitializePostProcessor() {
1838 if (private_submodules_->capture_post_processor) {
1839 private_submodules_->capture_post_processor->Initialize(
1840 proc_sample_rate_hz(), num_proc_channels());
1841 }
1842}
1843
Alex Loiko5825aa62017-12-18 16:02:40 +01001844void AudioProcessingImpl::InitializePreProcessor() {
1845 if (private_submodules_->render_pre_processor) {
1846 private_submodules_->render_pre_processor->Initialize(
1847 formats_.render_processing_format.sample_rate_hz(),
1848 formats_.render_processing_format.num_channels());
1849 }
1850}
1851
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001852void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001853 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001854
1855 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001856 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001857 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001858 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001859 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001860 capture_.stream_delay_jumps = 0;
1861 }
1862 if (capture_.aec_system_delay_jumps == -1 &&
1863 echo_cancellation()->stream_has_echo()) {
1864 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001865 }
1866
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001867 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001868 const int diff_stream_delay_ms =
1869 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1870 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1871 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001872 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1873 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001874 if (capture_.stream_delay_jumps == -1) {
1875 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001876 }
peahdf3efa82015-11-28 12:35:15 -08001877 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001878 }
peahdf3efa82015-11-28 12:35:15 -08001879 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001880
1881 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001882 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001883 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001884 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001885 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001886 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1887 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001888 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001889 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001890 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001891 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001892 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1893 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1894 100);
peahdf3efa82015-11-28 12:35:15 -08001895 if (capture_.aec_system_delay_jumps == -1) {
1896 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001897 }
peahdf3efa82015-11-28 12:35:15 -08001898 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001899 }
peahdf3efa82015-11-28 12:35:15 -08001900 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001901 }
1902}
1903
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001904void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001905 // Run in a single-threaded manner.
1906 rtc::CritScope cs_render(&crit_render_);
1907 rtc::CritScope cs_capture(&crit_capture_);
1908
1909 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001910 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001911 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001912 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001913 }
peahdf3efa82015-11-28 12:35:15 -08001914 capture_.stream_delay_jumps = -1;
1915 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001916
peahdf3efa82015-11-28 12:35:15 -08001917 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001918 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1919 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001920 }
peahdf3efa82015-11-28 12:35:15 -08001921 capture_.aec_system_delay_jumps = -1;
1922 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001923}
1924
aleloi868f32f2017-05-23 07:20:05 -07001925void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1926 if (!aec_dump_) {
1927 return;
1928 }
1929 std::string experiments_description =
1930 public_submodules_->echo_cancellation->GetExperimentsDescription();
1931 // TODO(peah): Add semicolon-separated concatenations of experiment
1932 // descriptions for other submodules.
1933 if (capture_nonlocked_.level_controller_enabled) {
1934 experiments_description += "LevelController;";
1935 }
1936 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1937 experiments_description += "AgcClippingLevelExperiment;";
1938 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001939 if (capture_nonlocked_.echo_controller_enabled) {
1940 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001941 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001942 if (config_.gain_controller2.enabled) {
1943 experiments_description += "GainController2;";
1944 }
aleloi868f32f2017-05-23 07:20:05 -07001945
1946 InternalAPMConfig apm_config;
1947
1948 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1949 apm_config.aec_delay_agnostic_enabled =
1950 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1951 apm_config.aec_drift_compensation_enabled =
1952 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1953 apm_config.aec_extended_filter_enabled =
1954 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1955 apm_config.aec_suppression_level = static_cast<int>(
1956 public_submodules_->echo_cancellation->suppression_level());
1957
1958 apm_config.aecm_enabled =
1959 public_submodules_->echo_control_mobile->is_enabled();
1960 apm_config.aecm_comfort_noise_enabled =
1961 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1962 apm_config.aecm_routing_mode =
1963 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1964
1965 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1966 apm_config.agc_mode =
1967 static_cast<int>(public_submodules_->gain_control->mode());
1968 apm_config.agc_limiter_enabled =
1969 public_submodules_->gain_control->is_limiter_enabled();
1970 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1971
1972 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1973
1974 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1975 apm_config.ns_level =
1976 static_cast<int>(public_submodules_->noise_suppression->level());
1977
1978 apm_config.transient_suppression_enabled =
1979 capture_.transient_suppressor_enabled;
1980 apm_config.intelligibility_enhancer_enabled =
1981 capture_nonlocked_.intelligibility_enabled;
1982 apm_config.experiments_description = experiments_description;
1983
1984 if (!forced && apm_config == apm_config_for_aec_dump_) {
1985 return;
1986 }
1987 aec_dump_->WriteConfig(apm_config);
1988 apm_config_for_aec_dump_ = apm_config;
1989}
1990
1991void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1992 const float* const* src) {
1993 RTC_DCHECK(aec_dump_);
1994 WriteAecDumpConfigMessage(false);
1995
1996 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1997 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1998 aec_dump_->AddCaptureStreamInput(
1999 FloatAudioFrame(src, num_channels, channel_size));
2000 RecordAudioProcessingState();
2001}
2002
2003void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2004 const AudioFrame& capture_frame) {
2005 RTC_DCHECK(aec_dump_);
2006 WriteAecDumpConfigMessage(false);
2007
2008 aec_dump_->AddCaptureStreamInput(capture_frame);
2009 RecordAudioProcessingState();
2010}
2011
2012void AudioProcessingImpl::RecordProcessedCaptureStream(
2013 const float* const* processed_capture_stream) {
2014 RTC_DCHECK(aec_dump_);
2015
2016 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2017 const size_t num_channels =
2018 formats_.api_format.output_stream().num_channels();
2019 aec_dump_->AddCaptureStreamOutput(
2020 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
2021 aec_dump_->WriteCaptureStreamMessage();
2022}
2023
2024void AudioProcessingImpl::RecordProcessedCaptureStream(
2025 const AudioFrame& processed_capture_frame) {
2026 RTC_DCHECK(aec_dump_);
2027
2028 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2029 aec_dump_->WriteCaptureStreamMessage();
2030}
2031
2032void AudioProcessingImpl::RecordAudioProcessingState() {
2033 RTC_DCHECK(aec_dump_);
2034 AecDump::AudioProcessingState audio_proc_state;
2035 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2036 audio_proc_state.drift =
2037 public_submodules_->echo_cancellation->stream_drift_samples();
2038 audio_proc_state.level = gain_control()->stream_analog_level();
2039 audio_proc_state.keypress = capture_.key_pressed;
2040 aec_dump_->AddAudioProcessingState(audio_proc_state);
2041}
2042
kwiberg83ffe452016-08-29 14:46:07 -07002043AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2044 bool transient_suppressor_enabled,
2045 const std::vector<Point>& array_geometry,
2046 SphericalPointf target_direction)
2047 : aec_system_delay_jumps(-1),
2048 delay_offset_ms(0),
2049 was_stream_delay_set(false),
2050 last_stream_delay_ms(0),
2051 last_aec_system_delay_ms(0),
2052 stream_delay_jumps(-1),
2053 output_will_be_muted(false),
2054 key_pressed(false),
2055 transient_suppressor_enabled(transient_suppressor_enabled),
2056 array_geometry(array_geometry),
2057 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002058 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002059 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002060 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002061
2062AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2063
2064AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2065
2066AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2067
niklase@google.com470e71d2011-07-07 08:21:25 +00002068} // namespace webrtc