blob: 99163525ed4e08980254f4c795eb62b05b4e348e [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
Per Åhgrend0fa8202018-04-18 09:35:13 +02001276 if (was_stream_delay_set()) {
1277 private_submodules_->echo_controller->SetAudioBufferDelay(
1278 stream_delay_ms());
1279 }
1280
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001281 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001282 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001283 } else {
1284 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1285 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001286 }
1287
peahdf3efa82015-11-28 12:35:15 -08001288 if (public_submodules_->echo_control_mobile->is_enabled() &&
1289 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001290 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001291 }
peahde65ddc2016-09-16 15:02:15 -07001292 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001293#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001294 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001295 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001296 const int gain_db =
1297 public_submodules_->gain_control->is_enabled()
1298 ? public_submodules_->gain_control->compression_gain_db()
1299 : 0;
1300 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001301 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001302 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001303 }
peah1bcfce52016-08-26 07:16:04 -07001304#endif
peah253534d2016-03-15 04:32:28 -07001305
1306 // Ensure that the stream delay was set before the call to the
1307 // AECM ProcessCaptureAudio function.
1308 if (public_submodules_->echo_control_mobile->is_enabled() &&
1309 !was_stream_delay_set()) {
1310 return AudioProcessing::kStreamParameterNotSetError;
1311 }
1312
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001313 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001314 public_submodules_->echo_cancellation->is_enabled())) {
1315 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1316 capture_buffer, stream_delay_ms()));
1317 }
ivoc9f4a4a02016-10-28 05:39:16 -07001318
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001319 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001320 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001321 }
1322
peahde65ddc2016-09-16 15:02:15 -07001323 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001324
peahbe615622016-02-13 16:40:47 -08001325 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001326 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001327 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001328 private_submodules_->beamformer->is_target_present())) {
1329 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001330 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1331 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001332 }
peahb8fbb542016-03-15 02:28:08 -07001333 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001334 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001335
peah2ace3f92016-09-10 04:42:27 -07001336 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1337 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001338 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1339 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001340 }
1341
peah9e6a2902017-05-15 07:19:21 -07001342 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001343 RTC_DCHECK(private_submodules_->echo_detector);
1344 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001345 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1346 capture_buffer->num_frames()));
1347 }
1348
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001349 // TODO(aluebs): Investigate if the transient suppression placement should be
1350 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001351 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001352 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001353 private_submodules_->agc_manager.get()
1354 ? private_submodules_->agc_manager->voice_probability()
1355 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001356
peahdf3efa82015-11-28 12:35:15 -08001357 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001358 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1359 capture_buffer->num_channels(),
1360 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1361 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1362 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001363 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001364 }
1365
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001366 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001367 private_submodules_->gain_controller2->Process(capture_buffer);
1368 }
1369
Sam Zackrisson0beac582017-09-25 12:04:02 +02001370 if (private_submodules_->capture_post_processor) {
1371 private_submodules_->capture_post_processor->Process(capture_buffer);
1372 }
1373
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001374 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001375 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001376
peah1b08dc32016-12-20 13:45:58 -08001377 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1378 capture_buffer->channels_const()[0],
1379 capture_nonlocked_.capture_processing_format.num_frames()));
1380 if (log_rms) {
1381 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1382 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1383 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1384 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1385 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1386 }
1387
peahdf3efa82015-11-28 12:35:15 -08001388 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001389 return kNoError;
1390}
1391
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001392int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001393 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001394 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001395 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001396 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001397 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001398 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001399 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001400 };
1401 if (samples_per_channel != reverse_config.num_frames()) {
1402 return kBadDataLengthError;
1403 }
peahdf3efa82015-11-28 12:35:15 -08001404 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001405}
1406
peahde65ddc2016-09-16 15:02:15 -07001407int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1408 const StreamConfig& input_config,
1409 const StreamConfig& output_config,
1410 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001411 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001412 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001413 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001414 if (submodule_states_.RenderMultiBandProcessingActive() ||
1415 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001416 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1417 dest);
peah2ace3f92016-09-10 04:42:27 -07001418 } else if (formats_.api_format.reverse_input_stream() !=
1419 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001420 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1421 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001422 } else {
peahde65ddc2016-09-16 15:02:15 -07001423 CopyAudioIfNeeded(src, input_config.num_frames(),
1424 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001425 }
1426
1427 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001428}
1429
peahdf3efa82015-11-28 12:35:15 -08001430int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001431 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001432 const StreamConfig& input_config,
1433 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001434 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001435 return kNullPointerError;
1436 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001437
peahde65ddc2016-09-16 15:02:15 -07001438 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001439 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001440 }
1441
peahdf3efa82015-11-28 12:35:15 -08001442 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001443 processing_config.reverse_input_stream() = input_config;
1444 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001445
peahdf3efa82015-11-28 12:35:15 -08001446 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001447 RTC_DCHECK_EQ(input_config.num_frames(),
1448 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001449
aleloi868f32f2017-05-23 07:20:05 -07001450 if (aec_dump_) {
1451 const size_t channel_size =
1452 formats_.api_format.reverse_input_stream().num_frames();
1453 const size_t num_channels =
1454 formats_.api_format.reverse_input_stream().num_channels();
1455 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001456 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001457 }
peahdf3efa82015-11-28 12:35:15 -08001458 render_.render_audio->CopyFrom(src,
1459 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001460 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001461}
1462
1463int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001464 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001465 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001466 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001467 return kNullPointerError;
1468 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001469 // Must be a native rate.
1470 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1471 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001472 frame->sample_rate_hz_ != kSampleRate32kHz &&
1473 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001474 return kBadSampleRateError;
1475 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001476
Michael Graczyk86c6d332015-07-23 11:41:39 -07001477 if (frame->num_channels_ <= 0) {
1478 return kBadNumberChannelsError;
1479 }
1480
peahdf3efa82015-11-28 12:35:15 -08001481 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001482 processing_config.reverse_input_stream().set_sample_rate_hz(
1483 frame->sample_rate_hz_);
1484 processing_config.reverse_input_stream().set_num_channels(
1485 frame->num_channels_);
1486 processing_config.reverse_output_stream().set_sample_rate_hz(
1487 frame->sample_rate_hz_);
1488 processing_config.reverse_output_stream().set_num_channels(
1489 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001490
peahdf3efa82015-11-28 12:35:15 -08001491 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001492 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001493 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001494 return kBadDataLengthError;
1495 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001496
aleloi868f32f2017-05-23 07:20:05 -07001497 if (aec_dump_) {
1498 aec_dump_->WriteRenderStreamMessage(*frame);
1499 }
1500
peahdf3efa82015-11-28 12:35:15 -08001501 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001502 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001503 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001504 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1505 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001506 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001507}
niklase@google.com470e71d2011-07-07 08:21:25 +00001508
peahde65ddc2016-09-16 15:02:15 -07001509int AudioProcessingImpl::ProcessRenderStreamLocked() {
1510 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001511
1512 QueueNonbandedRenderAudio(render_buffer);
1513
Alex Loiko5825aa62017-12-18 16:02:40 +01001514 if (private_submodules_->render_pre_processor) {
1515 private_submodules_->render_pre_processor->Process(render_buffer);
1516 }
1517
peah2ace3f92016-09-10 04:42:27 -07001518 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001519 SampleRateSupportsMultiBand(
1520 formats_.render_processing_format.sample_rate_hz())) {
1521 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001522 }
1523
peah1bcfce52016-08-26 07:16:04 -07001524#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001525 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001526 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001527 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001528 }
peah1bcfce52016-08-26 07:16:04 -07001529#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001530
peahce4d9152017-05-19 01:28:05 -07001531 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1532 QueueBandedRenderAudio(render_buffer);
1533 }
1534
peahe0eae3c2016-12-14 01:16:23 -08001535 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001536 if (private_submodules_->echo_controller) {
1537 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001538 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001539
peah2ace3f92016-09-10 04:42:27 -07001540 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001541 SampleRateSupportsMultiBand(
1542 formats_.render_processing_format.sample_rate_hz())) {
1543 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001544 }
1545
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001546 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001547}
1548
1549int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001550 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001551 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001552 capture_.was_stream_delay_set = true;
1553 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001554
niklase@google.com470e71d2011-07-07 08:21:25 +00001555 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001556 delay = 0;
1557 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001558 }
1559
1560 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1561 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001562 delay = 500;
1563 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001564 }
1565
peahdf3efa82015-11-28 12:35:15 -08001566 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001567 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001568}
1569
1570int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001571 // Used as callback from submodules, hence locking is not allowed.
1572 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001573}
1574
1575bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001576 // Used as callback from submodules, hence locking is not allowed.
1577 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001578}
1579
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001580void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001581 rtc::CritScope cs(&crit_capture_);
1582 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001583}
1584
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001585void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001586 rtc::CritScope cs(&crit_capture_);
1587 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001588}
1589
1590int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001591 rtc::CritScope cs(&crit_capture_);
1592 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001593}
1594
aleloi868f32f2017-05-23 07:20:05 -07001595void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1596 RTC_DCHECK(aec_dump);
1597 rtc::CritScope cs_render(&crit_render_);
1598 rtc::CritScope cs_capture(&crit_capture_);
1599
1600 // The previously attached AecDump will be destroyed with the
1601 // 'aec_dump' parameter, which is after locks are released.
1602 aec_dump_.swap(aec_dump);
1603 WriteAecDumpConfigMessage(true);
1604 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1605}
1606
1607void AudioProcessingImpl::DetachAecDump() {
1608 // The d-tor of a task-queue based AecDump blocks until all pending
1609 // tasks are done. This construction avoids blocking while holding
1610 // the render and capture locks.
1611 std::unique_ptr<AecDump> aec_dump = nullptr;
1612 {
1613 rtc::CritScope cs_render(&crit_render_);
1614 rtc::CritScope cs_capture(&crit_capture_);
1615 aec_dump = std::move(aec_dump_);
1616 }
1617}
1618
Sam Zackrisson4d364492018-03-02 16:03:21 +01001619void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1620 std::unique_ptr<AudioGenerator> audio_generator) {
1621 // TODO(bugs.webrtc.org/8882) Stub.
1622 // Reset internal audio generator with audio_generator.
1623}
1624
1625void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1626 // TODO(bugs.webrtc.org/8882) Stub.
1627 // Delete audio generator, if one is attached.
1628}
1629
ivoc4e477a12017-01-15 08:29:46 -08001630AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1631 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1632 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1633 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1634 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1635}
1636
1637AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1638 const AudioProcessingStatistics& other) = default;
1639
1640AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1641 default;
1642
ivoc3e9a5372016-10-28 07:55:33 -07001643// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1644AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1645 const {
1646 return AudioProcessingStatistics();
1647}
1648
Ivo Creusenae026092017-11-20 13:07:16 +01001649// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001650AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001651 bool has_remote_tracks) const {
1652 return AudioProcessingStats();
1653}
1654
ivoc3e9a5372016-10-28 07:55:33 -07001655AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1656 const {
1657 AudioProcessingStatistics stats;
1658 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001659 if (private_submodules_->echo_controller) {
1660 rtc::CritScope cs_capture(&crit_capture_);
1661 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1662 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1663 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1664 // Instant value will also be used for min, max and average.
1665 stats.echo_return_loss.Set(erl, erl, erl, erl);
1666 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1667 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1668 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001669 stats.a_nlp.Set(metrics.a_nlp);
1670 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1671 stats.echo_return_loss.Set(metrics.echo_return_loss);
1672 stats.echo_return_loss_enhancement.Set(
1673 metrics.echo_return_loss_enhancement);
1674 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1675 }
ivoc9c192b22017-03-16 04:22:14 -07001676 {
1677 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001678 RTC_DCHECK(private_submodules_->echo_detector);
1679 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1680 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001681 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001682 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001683 }
ivoc3e9a5372016-10-28 07:55:33 -07001684 public_submodules_->echo_cancellation->GetDelayMetrics(
1685 &stats.delay_median, &stats.delay_standard_deviation,
1686 &stats.fraction_poor_delays);
1687 return stats;
1688}
1689
Ivo Creusen56d46092017-11-24 17:29:59 +01001690AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001691 bool has_remote_tracks) const {
1692 AudioProcessingStats stats;
1693 if (has_remote_tracks) {
1694 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001695 if (private_submodules_->echo_controller) {
1696 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001697 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1698 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001699 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001700 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001701 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001702 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1703 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001704 if (metrics.divergent_filter_fraction != -1.0f) {
1705 stats.divergent_filter_fraction =
1706 rtc::Optional<double>(metrics.divergent_filter_fraction);
1707 }
1708 if (metrics.echo_return_loss.instant != -100) {
1709 stats.echo_return_loss =
1710 rtc::Optional<double>(metrics.echo_return_loss.instant);
1711 }
1712 if (metrics.echo_return_loss_enhancement.instant != -100) {
1713 stats.echo_return_loss_enhancement =
1714 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1715 }
1716 }
1717 if (config_.residual_echo_detector.enabled) {
1718 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001719 RTC_DCHECK(private_submodules_->echo_detector);
1720 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1721 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001722 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001723 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001724 }
1725 int delay_median, delay_std;
1726 float fraction_poor_delays;
1727 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1728 &delay_median, &delay_std, &fraction_poor_delays) ==
1729 Error::kNoError) {
1730 if (delay_median >= 0) {
1731 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1732 }
1733 if (delay_std >= 0) {
1734 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1735 }
1736 }
1737 }
1738 return stats;
1739}
1740
niklase@google.com470e71d2011-07-07 08:21:25 +00001741EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001742 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001743}
1744
1745EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001746 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001747}
1748
1749GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001750 if (constants_.use_experimental_agc) {
1751 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001752 }
peahbfa97112016-03-10 21:09:04 -08001753 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001754}
1755
1756HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001757 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001758}
1759
1760LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001761 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001762}
1763
1764NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001765 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001766}
1767
1768VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001769 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001770}
1771
peah8271d042016-11-22 07:24:52 -08001772void AudioProcessingImpl::MutateConfig(
1773 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1774 rtc::CritScope cs_render(&crit_render_);
1775 rtc::CritScope cs_capture(&crit_capture_);
1776 mutator(&config_);
1777 ApplyConfig(config_);
1778}
1779
1780AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1781 rtc::CritScope cs_render(&crit_render_);
1782 rtc::CritScope cs_capture(&crit_capture_);
1783 return config_;
1784}
1785
peah2ace3f92016-09-10 04:42:27 -07001786bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1787 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001788 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001789 public_submodules_->echo_cancellation->is_enabled(),
1790 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001791 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001792 public_submodules_->noise_suppression->is_enabled(),
1793 capture_nonlocked_.intelligibility_enabled,
1794 capture_nonlocked_.beamformer_enabled,
1795 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001796 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001797 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001798 public_submodules_->voice_detection->is_enabled(),
1799 public_submodules_->level_estimator->is_enabled(),
1800 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001801}
1802
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001803
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001804void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001805 if (capture_.transient_suppressor_enabled) {
1806 if (!public_submodules_->transient_suppressor.get()) {
1807 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001808 }
peahdf3efa82015-11-28 12:35:15 -08001809 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001810 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1811 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001812 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001813}
1814
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001815void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001816 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001817 if (!private_submodules_->beamformer) {
1818 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001819 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001820 }
peahdf3efa82015-11-28 12:35:15 -08001821 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1822 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001823 }
1824}
1825
ekmeyerson60d9b332015-08-14 10:35:55 -07001826void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001827#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001828 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001829 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001830 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001831 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001832 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001833 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001834 }
peah1bcfce52016-08-26 07:16:04 -07001835#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001836}
1837
peah8271d042016-11-22 07:24:52 -08001838void AudioProcessingImpl::InitializeLowCutFilter() {
1839 if (config_.high_pass_filter.enabled) {
1840 private_submodules_->low_cut_filter.reset(
1841 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1842 } else {
1843 private_submodules_->low_cut_filter.reset();
1844 }
1845}
alessiob3ec96df2017-05-22 06:57:06 -07001846
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001847void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001848 if (echo_control_factory_) {
1849 private_submodules_->echo_controller =
1850 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001851 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001852 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001853 }
1854}
peah8271d042016-11-22 07:24:52 -08001855
alessiob3ec96df2017-05-22 06:57:06 -07001856void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001857 if (config_.gain_controller2.enabled) {
1858 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001859 }
1860}
1861
Alex Loikob5c9a792018-04-16 16:31:22 +02001862void AudioProcessingImpl::InitializePreAmplifier() {
1863 if (config_.pre_amplifier.enabled) {
1864 private_submodules_->pre_amplifier.reset(
1865 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1866 } else {
1867 private_submodules_->pre_amplifier.reset();
1868 }
1869}
1870
ivoc9f4a4a02016-10-28 05:39:16 -07001871void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001872 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001873 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001874 proc_sample_rate_hz(), 1,
1875 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001876}
1877
Sam Zackrisson0beac582017-09-25 12:04:02 +02001878void AudioProcessingImpl::InitializePostProcessor() {
1879 if (private_submodules_->capture_post_processor) {
1880 private_submodules_->capture_post_processor->Initialize(
1881 proc_sample_rate_hz(), num_proc_channels());
1882 }
1883}
1884
Alex Loiko5825aa62017-12-18 16:02:40 +01001885void AudioProcessingImpl::InitializePreProcessor() {
1886 if (private_submodules_->render_pre_processor) {
1887 private_submodules_->render_pre_processor->Initialize(
1888 formats_.render_processing_format.sample_rate_hz(),
1889 formats_.render_processing_format.num_channels());
1890 }
1891}
1892
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001893void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001894 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001895
1896 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001897 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001898 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001899 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001900 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001901 capture_.stream_delay_jumps = 0;
1902 }
1903 if (capture_.aec_system_delay_jumps == -1 &&
1904 echo_cancellation()->stream_has_echo()) {
1905 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001906 }
1907
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001908 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001909 const int diff_stream_delay_ms =
1910 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1911 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1912 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001913 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1914 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001915 if (capture_.stream_delay_jumps == -1) {
1916 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001917 }
peahdf3efa82015-11-28 12:35:15 -08001918 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001919 }
peahdf3efa82015-11-28 12:35:15 -08001920 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001921
1922 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001923 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001924 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001925 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001926 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001927 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1928 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001929 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001930 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001931 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001932 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001933 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1934 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1935 100);
peahdf3efa82015-11-28 12:35:15 -08001936 if (capture_.aec_system_delay_jumps == -1) {
1937 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001938 }
peahdf3efa82015-11-28 12:35:15 -08001939 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001940 }
peahdf3efa82015-11-28 12:35:15 -08001941 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001942 }
1943}
1944
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001945void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001946 // Run in a single-threaded manner.
1947 rtc::CritScope cs_render(&crit_render_);
1948 rtc::CritScope cs_capture(&crit_capture_);
1949
1950 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001951 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001952 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001953 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001954 }
peahdf3efa82015-11-28 12:35:15 -08001955 capture_.stream_delay_jumps = -1;
1956 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001957
peahdf3efa82015-11-28 12:35:15 -08001958 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001959 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1960 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001961 }
peahdf3efa82015-11-28 12:35:15 -08001962 capture_.aec_system_delay_jumps = -1;
1963 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001964}
1965
aleloi868f32f2017-05-23 07:20:05 -07001966void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1967 if (!aec_dump_) {
1968 return;
1969 }
1970 std::string experiments_description =
1971 public_submodules_->echo_cancellation->GetExperimentsDescription();
1972 // TODO(peah): Add semicolon-separated concatenations of experiment
1973 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001974 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1975 experiments_description += "AgcClippingLevelExperiment;";
1976 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001977 if (capture_nonlocked_.echo_controller_enabled) {
1978 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001979 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001980 if (config_.gain_controller2.enabled) {
1981 experiments_description += "GainController2;";
1982 }
aleloi868f32f2017-05-23 07:20:05 -07001983
1984 InternalAPMConfig apm_config;
1985
1986 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1987 apm_config.aec_delay_agnostic_enabled =
1988 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1989 apm_config.aec_drift_compensation_enabled =
1990 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1991 apm_config.aec_extended_filter_enabled =
1992 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1993 apm_config.aec_suppression_level = static_cast<int>(
1994 public_submodules_->echo_cancellation->suppression_level());
1995
1996 apm_config.aecm_enabled =
1997 public_submodules_->echo_control_mobile->is_enabled();
1998 apm_config.aecm_comfort_noise_enabled =
1999 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
2000 apm_config.aecm_routing_mode =
2001 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
2002
2003 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2004 apm_config.agc_mode =
2005 static_cast<int>(public_submodules_->gain_control->mode());
2006 apm_config.agc_limiter_enabled =
2007 public_submodules_->gain_control->is_limiter_enabled();
2008 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2009
2010 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2011
2012 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2013 apm_config.ns_level =
2014 static_cast<int>(public_submodules_->noise_suppression->level());
2015
2016 apm_config.transient_suppression_enabled =
2017 capture_.transient_suppressor_enabled;
2018 apm_config.intelligibility_enhancer_enabled =
2019 capture_nonlocked_.intelligibility_enabled;
2020 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002021 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2022 apm_config.pre_amplifier_fixed_gain_factor =
2023 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002024
2025 if (!forced && apm_config == apm_config_for_aec_dump_) {
2026 return;
2027 }
2028 aec_dump_->WriteConfig(apm_config);
2029 apm_config_for_aec_dump_ = apm_config;
2030}
2031
2032void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2033 const float* const* src) {
2034 RTC_DCHECK(aec_dump_);
2035 WriteAecDumpConfigMessage(false);
2036
2037 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2038 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2039 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002040 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002041 RecordAudioProcessingState();
2042}
2043
2044void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2045 const AudioFrame& capture_frame) {
2046 RTC_DCHECK(aec_dump_);
2047 WriteAecDumpConfigMessage(false);
2048
2049 aec_dump_->AddCaptureStreamInput(capture_frame);
2050 RecordAudioProcessingState();
2051}
2052
2053void AudioProcessingImpl::RecordProcessedCaptureStream(
2054 const float* const* processed_capture_stream) {
2055 RTC_DCHECK(aec_dump_);
2056
2057 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2058 const size_t num_channels =
2059 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002060 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2061 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002062 aec_dump_->WriteCaptureStreamMessage();
2063}
2064
2065void AudioProcessingImpl::RecordProcessedCaptureStream(
2066 const AudioFrame& processed_capture_frame) {
2067 RTC_DCHECK(aec_dump_);
2068
2069 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2070 aec_dump_->WriteCaptureStreamMessage();
2071}
2072
2073void AudioProcessingImpl::RecordAudioProcessingState() {
2074 RTC_DCHECK(aec_dump_);
2075 AecDump::AudioProcessingState audio_proc_state;
2076 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2077 audio_proc_state.drift =
2078 public_submodules_->echo_cancellation->stream_drift_samples();
2079 audio_proc_state.level = gain_control()->stream_analog_level();
2080 audio_proc_state.keypress = capture_.key_pressed;
2081 aec_dump_->AddAudioProcessingState(audio_proc_state);
2082}
2083
kwiberg83ffe452016-08-29 14:46:07 -07002084AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2085 bool transient_suppressor_enabled,
2086 const std::vector<Point>& array_geometry,
2087 SphericalPointf target_direction)
2088 : aec_system_delay_jumps(-1),
2089 delay_offset_ms(0),
2090 was_stream_delay_set(false),
2091 last_stream_delay_ms(0),
2092 last_aec_system_delay_ms(0),
2093 stream_delay_jumps(-1),
2094 output_will_be_muted(false),
2095 key_pressed(false),
2096 transient_suppressor_enabled(transient_suppressor_enabled),
2097 array_geometry(array_geometry),
2098 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002099 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002100 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002101 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002102
2103AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2104
2105AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2106
2107AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2108
niklase@google.com470e71d2011-07-07 08:21:25 +00002109} // namespace webrtc