blob: 526d7d5974d7e11c858bdc1ffe98e23e6a9e6cbc [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
25#include "modules/audio_processing/beamformer/nonlinear_beamformer.h"
26#include "modules/audio_processing/common.h"
27#include "modules/audio_processing/echo_cancellation_impl.h"
28#include "modules/audio_processing/echo_control_mobile_impl.h"
29#include "modules/audio_processing/gain_control_for_experimental_agc.h"
30#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010031#include "modules/audio_processing/gain_controller2.h"
Per Åhgren13735822018-02-12 21:42:56 +010032#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/checks.h"
34#include "rtc_base/logging.h"
35#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020036#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070038#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070040#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "modules/audio_processing/level_estimator_impl.h"
42#include "modules/audio_processing/low_cut_filter.h"
43#include "modules/audio_processing/noise_suppression_impl.h"
44#include "modules/audio_processing/residual_echo_detector.h"
45#include "modules/audio_processing/transient/transient_suppressor.h"
46#include "modules/audio_processing/voice_detection_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010047#include "rtc_base/atomicops.h"
Karl Wiberg6a4d4112018-03-23 10:39:34 +010048#include "rtc_base/system/file_wrapper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000050
peah1bcfce52016-08-26 07:16:04 -070051// Check to verify that the define for the intelligibility enhancer is properly
52// set.
53#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
54 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
55 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
56#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
57#endif
58
Michael Graczyk86c6d332015-07-23 11:41:39 -070059#define RETURN_ON_ERR(expr) \
60 do { \
61 int err = (expr); \
62 if (err != kNoError) { \
63 return err; \
64 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000065 } while (0)
66
niklase@google.com470e71d2011-07-07 08:21:25 +000067namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070068
kwibergd59d3bb2016-09-13 07:49:33 -070069constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070070
Michael Graczyk86c6d332015-07-23 11:41:39 -070071namespace {
72
73static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
74 switch (layout) {
75 case AudioProcessing::kMono:
76 case AudioProcessing::kStereo:
77 return false;
78 case AudioProcessing::kMonoAndKeyboard:
79 case AudioProcessing::kStereoAndKeyboard:
80 return true;
81 }
82
kwiberg9e2be5f2016-09-14 05:23:22 -070083 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070084 return false;
85}
aluebsdf6416a2016-03-16 18:26:35 -070086
peah2ace3f92016-09-10 04:42:27 -070087bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070088 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
89 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
90}
91
peah2ace3f92016-09-10 04:42:27 -070092int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
93#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070094 constexpr int kMaxSplittingNativeProcessRate =
95 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070096#else
kwibergd59d3bb2016-09-13 07:49:33 -070097 constexpr int kMaxSplittingNativeProcessRate =
98 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070099#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700100 static_assert(
101 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
102 "");
peah2ace3f92016-09-10 04:42:27 -0700103 const int uppermost_native_rate = band_splitting_required
104 ? kMaxSplittingNativeProcessRate
105 : AudioProcessing::kSampleRate48kHz;
106
107 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
108 if (rate >= uppermost_native_rate) {
109 return uppermost_native_rate;
110 }
111 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700112 return rate;
113 }
114 }
peah2ace3f92016-09-10 04:42:27 -0700115 RTC_NOTREACHED();
116 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700117}
118
peah9e6a2902017-05-15 07:19:21 -0700119// Maximum lengths that frame of samples being passed from the render side to
120// the capture side can have (does not apply to AEC3).
121static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
122static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum number of frames to buffer in the render queue.
125// TODO(peah): Decrease this once we properly handle hugely unbalanced
126// reverse and forward call numbers.
127static const size_t kMaxNumFramesToBuffer = 100;
128
peah8271d042016-11-22 07:24:52 -0800129class HighPassFilterImpl : public HighPassFilter {
130 public:
131 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
132 ~HighPassFilterImpl() override = default;
133
134 // HighPassFilter implementation.
135 int Enable(bool enable) override {
136 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
137 config->high_pass_filter.enabled = enable;
138 });
139
140 return AudioProcessing::kNoError;
141 }
142
143 bool is_enabled() const override {
144 return apm_->GetConfig().high_pass_filter.enabled;
145 }
146
147 private:
148 AudioProcessingImpl* apm_;
149 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
150};
151
aleloi868f32f2017-05-23 07:20:05 -0700152webrtc::InternalAPMStreamsConfig ToStreamsConfig(
153 const ProcessingConfig& api_format) {
154 webrtc::InternalAPMStreamsConfig result;
155 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
156 result.input_num_channels = api_format.input_stream().num_channels();
157 result.output_num_channels = api_format.output_stream().num_channels();
158 result.render_input_num_channels =
159 api_format.reverse_input_stream().num_channels();
160 result.render_input_sample_rate =
161 api_format.reverse_input_stream().sample_rate_hz();
162 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
163 result.render_output_sample_rate =
164 api_format.reverse_output_stream().sample_rate_hz();
165 result.render_output_num_channels =
166 api_format.reverse_output_stream().num_channels();
167 return result;
168}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700169} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000170
171// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000172static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000173
Sam Zackrisson0beac582017-09-25 12:04:02 +0200174AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100175 bool capture_post_processor_enabled,
176 bool render_pre_processor_enabled)
177 : capture_post_processor_enabled_(capture_post_processor_enabled),
178 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700179
180bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800181 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700182 bool echo_canceller_enabled,
183 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700184 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700185 bool noise_suppressor_enabled,
186 bool intelligibility_enhancer_enabled,
187 bool beamformer_enabled,
188 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700189 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200190 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200191 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700192 bool voice_activity_detector_enabled,
193 bool level_estimator_enabled,
194 bool transient_suppressor_enabled) {
195 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800196 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700197 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
198 changed |=
199 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700200 changed |=
201 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700202 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
203 changed |=
204 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
205 changed |= (beamformer_enabled != beamformer_enabled_);
206 changed |=
207 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700208 changed |=
209 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200210 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200211 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700212 changed |= (level_estimator_enabled != level_estimator_enabled_);
213 changed |=
214 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
215 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
216 if (changed) {
peah8271d042016-11-22 07:24:52 -0800217 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700218 echo_canceller_enabled_ = echo_canceller_enabled;
219 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700220 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700221 noise_suppressor_enabled_ = noise_suppressor_enabled;
222 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
223 beamformer_enabled_ = beamformer_enabled;
224 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700225 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200226 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200227 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700228 level_estimator_enabled_ = level_estimator_enabled;
229 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
230 transient_suppressor_enabled_ = transient_suppressor_enabled;
231 }
232
233 changed |= first_update_;
234 first_update_ = false;
235 return changed;
236}
237
238bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
239 const {
240#if WEBRTC_INTELLIGIBILITY_ENHANCER
241 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700242 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700243#else
peah52775842017-05-16 06:14:09 -0700244 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700245#endif
246}
247
248bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
249 const {
peah8271d042016-11-22 07:24:52 -0800250 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700251 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800252 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200253 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700254}
255
peah23ac8b42017-05-23 05:33:56 -0700256bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
257 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200258 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
259 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700260}
261
peah2ace3f92016-09-10 04:42:27 -0700262bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
263 const {
264 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800265 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200266 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700267}
268
Alex Loiko5825aa62017-12-18 16:02:40 +0100269bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
270 const {
271 return render_pre_processor_enabled_;
272}
273
peah2ace3f92016-09-10 04:42:27 -0700274bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
275 const {
276#if WEBRTC_INTELLIGIBILITY_ENHANCER
277 return intelligibility_enhancer_enabled_;
278#else
279 return false;
280#endif
281}
282
solenberg5e465c32015-12-08 13:22:33 -0800283struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800284 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800285 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800286 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800287 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800288 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800289 std::unique_ptr<LevelEstimatorImpl> level_estimator;
290 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
291 std::unique_ptr<VoiceDetectionImpl> voice_detection;
292 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800293 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800294
295 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800296 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700297#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800298 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700299#endif
solenberg5e465c32015-12-08 13:22:33 -0800300};
301
302struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200303 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100304 std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100305 std::unique_ptr<CustomProcessing> render_pre_processor,
306 std::unique_ptr<EchoDetector> echo_detector)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200307 : beamformer(beamformer),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100308 echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100309 capture_post_processor(std::move(capture_post_processor)),
310 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800311 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700312 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800313 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700314 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800315 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100316 std::unique_ptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200317 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100318 std::unique_ptr<CustomProcessing> capture_post_processor;
319 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200320 std::unique_ptr<GainApplier> pre_amplifier;
solenberg5e465c32015-12-08 13:22:33 -0800321};
322
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100323AudioProcessingBuilder::AudioProcessingBuilder() = default;
324AudioProcessingBuilder::~AudioProcessingBuilder() = default;
325
326AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
327 std::unique_ptr<CustomProcessing> capture_post_processing) {
328 capture_post_processing_ = std::move(capture_post_processing);
329 return *this;
330}
331
332AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
333 std::unique_ptr<CustomProcessing> render_pre_processing) {
334 render_pre_processing_ = std::move(render_pre_processing);
335 return *this;
336}
337
338AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
339 std::unique_ptr<EchoControlFactory> echo_control_factory) {
340 echo_control_factory_ = std::move(echo_control_factory);
341 return *this;
342}
343
344AudioProcessingBuilder& AudioProcessingBuilder::SetNonlinearBeamformer(
345 std::unique_ptr<NonlinearBeamformer> nonlinear_beamformer) {
346 nonlinear_beamformer_ = std::move(nonlinear_beamformer);
347 return *this;
348}
349
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100350AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
351 std::unique_ptr<EchoDetector> echo_detector) {
352 echo_detector_ = std::move(echo_detector);
353 return *this;
354}
355
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100356AudioProcessing* AudioProcessingBuilder::Create() {
357 webrtc::Config config;
358 return Create(config);
359}
360
361AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100362 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
363 config, std::move(capture_post_processing_),
364 std::move(render_pre_processing_), std::move(echo_control_factory_),
365 std::move(echo_detector_), nonlinear_beamformer_.release());
366 if (apm->Initialize() != AudioProcessing::kNoError) {
367 delete apm;
368 apm = nullptr;
369 }
370 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100371}
372
peah88ac8532016-09-12 16:47:25 -0700373AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100374 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
375}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000376
Per Åhgren13735822018-02-12 21:42:56 +0100377int AudioProcessingImpl::instance_count_ = 0;
378
Sam Zackrisson0beac582017-09-25 12:04:02 +0200379AudioProcessingImpl::AudioProcessingImpl(
380 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100381 std::unique_ptr<CustomProcessing> capture_post_processor,
382 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200383 std::unique_ptr<EchoControlFactory> echo_control_factory,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100384 std::unique_ptr<EchoDetector> echo_detector,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200385 NonlinearBeamformer* beamformer)
Per Åhgren13735822018-02-12 21:42:56 +0100386 : data_dumper_(
387 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alessio Bazzicac054e782018-04-16 12:10:09 +0200388 runtime_settings_(new SwapQueue<RuntimeSetting>(100)),
389 runtime_settings_enqueuer_(runtime_settings_.get()),
Per Åhgren13735822018-02-12 21:42:56 +0100390 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200391 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100392 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800393 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200394 private_submodules_(
395 new ApmPrivateSubmodules(beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100396 std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100397 std::move(render_pre_processor),
398 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800399 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800400 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000401#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700402 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000403#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700404 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000405#endif
andrew1c7075f2015-06-24 18:14:14 -0700406#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800407 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700408#else
aluebs2a346882016-01-11 18:04:30 -0800409 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700410#endif
aluebs2a346882016-01-11 18:04:30 -0800411 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800412 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700413 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700414 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800415 {
416 rtc::CritScope cs_render(&crit_render_);
417 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000418
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200419 // Mark Echo Controller enabled if a factory is injected.
420 capture_nonlocked_.echo_controller_enabled =
421 static_cast<bool>(echo_control_factory_);
422
peahb624d8c2016-03-05 03:01:14 -0800423 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700424 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800425 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700426 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800427 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700428 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800429 public_submodules_->level_estimator.reset(
430 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800431 public_submodules_->noise_suppression.reset(
432 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800433 public_submodules_->voice_detection.reset(
434 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800435 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800436 new GainControlForExperimentalAgc(
437 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100438
439 // If no echo detector is injected, use the ResidualEchoDetector.
440 if (!private_submodules_->echo_detector) {
441 private_submodules_->echo_detector.reset(new ResidualEchoDetector());
442 }
peahca4cac72016-06-29 15:26:12 -0700443
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200444 // TODO(alessiob): Move the injected gain controller once injection is
445 // implemented.
446 private_submodules_->gain_controller2.reset(new GainController2());
447
Mirko Bonadei675513b2017-11-09 11:09:25 +0100448 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100449 << !!private_submodules_->capture_post_processor
450 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100451 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800452 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000453
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000454 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000455}
456
457AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800458 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800459 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800460 private_submodules_->agc_manager.reset();
461 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800462 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000463}
464
niklase@google.com470e71d2011-07-07 08:21:25 +0000465int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800466 // Run in a single-threaded manner during initialization.
467 rtc::CritScope cs_render(&crit_render_);
468 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000469 return InitializeLocked();
470}
471
peahde65ddc2016-09-16 15:02:15 -0700472int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
473 int capture_output_sample_rate_hz,
474 int render_input_sample_rate_hz,
475 ChannelLayout capture_input_layout,
476 ChannelLayout capture_output_layout,
477 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700478 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700479 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
480 LayoutHasKeyboard(capture_input_layout)},
481 {capture_output_sample_rate_hz,
482 ChannelsFromLayout(capture_output_layout),
483 LayoutHasKeyboard(capture_output_layout)},
484 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
485 LayoutHasKeyboard(render_input_layout)},
486 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
487 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700488
489 return Initialize(processing_config);
490}
491
492int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800493 // Run in a single-threaded manner during initialization.
494 rtc::CritScope cs_render(&crit_render_);
495 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700496 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000497}
498
peahdf3efa82015-11-28 12:35:15 -0800499int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800500 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700501 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800502}
503
peahdf3efa82015-11-28 12:35:15 -0800504int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700505 const ProcessingConfig& processing_config,
506 bool force_initialization) {
507 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800508}
509
peah192164e2015-11-17 02:16:45 -0800510// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800511// their current values (needs to be called while holding the crit_render_lock).
512int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700513 const ProcessingConfig& processing_config,
514 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800515 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700516 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800517 return kNoError;
518 }
peahdf3efa82015-11-28 12:35:15 -0800519
520 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800521 return InitializeLocked(processing_config);
522}
523
niklase@google.com470e71d2011-07-07 08:21:25 +0000524int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200525 UpdateActiveSubmoduleStates();
526
peah522d71b2017-02-23 05:16:26 -0800527 const int capture_audiobuffer_num_channels =
528 capture_nonlocked_.beamformer_enabled
529 ? formats_.api_format.input_stream().num_channels()
530 : formats_.api_format.output_stream().num_channels();
531
peahde65ddc2016-09-16 15:02:15 -0700532 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800533 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700534 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800535 : formats_.api_format.reverse_output_stream().num_frames();
536 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
537 render_.render_audio.reset(new AudioBuffer(
538 formats_.api_format.reverse_input_stream().num_frames(),
539 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700540 formats_.render_processing_format.num_frames(),
541 formats_.render_processing_format.num_channels(),
542 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700543 if (formats_.api_format.reverse_input_stream() !=
544 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800545 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800546 formats_.api_format.reverse_input_stream().num_channels(),
547 formats_.api_format.reverse_input_stream().num_frames(),
548 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800549 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700550 } else {
peahdf3efa82015-11-28 12:35:15 -0800551 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700552 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700553 } else {
peahdf3efa82015-11-28 12:35:15 -0800554 render_.render_audio.reset(nullptr);
555 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700556 }
peahce4d9152017-05-19 01:28:05 -0700557
peahdf3efa82015-11-28 12:35:15 -0800558 capture_.capture_audio.reset(
559 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
560 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700561 capture_nonlocked_.capture_processing_format.num_frames(),
562 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800563 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000564
peahde65ddc2016-09-16 15:02:15 -0700565 public_submodules_->echo_cancellation->Initialize(
566 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
567 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700568 AllocateRenderQueue();
569
ivoc3e9a5372016-10-28 07:55:33 -0700570 int success = public_submodules_->echo_cancellation->enable_metrics(true);
571 RTC_DCHECK_EQ(0, success);
572 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
573 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700574 public_submodules_->echo_control_mobile->Initialize(
575 proc_split_sample_rate_hz(), num_reverse_channels(),
576 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700577
578 public_submodules_->gain_control->Initialize(num_proc_channels(),
579 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700580 if (constants_.use_experimental_agc) {
581 if (!private_submodules_->agc_manager.get()) {
582 private_submodules_->agc_manager.reset(new AgcManagerDirect(
583 public_submodules_->gain_control.get(),
584 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800585 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700586 }
587 private_submodules_->agc_manager->Initialize();
588 private_submodules_->agc_manager->SetCaptureMuted(
589 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700590 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700591 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200592 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000593 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700594#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700595 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700596#endif
peah8271d042016-11-22 07:24:52 -0800597 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700598 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
599 proc_sample_rate_hz());
600 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
601 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700602 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200603 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700604 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200605 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100606 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800607
aleloi868f32f2017-05-23 07:20:05 -0700608 if (aec_dump_) {
609 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
610 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000611 return kNoError;
612}
613
Michael Graczyk86c6d332015-07-23 11:41:39 -0700614int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200615 UpdateActiveSubmoduleStates();
616
Michael Graczyk86c6d332015-07-23 11:41:39 -0700617 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700618 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
619 return kBadSampleRateError;
620 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000621 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700622
Peter Kasting69558702016-01-12 16:26:35 -0800623 const size_t num_in_channels = config.input_stream().num_channels();
624 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700625
626 // Need at least one input channel.
627 // Need either one output channel or as many outputs as there are inputs.
628 if (num_in_channels == 0 ||
629 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700630 return kBadNumberChannelsError;
631 }
632
aluebsb2328d12016-01-11 20:32:29 -0800633 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800634 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700635 return kBadNumberChannelsError;
636 }
637
peahdf3efa82015-11-28 12:35:15 -0800638 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000639
peahde65ddc2016-09-16 15:02:15 -0700640 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700641 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700642 formats_.api_format.output_stream().sample_rate_hz()),
643 submodule_states_.CaptureMultiBandSubModulesActive() ||
644 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000645
peahde65ddc2016-09-16 15:02:15 -0700646 capture_nonlocked_.capture_processing_format =
647 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700648
peah2ce640f2017-04-07 03:57:48 -0700649 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200650 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700651 render_processing_rate = FindNativeProcessRateToUse(
652 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
653 formats_.api_format.reverse_output_stream().sample_rate_hz()),
654 submodule_states_.CaptureMultiBandSubModulesActive() ||
655 submodule_states_.RenderMultiBandSubModulesActive());
656 } else {
657 render_processing_rate = capture_processing_rate;
658 }
659
aluebseb3603b2016-04-20 15:27:58 -0700660 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
661 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700662 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200663 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700664 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
665 ? kSampleRate32kHz
666 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700667 }
peah2ce640f2017-04-07 03:57:48 -0700668
peahde65ddc2016-09-16 15:02:15 -0700669 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700670 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700671 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
672 kSampleRate8kHz) {
673 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000674 } else {
peahde65ddc2016-09-16 15:02:15 -0700675 render_processing_rate =
676 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000677 }
678
peahde65ddc2016-09-16 15:02:15 -0700679 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000680 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700681 if (submodule_states_.RenderMultiBandSubModulesActive()) {
682 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
683 } else {
684 formats_.render_processing_format = StreamConfig(
685 formats_.api_format.reverse_input_stream().sample_rate_hz(),
686 formats_.api_format.reverse_input_stream().num_channels());
687 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000688
peahde65ddc2016-09-16 15:02:15 -0700689 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
690 kSampleRate32kHz ||
691 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
692 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800693 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000694 } else {
peahdf3efa82015-11-28 12:35:15 -0800695 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700696 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000697 }
698
699 return InitializeLocked();
700}
701
peah88ac8532016-09-12 16:47:25 -0700702void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700703 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700704
peah88ac8532016-09-12 16:47:25 -0700705 // Run in a single-threaded manner when applying the settings.
706 rtc::CritScope cs_render(&crit_render_);
707 rtc::CritScope cs_capture(&crit_capture_);
708
peah8271d042016-11-22 07:24:52 -0800709 InitializeLowCutFilter();
710
Mirko Bonadei675513b2017-11-09 11:09:25 +0100711 RTC_LOG(LS_INFO) << "Highpass filter activated: "
712 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800713
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100714 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700715 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100716 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
717 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100718 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100719 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700720 config_.gain_controller2 = AudioProcessing::Config::GainController2();
721 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200722 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200723 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200724 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100725 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
726 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200727 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
728 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700729}
730
731void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800732 // Run in a single-threaded manner when setting the extra options.
733 rtc::CritScope cs_render(&crit_render_);
734 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000735
peahb624d8c2016-03-05 03:01:14 -0800736 public_submodules_->echo_cancellation->SetExtraOptions(config);
737
peahdf3efa82015-11-28 12:35:15 -0800738 if (capture_.transient_suppressor_enabled !=
739 config.Get<ExperimentalNs>().enabled) {
740 capture_.transient_suppressor_enabled =
741 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000742 InitializeTransient();
743 }
aluebs2a346882016-01-11 18:04:30 -0800744
peah1bcfce52016-08-26 07:16:04 -0700745#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700746 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700747 config.Get<Intelligibility>().enabled) {
748 capture_nonlocked_.intelligibility_enabled =
749 config.Get<Intelligibility>().enabled;
750 InitializeIntelligibility();
751 }
peah1bcfce52016-08-26 07:16:04 -0700752#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700753
aluebs2a346882016-01-11 18:04:30 -0800754#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800755 if (capture_nonlocked_.beamformer_enabled !=
756 config.Get<Beamforming>().enabled) {
757 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800758 if (config.Get<Beamforming>().array_geometry.size() > 1) {
759 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
760 }
761 capture_.target_direction = config.Get<Beamforming>().target_direction;
762 InitializeBeamformer();
763 }
764#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000765}
766
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000767int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800768 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700769 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000770}
771
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000772int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800773 // Used as callback from submodules, hence locking is not allowed.
774 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000775}
776
Peter Kasting69558702016-01-12 16:26:35 -0800777size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800778 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700779 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000780}
781
Peter Kasting69558702016-01-12 16:26:35 -0800782size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800783 // Used as callback from submodules, hence locking is not allowed.
784 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000785}
786
Peter Kasting69558702016-01-12 16:26:35 -0800787size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800788 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700789 return (capture_nonlocked_.beamformer_enabled ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200790 capture_nonlocked_.echo_controller_enabled)
peahedddac52017-05-16 01:08:58 -0700791 ? 1
792 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800793}
794
Peter Kasting69558702016-01-12 16:26:35 -0800795size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800796 // Used as callback from submodules, hence locking is not allowed.
797 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000798}
799
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000800void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800801 rtc::CritScope cs(&crit_capture_);
802 capture_.output_will_be_muted = muted;
803 if (private_submodules_->agc_manager.get()) {
804 private_submodules_->agc_manager->SetCaptureMuted(
805 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000806 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000807}
808
Alessio Bazzicac054e782018-04-16 12:10:09 +0200809void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
810 RTC_DCHECK(setting.type() != RuntimeSetting::Type::kNotSpecified);
811 runtime_settings_enqueuer_.Enqueue(setting);
812}
813
814AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
815 SwapQueue<RuntimeSetting>* runtime_settings)
816 : runtime_settings_(runtime_settings) {
817 RTC_DCHECK(runtime_settings_);
818}
819
820AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
821 default;
822
823void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
824 RuntimeSetting setting) {
825 size_t remaining_attempts = 10;
826 while (!runtime_settings_->Insert(&setting) && remaining_attempts-- > 0) {
827 RuntimeSetting setting_to_discard;
828 if (runtime_settings_->Remove(&setting_to_discard))
829 RTC_LOG(LS_ERROR)
830 << "The runtime settings queue is full. Oldest setting discarded.";
831 }
832 if (remaining_attempts == 0)
833 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
834}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000835
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000836int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700837 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000838 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000839 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000840 int output_sample_rate_hz,
841 ChannelLayout output_layout,
842 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800843 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800844 StreamConfig input_stream;
845 StreamConfig output_stream;
846 {
847 // Access the formats_.api_format.input_stream beneath the capture lock.
848 // The lock must be released as it is later required in the call
849 // to ProcessStream(,,,);
850 rtc::CritScope cs(&crit_capture_);
851 input_stream = formats_.api_format.input_stream();
852 output_stream = formats_.api_format.output_stream();
853 }
854
Michael Graczyk86c6d332015-07-23 11:41:39 -0700855 input_stream.set_sample_rate_hz(input_sample_rate_hz);
856 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
857 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700858 output_stream.set_sample_rate_hz(output_sample_rate_hz);
859 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
860 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
861
862 if (samples_per_channel != input_stream.num_frames()) {
863 return kBadDataLengthError;
864 }
865 return ProcessStream(src, input_stream, output_stream, dest);
866}
867
868int AudioProcessingImpl::ProcessStream(const float* const* src,
869 const StreamConfig& input_config,
870 const StreamConfig& output_config,
871 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800872 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800873 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700874 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800875 {
876 // Acquire the capture lock in order to safely call the function
877 // that retrieves the render side data. This function accesses apm
878 // getters that need the capture lock held when being called.
879 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700880 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800881
882 if (!src || !dest) {
883 return kNullPointerError;
884 }
885
886 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700887 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000888 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000889
Michael Graczyk86c6d332015-07-23 11:41:39 -0700890 processing_config.input_stream() = input_config;
891 processing_config.output_stream() = output_config;
892
peahdf3efa82015-11-28 12:35:15 -0800893 {
894 // Do conditional reinitialization.
895 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700896 RETURN_ON_ERR(
897 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800898 }
899 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700900 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
901 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000902
aleloi868f32f2017-05-23 07:20:05 -0700903 if (aec_dump_) {
904 RecordUnprocessedCaptureStream(src);
905 }
906
peahdf3efa82015-11-28 12:35:15 -0800907 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700908 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800909 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000910
aleloi868f32f2017-05-23 07:20:05 -0700911 if (aec_dump_) {
912 RecordProcessedCaptureStream(dest);
913 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000914 return kNoError;
915}
916
Alessio Bazzicac054e782018-04-16 12:10:09 +0200917void AudioProcessingImpl::HandleRuntimeSettings() {
918 RuntimeSetting setting;
919 while (runtime_settings_->Remove(&setting)) {
920 RTC_DCHECK(setting.type() != RuntimeSetting::Type::kNotSpecified);
921 switch (setting.type()) {
922 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200923 if (config_.pre_amplifier.enabled) {
924 float value;
925 setting.GetFloat(&value);
926 private_submodules_->pre_amplifier->SetGainFactor(value);
927 }
928 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200929 break;
930 default:
931 RTC_NOTREACHED();
932 break;
933 }
934 }
935}
936
peah9e6a2902017-05-15 07:19:21 -0700937void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700938 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
939 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700940 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700941
kwibergaf476c72016-11-28 15:21:39 -0800942 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700943
944 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700945 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700946 // The data queue is full and needs to be emptied.
947 EmptyQueuedRenderAudio();
948
949 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700950 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700951 RTC_DCHECK(result);
952 }
953
954 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
955 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700956 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700957
958 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700959 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700960 // The data queue is full and needs to be emptied.
961 EmptyQueuedRenderAudio();
962
963 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700964 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700965 RTC_DCHECK(result);
966 }
peah701d6282016-10-25 05:42:20 -0700967
968 if (!constants_.use_experimental_agc) {
969 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
970 // Insert the samples into the queue.
971 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
972 // The data queue is full and needs to be emptied.
973 EmptyQueuedRenderAudio();
974
975 // Retry the insert (should always work).
976 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
977 RTC_DCHECK(result);
978 }
979 }
peah9e6a2902017-05-15 07:19:21 -0700980}
ivoc9f4a4a02016-10-28 05:39:16 -0700981
peah9e6a2902017-05-15 07:19:21 -0700982void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700983 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
984
985 // Insert the samples into the queue.
986 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
987 // The data queue is full and needs to be emptied.
988 EmptyQueuedRenderAudio();
989
990 // Retry the insert (should always work).
991 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
992 RTC_DCHECK(result);
993 }
peah764e3642016-10-22 05:04:30 -0700994}
995
996void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700997 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700998 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700999 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -07001000 EchoCancellationImpl::NumCancellersRequired(
1001 num_output_channels(), num_reverse_channels()));
1002
peah701d6282016-10-25 05:42:20 -07001003 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001004 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001005 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001006 EchoControlMobileImpl::NumCancellersRequired(
1007 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001008
peah701d6282016-10-25 05:42:20 -07001009 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001010 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001011
ivoc9f4a4a02016-10-28 05:39:16 -07001012 const size_t new_red_render_queue_element_max_size =
1013 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1014
peaha0624602016-10-25 04:45:24 -07001015 // Reallocate the queues if the queue item sizes are too small to fit the
1016 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001017 if (aec_render_queue_element_max_size_ <
1018 new_aec_render_queue_element_max_size) {
1019 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001020
peaha0624602016-10-25 04:45:24 -07001021 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001022 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001023
peah701d6282016-10-25 05:42:20 -07001024 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001025 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1026 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001027 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001028 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001029
peah701d6282016-10-25 05:42:20 -07001030 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1031 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001032 } else {
peah701d6282016-10-25 05:42:20 -07001033 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001034 }
1035
peah701d6282016-10-25 05:42:20 -07001036 if (aecm_render_queue_element_max_size_ <
1037 new_aecm_render_queue_element_max_size) {
1038 aecm_render_queue_element_max_size_ =
1039 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001040
1041 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001042 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001043
peah701d6282016-10-25 05:42:20 -07001044 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001045 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1046 kMaxNumFramesToBuffer, template_queue_element,
1047 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001048 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001049
peah701d6282016-10-25 05:42:20 -07001050 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1051 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001052 } else {
peah701d6282016-10-25 05:42:20 -07001053 aecm_render_signal_queue_->Clear();
1054 }
1055
1056 if (agc_render_queue_element_max_size_ <
1057 new_agc_render_queue_element_max_size) {
1058 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1059
1060 std::vector<int16_t> template_queue_element(
1061 agc_render_queue_element_max_size_);
1062
1063 agc_render_signal_queue_.reset(
1064 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1065 kMaxNumFramesToBuffer, template_queue_element,
1066 RenderQueueItemVerifier<int16_t>(
1067 agc_render_queue_element_max_size_)));
1068
1069 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1070 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1071 } else {
1072 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001073 }
ivoc9f4a4a02016-10-28 05:39:16 -07001074
1075 if (red_render_queue_element_max_size_ <
1076 new_red_render_queue_element_max_size) {
1077 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1078
1079 std::vector<float> template_queue_element(
1080 red_render_queue_element_max_size_);
1081
1082 red_render_signal_queue_.reset(
1083 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1084 kMaxNumFramesToBuffer, template_queue_element,
1085 RenderQueueItemVerifier<float>(
1086 red_render_queue_element_max_size_)));
1087
1088 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1089 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1090 } else {
1091 red_render_signal_queue_->Clear();
1092 }
peah764e3642016-10-22 05:04:30 -07001093}
1094
1095void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1096 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001097 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001098 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001099 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001100 }
1101
peah701d6282016-10-25 05:42:20 -07001102 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001103 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001104 aecm_capture_queue_buffer_);
1105 }
1106
1107 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1108 public_submodules_->gain_control->ProcessRenderAudio(
1109 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001110 }
ivoc9f4a4a02016-10-28 05:39:16 -07001111
1112 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001113 RTC_DCHECK(private_submodules_->echo_detector);
1114 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001115 red_capture_queue_buffer_);
1116 }
peah764e3642016-10-22 05:04:30 -07001117}
1118
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001119int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001120 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001121 {
1122 // Acquire the capture lock in order to safely call the function
1123 // that retrieves the render side data. This function accesses apm
1124 // getters that need the capture lock held when being called.
1125 // The lock needs to be released as
1126 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1127 // as well.
1128 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001129 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001130 }
peahfa6228e2015-11-16 16:27:42 -08001131
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001132 if (!frame) {
1133 return kNullPointerError;
1134 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001135 // Must be a native rate.
1136 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1137 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001138 frame->sample_rate_hz_ != kSampleRate32kHz &&
1139 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001140 return kBadSampleRateError;
1141 }
peah192164e2015-11-17 02:16:45 -08001142
peahdf3efa82015-11-28 12:35:15 -08001143 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001144 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001145 {
1146 // Aquire lock for the access of api_format.
1147 // The lock is released immediately due to the conditional
1148 // reinitialization.
1149 rtc::CritScope cs_capture(&crit_capture_);
1150 // TODO(ajm): The input and output rates and channels are currently
1151 // constrained to be identical in the int16 interface.
1152 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001153
1154 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001155 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001156 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1157 processing_config.input_stream().set_num_channels(frame->num_channels_);
1158 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1159 processing_config.output_stream().set_num_channels(frame->num_channels_);
1160
peahdf3efa82015-11-28 12:35:15 -08001161 {
1162 // Do conditional reinitialization.
1163 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001164 RETURN_ON_ERR(
1165 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001166 }
1167 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001168 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001169 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001170 return kBadDataLengthError;
1171 }
1172
aleloi868f32f2017-05-23 07:20:05 -07001173 if (aec_dump_) {
1174 RecordUnprocessedCaptureStream(*frame);
1175 }
1176
peahdf3efa82015-11-28 12:35:15 -08001177 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001178 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001179 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001180 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1181 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001182
aleloi868f32f2017-05-23 07:20:05 -07001183 if (aec_dump_) {
1184 RecordProcessedCaptureStream(*frame);
1185 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001186
1187 return kNoError;
1188}
1189
peahde65ddc2016-09-16 15:02:15 -07001190int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001191 HandleRuntimeSettings();
1192
peahb58a1582016-03-15 09:34:24 -07001193 // Ensure that not both the AEC and AECM are active at the same time.
1194 // TODO(peah): Simplify once the public API Enable functions for these
1195 // are moved to APM.
1196 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1197 public_submodules_->echo_control_mobile->is_enabled()));
1198
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001199 MaybeUpdateHistograms();
1200
peahde65ddc2016-09-16 15:02:15 -07001201 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001202
Alex Loikob5c9a792018-04-16 16:31:22 +02001203 if (private_submodules_->pre_amplifier) {
1204 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1205 capture_buffer->channels_f(), capture_buffer->num_channels(),
1206 capture_buffer->num_frames()));
1207 }
1208
peah1b08dc32016-12-20 13:45:58 -08001209 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001210 capture_buffer->channels_const()[0],
1211 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001212 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1213 if (log_rms) {
1214 capture_rms_interval_counter_ = 0;
1215 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001216 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1217 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1218 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1219 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001220 }
1221
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001222 if (private_submodules_->echo_controller) {
Per Åhgren9aed31c2017-06-29 20:23:27 +02001223 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1224 // issues have been addressed.
1225 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001226 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001227 }
1228
peahbe615622016-02-13 16:40:47 -08001229 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001230 public_submodules_->gain_control->is_enabled()) {
1231 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001232 capture_buffer->channels()[0], capture_buffer->num_channels(),
1233 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001234 }
1235
peah2ace3f92016-09-10 04:42:27 -07001236 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1237 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001238 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1239 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001240 }
1241
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001242 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001243 // Force down-mixing of the number of channels after the detection of
1244 // capture signal saturation.
1245 // TODO(peah): Look into ensuring that this kind of tampering with the
1246 // AudioBuffer functionality should not be needed.
1247 capture_buffer->set_num_channels(1);
1248 }
1249
aluebsb2328d12016-01-11 20:32:29 -08001250 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001251 private_submodules_->beamformer->AnalyzeChunk(
1252 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001253 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001254 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001255 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001256
peahe0eae3c2016-12-14 01:16:23 -08001257 // TODO(peah): Move the AEC3 low-cut filter to this place.
1258 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001259 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001260 private_submodules_->low_cut_filter->Process(capture_buffer);
1261 }
peahde65ddc2016-09-16 15:02:15 -07001262 RETURN_ON_ERR(
1263 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1264 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001265
1266 // Ensure that the stream delay was set before the call to the
1267 // AEC ProcessCaptureAudio function.
1268 if (public_submodules_->echo_cancellation->is_enabled() &&
1269 !was_stream_delay_set()) {
1270 return AudioProcessing::kStreamParameterNotSetError;
1271 }
1272
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001273 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001274 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1275
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001276 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001277 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001278 } else {
1279 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1280 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001281 }
1282
peahdf3efa82015-11-28 12:35:15 -08001283 if (public_submodules_->echo_control_mobile->is_enabled() &&
1284 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001285 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001286 }
peahde65ddc2016-09-16 15:02:15 -07001287 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001288#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001289 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001290 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001291 const int gain_db =
1292 public_submodules_->gain_control->is_enabled()
1293 ? public_submodules_->gain_control->compression_gain_db()
1294 : 0;
1295 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001296 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001297 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001298 }
peah1bcfce52016-08-26 07:16:04 -07001299#endif
peah253534d2016-03-15 04:32:28 -07001300
1301 // Ensure that the stream delay was set before the call to the
1302 // AECM ProcessCaptureAudio function.
1303 if (public_submodules_->echo_control_mobile->is_enabled() &&
1304 !was_stream_delay_set()) {
1305 return AudioProcessing::kStreamParameterNotSetError;
1306 }
1307
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001308 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001309 public_submodules_->echo_cancellation->is_enabled())) {
1310 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1311 capture_buffer, stream_delay_ms()));
1312 }
ivoc9f4a4a02016-10-28 05:39:16 -07001313
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001314 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001315 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001316 }
1317
peahde65ddc2016-09-16 15:02:15 -07001318 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001319
peahbe615622016-02-13 16:40:47 -08001320 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001321 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001322 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001323 private_submodules_->beamformer->is_target_present())) {
1324 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001325 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1326 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001327 }
peahb8fbb542016-03-15 02:28:08 -07001328 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001329 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001330
peah2ace3f92016-09-10 04:42:27 -07001331 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1332 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001333 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1334 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001335 }
1336
peah9e6a2902017-05-15 07:19:21 -07001337 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001338 RTC_DCHECK(private_submodules_->echo_detector);
1339 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001340 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1341 capture_buffer->num_frames()));
1342 }
1343
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001344 // TODO(aluebs): Investigate if the transient suppression placement should be
1345 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001346 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001347 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001348 private_submodules_->agc_manager.get()
1349 ? private_submodules_->agc_manager->voice_probability()
1350 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001351
peahdf3efa82015-11-28 12:35:15 -08001352 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001353 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1354 capture_buffer->num_channels(),
1355 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1356 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1357 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001358 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001359 }
1360
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001361 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001362 private_submodules_->gain_controller2->Process(capture_buffer);
1363 }
1364
Sam Zackrisson0beac582017-09-25 12:04:02 +02001365 if (private_submodules_->capture_post_processor) {
1366 private_submodules_->capture_post_processor->Process(capture_buffer);
1367 }
1368
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001369 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001370 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001371
peah1b08dc32016-12-20 13:45:58 -08001372 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1373 capture_buffer->channels_const()[0],
1374 capture_nonlocked_.capture_processing_format.num_frames()));
1375 if (log_rms) {
1376 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1377 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1378 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1379 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1380 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1381 }
1382
peahdf3efa82015-11-28 12:35:15 -08001383 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001384 return kNoError;
1385}
1386
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001387int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001388 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001389 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001390 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001391 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001392 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001393 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001394 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001395 };
1396 if (samples_per_channel != reverse_config.num_frames()) {
1397 return kBadDataLengthError;
1398 }
peahdf3efa82015-11-28 12:35:15 -08001399 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001400}
1401
peahde65ddc2016-09-16 15:02:15 -07001402int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1403 const StreamConfig& input_config,
1404 const StreamConfig& output_config,
1405 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001406 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001407 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001408 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001409 if (submodule_states_.RenderMultiBandProcessingActive() ||
1410 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001411 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1412 dest);
peah2ace3f92016-09-10 04:42:27 -07001413 } else if (formats_.api_format.reverse_input_stream() !=
1414 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001415 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1416 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001417 } else {
peahde65ddc2016-09-16 15:02:15 -07001418 CopyAudioIfNeeded(src, input_config.num_frames(),
1419 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001420 }
1421
1422 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001423}
1424
peahdf3efa82015-11-28 12:35:15 -08001425int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001426 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001427 const StreamConfig& input_config,
1428 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001429 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001430 return kNullPointerError;
1431 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001432
peahde65ddc2016-09-16 15:02:15 -07001433 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001434 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001435 }
1436
peahdf3efa82015-11-28 12:35:15 -08001437 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001438 processing_config.reverse_input_stream() = input_config;
1439 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001440
peahdf3efa82015-11-28 12:35:15 -08001441 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001442 RTC_DCHECK_EQ(input_config.num_frames(),
1443 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001444
aleloi868f32f2017-05-23 07:20:05 -07001445 if (aec_dump_) {
1446 const size_t channel_size =
1447 formats_.api_format.reverse_input_stream().num_frames();
1448 const size_t num_channels =
1449 formats_.api_format.reverse_input_stream().num_channels();
1450 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001451 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001452 }
peahdf3efa82015-11-28 12:35:15 -08001453 render_.render_audio->CopyFrom(src,
1454 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001455 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001456}
1457
1458int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001459 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001460 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001461 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001462 return kNullPointerError;
1463 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001464 // Must be a native rate.
1465 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1466 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001467 frame->sample_rate_hz_ != kSampleRate32kHz &&
1468 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001469 return kBadSampleRateError;
1470 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001471
Michael Graczyk86c6d332015-07-23 11:41:39 -07001472 if (frame->num_channels_ <= 0) {
1473 return kBadNumberChannelsError;
1474 }
1475
peahdf3efa82015-11-28 12:35:15 -08001476 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001477 processing_config.reverse_input_stream().set_sample_rate_hz(
1478 frame->sample_rate_hz_);
1479 processing_config.reverse_input_stream().set_num_channels(
1480 frame->num_channels_);
1481 processing_config.reverse_output_stream().set_sample_rate_hz(
1482 frame->sample_rate_hz_);
1483 processing_config.reverse_output_stream().set_num_channels(
1484 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001485
peahdf3efa82015-11-28 12:35:15 -08001486 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001487 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001488 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001489 return kBadDataLengthError;
1490 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001491
aleloi868f32f2017-05-23 07:20:05 -07001492 if (aec_dump_) {
1493 aec_dump_->WriteRenderStreamMessage(*frame);
1494 }
1495
peahdf3efa82015-11-28 12:35:15 -08001496 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001497 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001498 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001499 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1500 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001501 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001502}
niklase@google.com470e71d2011-07-07 08:21:25 +00001503
peahde65ddc2016-09-16 15:02:15 -07001504int AudioProcessingImpl::ProcessRenderStreamLocked() {
1505 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001506
1507 QueueNonbandedRenderAudio(render_buffer);
1508
Alex Loiko5825aa62017-12-18 16:02:40 +01001509 if (private_submodules_->render_pre_processor) {
1510 private_submodules_->render_pre_processor->Process(render_buffer);
1511 }
1512
peah2ace3f92016-09-10 04:42:27 -07001513 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001514 SampleRateSupportsMultiBand(
1515 formats_.render_processing_format.sample_rate_hz())) {
1516 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001517 }
1518
peah1bcfce52016-08-26 07:16:04 -07001519#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001520 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001521 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001522 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001523 }
peah1bcfce52016-08-26 07:16:04 -07001524#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001525
peahce4d9152017-05-19 01:28:05 -07001526 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1527 QueueBandedRenderAudio(render_buffer);
1528 }
1529
peahe0eae3c2016-12-14 01:16:23 -08001530 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001531 if (private_submodules_->echo_controller) {
1532 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001533 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001534
peah2ace3f92016-09-10 04:42:27 -07001535 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001536 SampleRateSupportsMultiBand(
1537 formats_.render_processing_format.sample_rate_hz())) {
1538 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001539 }
1540
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001541 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001542}
1543
1544int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001545 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001546 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001547 capture_.was_stream_delay_set = true;
1548 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001549
niklase@google.com470e71d2011-07-07 08:21:25 +00001550 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001551 delay = 0;
1552 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001553 }
1554
1555 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1556 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001557 delay = 500;
1558 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001559 }
1560
peahdf3efa82015-11-28 12:35:15 -08001561 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001562 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001563}
1564
1565int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001566 // Used as callback from submodules, hence locking is not allowed.
1567 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001568}
1569
1570bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001571 // Used as callback from submodules, hence locking is not allowed.
1572 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001573}
1574
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001575void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001576 rtc::CritScope cs(&crit_capture_);
1577 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001578}
1579
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001580void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001581 rtc::CritScope cs(&crit_capture_);
1582 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001583}
1584
1585int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001586 rtc::CritScope cs(&crit_capture_);
1587 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001588}
1589
aleloi868f32f2017-05-23 07:20:05 -07001590void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1591 RTC_DCHECK(aec_dump);
1592 rtc::CritScope cs_render(&crit_render_);
1593 rtc::CritScope cs_capture(&crit_capture_);
1594
1595 // The previously attached AecDump will be destroyed with the
1596 // 'aec_dump' parameter, which is after locks are released.
1597 aec_dump_.swap(aec_dump);
1598 WriteAecDumpConfigMessage(true);
1599 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1600}
1601
1602void AudioProcessingImpl::DetachAecDump() {
1603 // The d-tor of a task-queue based AecDump blocks until all pending
1604 // tasks are done. This construction avoids blocking while holding
1605 // the render and capture locks.
1606 std::unique_ptr<AecDump> aec_dump = nullptr;
1607 {
1608 rtc::CritScope cs_render(&crit_render_);
1609 rtc::CritScope cs_capture(&crit_capture_);
1610 aec_dump = std::move(aec_dump_);
1611 }
1612}
1613
Sam Zackrisson4d364492018-03-02 16:03:21 +01001614void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1615 std::unique_ptr<AudioGenerator> audio_generator) {
1616 // TODO(bugs.webrtc.org/8882) Stub.
1617 // Reset internal audio generator with audio_generator.
1618}
1619
1620void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1621 // TODO(bugs.webrtc.org/8882) Stub.
1622 // Delete audio generator, if one is attached.
1623}
1624
ivoc4e477a12017-01-15 08:29:46 -08001625AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1626 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1627 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1628 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1629 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1630}
1631
1632AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1633 const AudioProcessingStatistics& other) = default;
1634
1635AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1636 default;
1637
ivoc3e9a5372016-10-28 07:55:33 -07001638// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1639AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1640 const {
1641 return AudioProcessingStatistics();
1642}
1643
Ivo Creusenae026092017-11-20 13:07:16 +01001644// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001645AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001646 bool has_remote_tracks) const {
1647 return AudioProcessingStats();
1648}
1649
ivoc3e9a5372016-10-28 07:55:33 -07001650AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1651 const {
1652 AudioProcessingStatistics stats;
1653 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001654 if (private_submodules_->echo_controller) {
1655 rtc::CritScope cs_capture(&crit_capture_);
1656 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1657 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1658 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1659 // Instant value will also be used for min, max and average.
1660 stats.echo_return_loss.Set(erl, erl, erl, erl);
1661 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1662 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1663 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001664 stats.a_nlp.Set(metrics.a_nlp);
1665 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1666 stats.echo_return_loss.Set(metrics.echo_return_loss);
1667 stats.echo_return_loss_enhancement.Set(
1668 metrics.echo_return_loss_enhancement);
1669 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1670 }
ivoc9c192b22017-03-16 04:22:14 -07001671 {
1672 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001673 RTC_DCHECK(private_submodules_->echo_detector);
1674 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1675 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001676 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001677 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001678 }
ivoc3e9a5372016-10-28 07:55:33 -07001679 public_submodules_->echo_cancellation->GetDelayMetrics(
1680 &stats.delay_median, &stats.delay_standard_deviation,
1681 &stats.fraction_poor_delays);
1682 return stats;
1683}
1684
Ivo Creusen56d46092017-11-24 17:29:59 +01001685AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001686 bool has_remote_tracks) const {
1687 AudioProcessingStats stats;
1688 if (has_remote_tracks) {
1689 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001690 if (private_submodules_->echo_controller) {
1691 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001692 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1693 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001694 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001695 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001696 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001697 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1698 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001699 if (metrics.divergent_filter_fraction != -1.0f) {
1700 stats.divergent_filter_fraction =
1701 rtc::Optional<double>(metrics.divergent_filter_fraction);
1702 }
1703 if (metrics.echo_return_loss.instant != -100) {
1704 stats.echo_return_loss =
1705 rtc::Optional<double>(metrics.echo_return_loss.instant);
1706 }
1707 if (metrics.echo_return_loss_enhancement.instant != -100) {
1708 stats.echo_return_loss_enhancement =
1709 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1710 }
1711 }
1712 if (config_.residual_echo_detector.enabled) {
1713 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001714 RTC_DCHECK(private_submodules_->echo_detector);
1715 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1716 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001717 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001718 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001719 }
1720 int delay_median, delay_std;
1721 float fraction_poor_delays;
1722 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1723 &delay_median, &delay_std, &fraction_poor_delays) ==
1724 Error::kNoError) {
1725 if (delay_median >= 0) {
1726 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1727 }
1728 if (delay_std >= 0) {
1729 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1730 }
1731 }
1732 }
1733 return stats;
1734}
1735
niklase@google.com470e71d2011-07-07 08:21:25 +00001736EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001737 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001738}
1739
1740EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001741 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
1744GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001745 if (constants_.use_experimental_agc) {
1746 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001747 }
peahbfa97112016-03-10 21:09:04 -08001748 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001749}
1750
1751HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001752 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001753}
1754
1755LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001756 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001757}
1758
1759NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001760 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001761}
1762
1763VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001764 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001765}
1766
peah8271d042016-11-22 07:24:52 -08001767void AudioProcessingImpl::MutateConfig(
1768 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1769 rtc::CritScope cs_render(&crit_render_);
1770 rtc::CritScope cs_capture(&crit_capture_);
1771 mutator(&config_);
1772 ApplyConfig(config_);
1773}
1774
1775AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1776 rtc::CritScope cs_render(&crit_render_);
1777 rtc::CritScope cs_capture(&crit_capture_);
1778 return config_;
1779}
1780
peah2ace3f92016-09-10 04:42:27 -07001781bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1782 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001783 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001784 public_submodules_->echo_cancellation->is_enabled(),
1785 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001786 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001787 public_submodules_->noise_suppression->is_enabled(),
1788 capture_nonlocked_.intelligibility_enabled,
1789 capture_nonlocked_.beamformer_enabled,
1790 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001791 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001792 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001793 public_submodules_->voice_detection->is_enabled(),
1794 public_submodules_->level_estimator->is_enabled(),
1795 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001796}
1797
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001798
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001799void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001800 if (capture_.transient_suppressor_enabled) {
1801 if (!public_submodules_->transient_suppressor.get()) {
1802 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001803 }
peahdf3efa82015-11-28 12:35:15 -08001804 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001805 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1806 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001807 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001808}
1809
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001810void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001811 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001812 if (!private_submodules_->beamformer) {
1813 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001814 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001815 }
peahdf3efa82015-11-28 12:35:15 -08001816 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1817 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001818 }
1819}
1820
ekmeyerson60d9b332015-08-14 10:35:55 -07001821void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001822#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001823 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001824 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001825 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001826 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001827 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001828 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001829 }
peah1bcfce52016-08-26 07:16:04 -07001830#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001831}
1832
peah8271d042016-11-22 07:24:52 -08001833void AudioProcessingImpl::InitializeLowCutFilter() {
1834 if (config_.high_pass_filter.enabled) {
1835 private_submodules_->low_cut_filter.reset(
1836 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1837 } else {
1838 private_submodules_->low_cut_filter.reset();
1839 }
1840}
alessiob3ec96df2017-05-22 06:57:06 -07001841
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001842void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001843 if (echo_control_factory_) {
1844 private_submodules_->echo_controller =
1845 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001846 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001847 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001848 }
1849}
peah8271d042016-11-22 07:24:52 -08001850
alessiob3ec96df2017-05-22 06:57:06 -07001851void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001852 if (config_.gain_controller2.enabled) {
1853 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001854 }
1855}
1856
Alex Loikob5c9a792018-04-16 16:31:22 +02001857void AudioProcessingImpl::InitializePreAmplifier() {
1858 if (config_.pre_amplifier.enabled) {
1859 private_submodules_->pre_amplifier.reset(
1860 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1861 } else {
1862 private_submodules_->pre_amplifier.reset();
1863 }
1864}
1865
ivoc9f4a4a02016-10-28 05:39:16 -07001866void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001867 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001868 private_submodules_->echo_detector->Initialize(
1869 proc_sample_rate_hz(), num_proc_channels(),
1870 formats_.render_processing_format.sample_rate_hz(),
1871 formats_.render_processing_format.num_channels());
ivoc9f4a4a02016-10-28 05:39:16 -07001872}
1873
Sam Zackrisson0beac582017-09-25 12:04:02 +02001874void AudioProcessingImpl::InitializePostProcessor() {
1875 if (private_submodules_->capture_post_processor) {
1876 private_submodules_->capture_post_processor->Initialize(
1877 proc_sample_rate_hz(), num_proc_channels());
1878 }
1879}
1880
Alex Loiko5825aa62017-12-18 16:02:40 +01001881void AudioProcessingImpl::InitializePreProcessor() {
1882 if (private_submodules_->render_pre_processor) {
1883 private_submodules_->render_pre_processor->Initialize(
1884 formats_.render_processing_format.sample_rate_hz(),
1885 formats_.render_processing_format.num_channels());
1886 }
1887}
1888
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001889void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001890 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001891
1892 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001893 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001894 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001895 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001896 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001897 capture_.stream_delay_jumps = 0;
1898 }
1899 if (capture_.aec_system_delay_jumps == -1 &&
1900 echo_cancellation()->stream_has_echo()) {
1901 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001902 }
1903
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001904 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001905 const int diff_stream_delay_ms =
1906 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1907 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1908 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001909 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1910 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001911 if (capture_.stream_delay_jumps == -1) {
1912 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001913 }
peahdf3efa82015-11-28 12:35:15 -08001914 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001915 }
peahdf3efa82015-11-28 12:35:15 -08001916 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001917
1918 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001919 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001920 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001921 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001922 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001923 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1924 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001925 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001926 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001927 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001928 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001929 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1930 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1931 100);
peahdf3efa82015-11-28 12:35:15 -08001932 if (capture_.aec_system_delay_jumps == -1) {
1933 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001934 }
peahdf3efa82015-11-28 12:35:15 -08001935 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001936 }
peahdf3efa82015-11-28 12:35:15 -08001937 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001938 }
1939}
1940
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001941void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001942 // Run in a single-threaded manner.
1943 rtc::CritScope cs_render(&crit_render_);
1944 rtc::CritScope cs_capture(&crit_capture_);
1945
1946 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001947 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001948 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001949 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001950 }
peahdf3efa82015-11-28 12:35:15 -08001951 capture_.stream_delay_jumps = -1;
1952 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001953
peahdf3efa82015-11-28 12:35:15 -08001954 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001955 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1956 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001957 }
peahdf3efa82015-11-28 12:35:15 -08001958 capture_.aec_system_delay_jumps = -1;
1959 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001960}
1961
aleloi868f32f2017-05-23 07:20:05 -07001962void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1963 if (!aec_dump_) {
1964 return;
1965 }
1966 std::string experiments_description =
1967 public_submodules_->echo_cancellation->GetExperimentsDescription();
1968 // TODO(peah): Add semicolon-separated concatenations of experiment
1969 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001970 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1971 experiments_description += "AgcClippingLevelExperiment;";
1972 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001973 if (capture_nonlocked_.echo_controller_enabled) {
1974 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001975 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001976 if (config_.gain_controller2.enabled) {
1977 experiments_description += "GainController2;";
1978 }
aleloi868f32f2017-05-23 07:20:05 -07001979
1980 InternalAPMConfig apm_config;
1981
1982 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1983 apm_config.aec_delay_agnostic_enabled =
1984 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1985 apm_config.aec_drift_compensation_enabled =
1986 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1987 apm_config.aec_extended_filter_enabled =
1988 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1989 apm_config.aec_suppression_level = static_cast<int>(
1990 public_submodules_->echo_cancellation->suppression_level());
1991
1992 apm_config.aecm_enabled =
1993 public_submodules_->echo_control_mobile->is_enabled();
1994 apm_config.aecm_comfort_noise_enabled =
1995 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1996 apm_config.aecm_routing_mode =
1997 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1998
1999 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2000 apm_config.agc_mode =
2001 static_cast<int>(public_submodules_->gain_control->mode());
2002 apm_config.agc_limiter_enabled =
2003 public_submodules_->gain_control->is_limiter_enabled();
2004 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2005
2006 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2007
2008 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2009 apm_config.ns_level =
2010 static_cast<int>(public_submodules_->noise_suppression->level());
2011
2012 apm_config.transient_suppression_enabled =
2013 capture_.transient_suppressor_enabled;
2014 apm_config.intelligibility_enhancer_enabled =
2015 capture_nonlocked_.intelligibility_enabled;
2016 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002017 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2018 apm_config.pre_amplifier_fixed_gain_factor =
2019 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002020
2021 if (!forced && apm_config == apm_config_for_aec_dump_) {
2022 return;
2023 }
2024 aec_dump_->WriteConfig(apm_config);
2025 apm_config_for_aec_dump_ = apm_config;
2026}
2027
2028void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2029 const float* const* src) {
2030 RTC_DCHECK(aec_dump_);
2031 WriteAecDumpConfigMessage(false);
2032
2033 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2034 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2035 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002036 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002037 RecordAudioProcessingState();
2038}
2039
2040void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2041 const AudioFrame& capture_frame) {
2042 RTC_DCHECK(aec_dump_);
2043 WriteAecDumpConfigMessage(false);
2044
2045 aec_dump_->AddCaptureStreamInput(capture_frame);
2046 RecordAudioProcessingState();
2047}
2048
2049void AudioProcessingImpl::RecordProcessedCaptureStream(
2050 const float* const* processed_capture_stream) {
2051 RTC_DCHECK(aec_dump_);
2052
2053 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2054 const size_t num_channels =
2055 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002056 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2057 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002058 aec_dump_->WriteCaptureStreamMessage();
2059}
2060
2061void AudioProcessingImpl::RecordProcessedCaptureStream(
2062 const AudioFrame& processed_capture_frame) {
2063 RTC_DCHECK(aec_dump_);
2064
2065 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2066 aec_dump_->WriteCaptureStreamMessage();
2067}
2068
2069void AudioProcessingImpl::RecordAudioProcessingState() {
2070 RTC_DCHECK(aec_dump_);
2071 AecDump::AudioProcessingState audio_proc_state;
2072 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2073 audio_proc_state.drift =
2074 public_submodules_->echo_cancellation->stream_drift_samples();
2075 audio_proc_state.level = gain_control()->stream_analog_level();
2076 audio_proc_state.keypress = capture_.key_pressed;
2077 aec_dump_->AddAudioProcessingState(audio_proc_state);
2078}
2079
kwiberg83ffe452016-08-29 14:46:07 -07002080AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2081 bool transient_suppressor_enabled,
2082 const std::vector<Point>& array_geometry,
2083 SphericalPointf target_direction)
2084 : aec_system_delay_jumps(-1),
2085 delay_offset_ms(0),
2086 was_stream_delay_set(false),
2087 last_stream_delay_ms(0),
2088 last_aec_system_delay_ms(0),
2089 stream_delay_jumps(-1),
2090 output_will_be_muted(false),
2091 key_pressed(false),
2092 transient_suppressor_enabled(transient_suppressor_enabled),
2093 array_geometry(array_geometry),
2094 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002095 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002096 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002097 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002098
2099AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2100
2101AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2102
2103AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2104
niklase@google.com470e71d2011-07-07 08:21:25 +00002105} // namespace webrtc