blob: 2fbf369e5156a3cf541eeca7e625d4d453df1c54 [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"
22#include "modules/audio_processing/aec3/echo_canceller3.h"
23#include "modules/audio_processing/agc/agc_manager_direct.h"
24#include "modules/audio_processing/agc2/gain_controller2.h"
25#include "modules/audio_processing/audio_buffer.h"
26#include "modules/audio_processing/beamformer/nonlinear_beamformer.h"
27#include "modules/audio_processing/common.h"
28#include "modules/audio_processing/echo_cancellation_impl.h"
29#include "modules/audio_processing/echo_control_mobile_impl.h"
30#include "modules/audio_processing/gain_control_for_experimental_agc.h"
31#include "modules/audio_processing/gain_control_impl.h"
32#include "rtc_base/checks.h"
33#include "rtc_base/logging.h"
34#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020035#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070037#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070039#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "modules/audio_processing/level_controller/level_controller.h"
41#include "modules/audio_processing/level_estimator_impl.h"
42#include "modules/audio_processing/low_cut_filter.h"
43#include "modules/audio_processing/noise_suppression_impl.h"
44#include "modules/audio_processing/residual_echo_detector.h"
45#include "modules/audio_processing/transient/transient_suppressor.h"
46#include "modules/audio_processing/voice_detection_impl.h"
47#include "modules/include/module_common_types.h"
48#include "system_wrappers/include/file_wrapper.h"
49#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,
peah2ace3f92016-09-10 04:42:27 -0700190 bool level_controller_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_);
peah2ace3f92016-09-10 04:42:27 -0700210 changed |= (level_controller_enabled != level_controller_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;
peah2ace3f92016-09-10 04:42:27 -0700226 level_controller_enabled_ = level_controller_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 {
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200258 return level_controller_enabled_ || gain_controller2_enabled_ ||
259 capture_post_processor_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,
305 std::unique_ptr<CustomProcessing> render_pre_processor)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200306 : beamformer(beamformer),
Alex Loiko5825aa62017-12-18 16:02:40 +0100307 capture_post_processor(std::move(capture_post_processor)),
308 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800309 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700310 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800311 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700312 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800313 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700314 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700315 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200316 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100317 std::unique_ptr<CustomProcessing> capture_post_processor;
318 std::unique_ptr<CustomProcessing> render_pre_processor;
solenberg5e465c32015-12-08 13:22:33 -0800319};
320
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000321AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700322 webrtc::Config config;
Alex Loiko5825aa62017-12-18 16:02:40 +0100323 return Create(config, nullptr, nullptr, nullptr, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000324}
325
peah88ac8532016-09-12 16:47:25 -0700326AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
Alex Loiko5825aa62017-12-18 16:02:40 +0100327 return Create(config, nullptr, nullptr, nullptr, nullptr);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000328}
329
peah88ac8532016-09-12 16:47:25 -0700330AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700331 NonlinearBeamformer* beamformer) {
Alex Loiko5825aa62017-12-18 16:02:40 +0100332 return Create(config, nullptr, nullptr, nullptr, beamformer);
Sam Zackrisson0beac582017-09-25 12:04:02 +0200333}
334
335AudioProcessing* AudioProcessing::Create(
336 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100337 std::unique_ptr<CustomProcessing> capture_post_processor,
338 std::unique_ptr<EchoControlFactory> echo_control_factory,
339 NonlinearBeamformer* beamformer) {
340 return Create(config, std::move(capture_post_processor), nullptr,
341 std::move(echo_control_factory), beamformer);
342}
343
344AudioProcessing* AudioProcessing::Create(
345 const webrtc::Config& config,
346 std::unique_ptr<CustomProcessing> capture_post_processor,
347 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200348 std::unique_ptr<EchoControlFactory> echo_control_factory,
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200349 NonlinearBeamformer* beamformer) {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200350 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200351 config, std::move(capture_post_processor),
Alex Loiko5825aa62017-12-18 16:02:40 +0100352 std::move(render_pre_processor), std::move(echo_control_factory),
353 beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000354 if (apm->Initialize() != kNoError) {
355 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800356 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000357 }
358
359 return apm;
360}
361
peah88ac8532016-09-12 16:47:25 -0700362AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Alex Loiko5825aa62017-12-18 16:02:40 +0100363 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000364
Sam Zackrisson0beac582017-09-25 12:04:02 +0200365AudioProcessingImpl::AudioProcessingImpl(
366 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100367 std::unique_ptr<CustomProcessing> capture_post_processor,
368 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200369 std::unique_ptr<EchoControlFactory> echo_control_factory,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200370 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800371 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200372 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100373 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800374 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200375 private_submodules_(
376 new ApmPrivateSubmodules(beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100377 std::move(capture_post_processor),
378 std::move(render_pre_processor))),
peahdf3efa82015-11-28 12:35:15 -0800379 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800380 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000381#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700382 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000383#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700384 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000385#endif
andrew1c7075f2015-06-24 18:14:14 -0700386#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800387 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700388#else
aluebs2a346882016-01-11 18:04:30 -0800389 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700390#endif
aluebs2a346882016-01-11 18:04:30 -0800391 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800392 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700393 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700394 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800395 {
396 rtc::CritScope cs_render(&crit_render_);
397 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000398
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200399 // Mark Echo Controller enabled if a factory is injected.
400 capture_nonlocked_.echo_controller_enabled =
401 static_cast<bool>(echo_control_factory_);
402
peahb624d8c2016-03-05 03:01:14 -0800403 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700404 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800405 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700406 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800407 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700408 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800409 public_submodules_->level_estimator.reset(
410 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800411 public_submodules_->noise_suppression.reset(
412 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800413 public_submodules_->voice_detection.reset(
414 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800415 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800416 new GainControlForExperimentalAgc(
417 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700418 private_submodules_->residual_echo_detector.reset(
419 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700420
peahc19f3122016-10-07 14:54:10 -0700421 // TODO(peah): Move this creation to happen only when the level controller
422 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700423 private_submodules_->level_controller.reset(new LevelController());
Sam Zackrisson0beac582017-09-25 12:04:02 +0200424
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200425 // TODO(alessiob): Move the injected gain controller once injection is
426 // implemented.
427 private_submodules_->gain_controller2.reset(new GainController2());
428
Mirko Bonadei675513b2017-11-09 11:09:25 +0100429 RTC_LOG(LS_INFO) << "Capture post processor activated: "
430 << !!private_submodules_->capture_post_processor;
Alex Loiko5825aa62017-12-18 16:02:40 +0100431
432 RTC_LOG(LS_INFO) << "Render pre processor activated: "
433 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800434 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000435
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000436 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000437}
438
439AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800440 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800441 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800442 private_submodules_->agc_manager.reset();
443 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800444 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000445}
446
niklase@google.com470e71d2011-07-07 08:21:25 +0000447int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800448 // Run in a single-threaded manner during initialization.
449 rtc::CritScope cs_render(&crit_render_);
450 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000451 return InitializeLocked();
452}
453
peahde65ddc2016-09-16 15:02:15 -0700454int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
455 int capture_output_sample_rate_hz,
456 int render_input_sample_rate_hz,
457 ChannelLayout capture_input_layout,
458 ChannelLayout capture_output_layout,
459 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700460 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700461 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
462 LayoutHasKeyboard(capture_input_layout)},
463 {capture_output_sample_rate_hz,
464 ChannelsFromLayout(capture_output_layout),
465 LayoutHasKeyboard(capture_output_layout)},
466 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
467 LayoutHasKeyboard(render_input_layout)},
468 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
469 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700470
471 return Initialize(processing_config);
472}
473
474int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800475 // Run in a single-threaded manner during initialization.
476 rtc::CritScope cs_render(&crit_render_);
477 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700478 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000479}
480
peahdf3efa82015-11-28 12:35:15 -0800481int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800482 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700483 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800484}
485
peahdf3efa82015-11-28 12:35:15 -0800486int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700487 const ProcessingConfig& processing_config,
488 bool force_initialization) {
489 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800490}
491
peah192164e2015-11-17 02:16:45 -0800492// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800493// their current values (needs to be called while holding the crit_render_lock).
494int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700495 const ProcessingConfig& processing_config,
496 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800497 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700498 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800499 return kNoError;
500 }
peahdf3efa82015-11-28 12:35:15 -0800501
502 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800503 return InitializeLocked(processing_config);
504}
505
niklase@google.com470e71d2011-07-07 08:21:25 +0000506int AudioProcessingImpl::InitializeLocked() {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200507 UpdateActiveSubmoduleStates();
508
peah522d71b2017-02-23 05:16:26 -0800509 const int capture_audiobuffer_num_channels =
510 capture_nonlocked_.beamformer_enabled
511 ? formats_.api_format.input_stream().num_channels()
512 : formats_.api_format.output_stream().num_channels();
513
peahde65ddc2016-09-16 15:02:15 -0700514 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800515 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700516 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800517 : formats_.api_format.reverse_output_stream().num_frames();
518 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
519 render_.render_audio.reset(new AudioBuffer(
520 formats_.api_format.reverse_input_stream().num_frames(),
521 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700522 formats_.render_processing_format.num_frames(),
523 formats_.render_processing_format.num_channels(),
524 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700525 if (formats_.api_format.reverse_input_stream() !=
526 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800527 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800528 formats_.api_format.reverse_input_stream().num_channels(),
529 formats_.api_format.reverse_input_stream().num_frames(),
530 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800531 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700532 } else {
peahdf3efa82015-11-28 12:35:15 -0800533 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700534 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700535 } else {
peahdf3efa82015-11-28 12:35:15 -0800536 render_.render_audio.reset(nullptr);
537 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700538 }
peahce4d9152017-05-19 01:28:05 -0700539
peahdf3efa82015-11-28 12:35:15 -0800540 capture_.capture_audio.reset(
541 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
542 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700543 capture_nonlocked_.capture_processing_format.num_frames(),
544 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800545 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000546
peahde65ddc2016-09-16 15:02:15 -0700547 public_submodules_->echo_cancellation->Initialize(
548 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
549 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700550 AllocateRenderQueue();
551
ivoc3e9a5372016-10-28 07:55:33 -0700552 int success = public_submodules_->echo_cancellation->enable_metrics(true);
553 RTC_DCHECK_EQ(0, success);
554 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
555 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700556 public_submodules_->echo_control_mobile->Initialize(
557 proc_split_sample_rate_hz(), num_reverse_channels(),
558 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700559
560 public_submodules_->gain_control->Initialize(num_proc_channels(),
561 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700562 if (constants_.use_experimental_agc) {
563 if (!private_submodules_->agc_manager.get()) {
564 private_submodules_->agc_manager.reset(new AgcManagerDirect(
565 public_submodules_->gain_control.get(),
566 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800567 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700568 }
569 private_submodules_->agc_manager->Initialize();
570 private_submodules_->agc_manager->SetCaptureMuted(
571 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700572 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700573 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200574 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000575 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700576#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700577 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700578#endif
peah8271d042016-11-22 07:24:52 -0800579 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700580 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
581 proc_sample_rate_hz());
582 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
583 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700584 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700585 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200586 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700587 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200588 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100589 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800590
aleloi868f32f2017-05-23 07:20:05 -0700591 if (aec_dump_) {
592 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
593 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000594 return kNoError;
595}
596
Michael Graczyk86c6d332015-07-23 11:41:39 -0700597int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200598 UpdateActiveSubmoduleStates();
599
Michael Graczyk86c6d332015-07-23 11:41:39 -0700600 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700601 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
602 return kBadSampleRateError;
603 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000604 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700605
Peter Kasting69558702016-01-12 16:26:35 -0800606 const size_t num_in_channels = config.input_stream().num_channels();
607 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700608
609 // Need at least one input channel.
610 // Need either one output channel or as many outputs as there are inputs.
611 if (num_in_channels == 0 ||
612 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700613 return kBadNumberChannelsError;
614 }
615
aluebsb2328d12016-01-11 20:32:29 -0800616 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800617 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700618 return kBadNumberChannelsError;
619 }
620
peahdf3efa82015-11-28 12:35:15 -0800621 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000622
peahde65ddc2016-09-16 15:02:15 -0700623 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700624 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700625 formats_.api_format.output_stream().sample_rate_hz()),
626 submodule_states_.CaptureMultiBandSubModulesActive() ||
627 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000628
peahde65ddc2016-09-16 15:02:15 -0700629 capture_nonlocked_.capture_processing_format =
630 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700631
peah2ce640f2017-04-07 03:57:48 -0700632 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200633 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700634 render_processing_rate = FindNativeProcessRateToUse(
635 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
636 formats_.api_format.reverse_output_stream().sample_rate_hz()),
637 submodule_states_.CaptureMultiBandSubModulesActive() ||
638 submodule_states_.RenderMultiBandSubModulesActive());
639 } else {
640 render_processing_rate = capture_processing_rate;
641 }
642
aluebseb3603b2016-04-20 15:27:58 -0700643 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
644 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700645 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200646 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700647 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
648 ? kSampleRate32kHz
649 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700650 }
peah2ce640f2017-04-07 03:57:48 -0700651
peahde65ddc2016-09-16 15:02:15 -0700652 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700653 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700654 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
655 kSampleRate8kHz) {
656 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000657 } else {
peahde65ddc2016-09-16 15:02:15 -0700658 render_processing_rate =
659 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000660 }
661
peahde65ddc2016-09-16 15:02:15 -0700662 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000663 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700664 if (submodule_states_.RenderMultiBandSubModulesActive()) {
665 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
666 } else {
667 formats_.render_processing_format = StreamConfig(
668 formats_.api_format.reverse_input_stream().sample_rate_hz(),
669 formats_.api_format.reverse_input_stream().num_channels());
670 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000671
peahde65ddc2016-09-16 15:02:15 -0700672 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
673 kSampleRate32kHz ||
674 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
675 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800676 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000677 } else {
peahdf3efa82015-11-28 12:35:15 -0800678 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700679 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000680 }
681
682 return InitializeLocked();
683}
684
peah88ac8532016-09-12 16:47:25 -0700685void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700686 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700687
peahc19f3122016-10-07 14:54:10 -0700688 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700689 if (!config_ok) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100690 RTC_LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
691 << "level_controller: "
692 << LevelController::ToString(config_.level_controller)
693 << std::endl
694 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700695 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700696 }
697
698 // Run in a single-threaded manner when applying the settings.
699 rtc::CritScope cs_render(&crit_render_);
700 rtc::CritScope cs_capture(&crit_capture_);
701
peahc19f3122016-10-07 14:54:10 -0700702 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
703 // with the value in config_ everywhere in the code.
704 if (capture_nonlocked_.level_controller_enabled !=
705 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700706 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700707 config_.level_controller.enabled;
708 // TODO(peah): Remove the conditional initialization to always initialize
709 // the level controller regardless of whether it is enabled or not.
710 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700711 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100712 RTC_LOG(LS_INFO) << "Level controller activated: "
713 << capture_nonlocked_.level_controller_enabled;
peahc19f3122016-10-07 14:54:10 -0700714
715 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800716
717 InitializeLowCutFilter();
718
Mirko Bonadei675513b2017-11-09 11:09:25 +0100719 RTC_LOG(LS_INFO) << "Highpass filter activated: "
720 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800721
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200722 // Deprecated way of activating AEC3.
723 // TODO(gustaf): Remove when possible.
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200724 if (config.echo_canceller3.enabled && !echo_control_factory_) {
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200725 capture_nonlocked_.echo_controller_enabled =
peahe0eae3c2016-12-14 01:16:23 -0800726 config_.echo_canceller3.enabled;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200727 echo_control_factory_ =
728 std::unique_ptr<EchoControlFactory>(new EchoCanceller3Factory());
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200729 InitializeEchoController();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100730 RTC_LOG(LS_INFO) << "Echo canceller 3 activated: "
731 << capture_nonlocked_.echo_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800732 }
alessiob3ec96df2017-05-22 06:57:06 -0700733
734 config_ok = GainController2::Validate(config_.gain_controller2);
735 if (!config_ok) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100736 RTC_LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
737 << "Gain Controller 2: "
738 << GainController2::ToString(config_.gain_controller2)
739 << std::endl
740 << "Reverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700741 config_.gain_controller2 = AudioProcessing::Config::GainController2();
742 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200743 InitializeGainController2();
744 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100745 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
746 << config_.gain_controller2.enabled;
peah88ac8532016-09-12 16:47:25 -0700747}
748
749void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800750 // Run in a single-threaded manner when setting the extra options.
751 rtc::CritScope cs_render(&crit_render_);
752 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000753
peahb624d8c2016-03-05 03:01:14 -0800754 public_submodules_->echo_cancellation->SetExtraOptions(config);
755
peahdf3efa82015-11-28 12:35:15 -0800756 if (capture_.transient_suppressor_enabled !=
757 config.Get<ExperimentalNs>().enabled) {
758 capture_.transient_suppressor_enabled =
759 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000760 InitializeTransient();
761 }
aluebs2a346882016-01-11 18:04:30 -0800762
peah1bcfce52016-08-26 07:16:04 -0700763#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700764 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700765 config.Get<Intelligibility>().enabled) {
766 capture_nonlocked_.intelligibility_enabled =
767 config.Get<Intelligibility>().enabled;
768 InitializeIntelligibility();
769 }
peah1bcfce52016-08-26 07:16:04 -0700770#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700771
aluebs2a346882016-01-11 18:04:30 -0800772#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800773 if (capture_nonlocked_.beamformer_enabled !=
774 config.Get<Beamforming>().enabled) {
775 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800776 if (config.Get<Beamforming>().array_geometry.size() > 1) {
777 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
778 }
779 capture_.target_direction = config.Get<Beamforming>().target_direction;
780 InitializeBeamformer();
781 }
782#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000783}
784
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000785int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800786 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700787 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000788}
789
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000790int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800791 // Used as callback from submodules, hence locking is not allowed.
792 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000793}
794
Peter Kasting69558702016-01-12 16:26:35 -0800795size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800796 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700797 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000798}
799
Peter Kasting69558702016-01-12 16:26:35 -0800800size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800801 // Used as callback from submodules, hence locking is not allowed.
802 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000803}
804
Peter Kasting69558702016-01-12 16:26:35 -0800805size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800806 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700807 return (capture_nonlocked_.beamformer_enabled ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200808 capture_nonlocked_.echo_controller_enabled)
peahedddac52017-05-16 01:08:58 -0700809 ? 1
810 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800811}
812
Peter Kasting69558702016-01-12 16:26:35 -0800813size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800814 // Used as callback from submodules, hence locking is not allowed.
815 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000816}
817
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000818void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800819 rtc::CritScope cs(&crit_capture_);
820 capture_.output_will_be_muted = muted;
821 if (private_submodules_->agc_manager.get()) {
822 private_submodules_->agc_manager->SetCaptureMuted(
823 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000824 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000825}
826
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000827
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000828int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700829 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000830 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000831 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000832 int output_sample_rate_hz,
833 ChannelLayout output_layout,
834 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800835 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800836 StreamConfig input_stream;
837 StreamConfig output_stream;
838 {
839 // Access the formats_.api_format.input_stream beneath the capture lock.
840 // The lock must be released as it is later required in the call
841 // to ProcessStream(,,,);
842 rtc::CritScope cs(&crit_capture_);
843 input_stream = formats_.api_format.input_stream();
844 output_stream = formats_.api_format.output_stream();
845 }
846
Michael Graczyk86c6d332015-07-23 11:41:39 -0700847 input_stream.set_sample_rate_hz(input_sample_rate_hz);
848 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
849 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700850 output_stream.set_sample_rate_hz(output_sample_rate_hz);
851 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
852 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
853
854 if (samples_per_channel != input_stream.num_frames()) {
855 return kBadDataLengthError;
856 }
857 return ProcessStream(src, input_stream, output_stream, dest);
858}
859
860int AudioProcessingImpl::ProcessStream(const float* const* src,
861 const StreamConfig& input_config,
862 const StreamConfig& output_config,
863 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800864 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800865 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700866 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800867 {
868 // Acquire the capture lock in order to safely call the function
869 // that retrieves the render side data. This function accesses apm
870 // getters that need the capture lock held when being called.
871 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700872 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800873
874 if (!src || !dest) {
875 return kNullPointerError;
876 }
877
878 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700879 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000880 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000881
Michael Graczyk86c6d332015-07-23 11:41:39 -0700882 processing_config.input_stream() = input_config;
883 processing_config.output_stream() = output_config;
884
peahdf3efa82015-11-28 12:35:15 -0800885 {
886 // Do conditional reinitialization.
887 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700888 RETURN_ON_ERR(
889 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800890 }
891 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700892 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
893 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000894
aleloi868f32f2017-05-23 07:20:05 -0700895 if (aec_dump_) {
896 RecordUnprocessedCaptureStream(src);
897 }
898
peahdf3efa82015-11-28 12:35:15 -0800899 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700900 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800901 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000902
aleloi868f32f2017-05-23 07:20:05 -0700903 if (aec_dump_) {
904 RecordProcessedCaptureStream(dest);
905 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000906 return kNoError;
907}
908
peah9e6a2902017-05-15 07:19:21 -0700909void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700910 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
911 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700912 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700913
kwibergaf476c72016-11-28 15:21:39 -0800914 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700915
916 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700917 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700918 // The data queue is full and needs to be emptied.
919 EmptyQueuedRenderAudio();
920
921 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700922 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700923 RTC_DCHECK(result);
924 }
925
926 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
927 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700928 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700929
930 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700931 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700932 // The data queue is full and needs to be emptied.
933 EmptyQueuedRenderAudio();
934
935 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700936 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700937 RTC_DCHECK(result);
938 }
peah701d6282016-10-25 05:42:20 -0700939
940 if (!constants_.use_experimental_agc) {
941 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
942 // Insert the samples into the queue.
943 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
944 // The data queue is full and needs to be emptied.
945 EmptyQueuedRenderAudio();
946
947 // Retry the insert (should always work).
948 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
949 RTC_DCHECK(result);
950 }
951 }
peah9e6a2902017-05-15 07:19:21 -0700952}
ivoc9f4a4a02016-10-28 05:39:16 -0700953
peah9e6a2902017-05-15 07:19:21 -0700954void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700955 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
956
957 // Insert the samples into the queue.
958 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
959 // The data queue is full and needs to be emptied.
960 EmptyQueuedRenderAudio();
961
962 // Retry the insert (should always work).
963 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
964 RTC_DCHECK(result);
965 }
peah764e3642016-10-22 05:04:30 -0700966}
967
968void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700969 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700970 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700971 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700972 EchoCancellationImpl::NumCancellersRequired(
973 num_output_channels(), num_reverse_channels()));
974
peah701d6282016-10-25 05:42:20 -0700975 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700976 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700977 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700978 EchoControlMobileImpl::NumCancellersRequired(
979 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700980
peah701d6282016-10-25 05:42:20 -0700981 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700982 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700983
ivoc9f4a4a02016-10-28 05:39:16 -0700984 const size_t new_red_render_queue_element_max_size =
985 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
986
peaha0624602016-10-25 04:45:24 -0700987 // Reallocate the queues if the queue item sizes are too small to fit the
988 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700989 if (aec_render_queue_element_max_size_ <
990 new_aec_render_queue_element_max_size) {
991 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700992
peaha0624602016-10-25 04:45:24 -0700993 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700994 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700995
peah701d6282016-10-25 05:42:20 -0700996 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700997 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
998 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700999 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001000 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001001
peah701d6282016-10-25 05:42:20 -07001002 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1003 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001004 } else {
peah701d6282016-10-25 05:42:20 -07001005 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001006 }
1007
peah701d6282016-10-25 05:42:20 -07001008 if (aecm_render_queue_element_max_size_ <
1009 new_aecm_render_queue_element_max_size) {
1010 aecm_render_queue_element_max_size_ =
1011 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001012
1013 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001014 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001015
peah701d6282016-10-25 05:42:20 -07001016 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001017 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1018 kMaxNumFramesToBuffer, template_queue_element,
1019 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001020 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001021
peah701d6282016-10-25 05:42:20 -07001022 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1023 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001024 } else {
peah701d6282016-10-25 05:42:20 -07001025 aecm_render_signal_queue_->Clear();
1026 }
1027
1028 if (agc_render_queue_element_max_size_ <
1029 new_agc_render_queue_element_max_size) {
1030 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1031
1032 std::vector<int16_t> template_queue_element(
1033 agc_render_queue_element_max_size_);
1034
1035 agc_render_signal_queue_.reset(
1036 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1037 kMaxNumFramesToBuffer, template_queue_element,
1038 RenderQueueItemVerifier<int16_t>(
1039 agc_render_queue_element_max_size_)));
1040
1041 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1042 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1043 } else {
1044 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001045 }
ivoc9f4a4a02016-10-28 05:39:16 -07001046
1047 if (red_render_queue_element_max_size_ <
1048 new_red_render_queue_element_max_size) {
1049 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1050
1051 std::vector<float> template_queue_element(
1052 red_render_queue_element_max_size_);
1053
1054 red_render_signal_queue_.reset(
1055 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1056 kMaxNumFramesToBuffer, template_queue_element,
1057 RenderQueueItemVerifier<float>(
1058 red_render_queue_element_max_size_)));
1059
1060 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1061 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1062 } else {
1063 red_render_signal_queue_->Clear();
1064 }
peah764e3642016-10-22 05:04:30 -07001065}
1066
1067void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1068 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001069 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001070 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001071 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001072 }
1073
peah701d6282016-10-25 05:42:20 -07001074 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001075 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001076 aecm_capture_queue_buffer_);
1077 }
1078
1079 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1080 public_submodules_->gain_control->ProcessRenderAudio(
1081 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001082 }
ivoc9f4a4a02016-10-28 05:39:16 -07001083
1084 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1085 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1086 red_capture_queue_buffer_);
1087 }
peah764e3642016-10-22 05:04:30 -07001088}
1089
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001090int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001091 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001092 {
1093 // Acquire the capture lock in order to safely call the function
1094 // that retrieves the render side data. This function accesses apm
1095 // getters that need the capture lock held when being called.
1096 // The lock needs to be released as
1097 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1098 // as well.
1099 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001100 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001101 }
peahfa6228e2015-11-16 16:27:42 -08001102
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001103 if (!frame) {
1104 return kNullPointerError;
1105 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001106 // Must be a native rate.
1107 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1108 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001109 frame->sample_rate_hz_ != kSampleRate32kHz &&
1110 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001111 return kBadSampleRateError;
1112 }
peah192164e2015-11-17 02:16:45 -08001113
peahdf3efa82015-11-28 12:35:15 -08001114 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001115 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001116 {
1117 // Aquire lock for the access of api_format.
1118 // The lock is released immediately due to the conditional
1119 // reinitialization.
1120 rtc::CritScope cs_capture(&crit_capture_);
1121 // TODO(ajm): The input and output rates and channels are currently
1122 // constrained to be identical in the int16 interface.
1123 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001124
1125 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001126 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001127 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1128 processing_config.input_stream().set_num_channels(frame->num_channels_);
1129 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1130 processing_config.output_stream().set_num_channels(frame->num_channels_);
1131
peahdf3efa82015-11-28 12:35:15 -08001132 {
1133 // Do conditional reinitialization.
1134 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001135 RETURN_ON_ERR(
1136 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001137 }
1138 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001139 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001140 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001141 return kBadDataLengthError;
1142 }
1143
aleloi868f32f2017-05-23 07:20:05 -07001144 if (aec_dump_) {
1145 RecordUnprocessedCaptureStream(*frame);
1146 }
1147
peahdf3efa82015-11-28 12:35:15 -08001148 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001149 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001150 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001151 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1152 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001153
aleloi868f32f2017-05-23 07:20:05 -07001154 if (aec_dump_) {
1155 RecordProcessedCaptureStream(*frame);
1156 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001157
1158 return kNoError;
1159}
1160
peahde65ddc2016-09-16 15:02:15 -07001161int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001162 // Ensure that not both the AEC and AECM are active at the same time.
1163 // TODO(peah): Simplify once the public API Enable functions for these
1164 // are moved to APM.
1165 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1166 public_submodules_->echo_control_mobile->is_enabled()));
1167
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001168 MaybeUpdateHistograms();
1169
peahde65ddc2016-09-16 15:02:15 -07001170 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001171
peah1b08dc32016-12-20 13:45:58 -08001172 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001173 capture_buffer->channels_const()[0],
1174 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001175 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1176 if (log_rms) {
1177 capture_rms_interval_counter_ = 0;
1178 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001179 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1180 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1181 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1182 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001183 }
1184
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001185 if (private_submodules_->echo_controller) {
Per Ã…hgren9aed31c2017-06-29 20:23:27 +02001186 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1187 // issues have been addressed.
1188 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001189 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001190 }
1191
peahbe615622016-02-13 16:40:47 -08001192 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001193 public_submodules_->gain_control->is_enabled()) {
1194 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001195 capture_buffer->channels()[0], capture_buffer->num_channels(),
1196 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001197 }
1198
peah2ace3f92016-09-10 04:42:27 -07001199 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1200 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001201 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1202 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001203 }
1204
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001205 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001206 // Force down-mixing of the number of channels after the detection of
1207 // capture signal saturation.
1208 // TODO(peah): Look into ensuring that this kind of tampering with the
1209 // AudioBuffer functionality should not be needed.
1210 capture_buffer->set_num_channels(1);
1211 }
1212
aluebsb2328d12016-01-11 20:32:29 -08001213 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001214 private_submodules_->beamformer->AnalyzeChunk(
1215 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001216 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001217 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001218 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001219
peahe0eae3c2016-12-14 01:16:23 -08001220 // TODO(peah): Move the AEC3 low-cut filter to this place.
1221 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001222 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001223 private_submodules_->low_cut_filter->Process(capture_buffer);
1224 }
peahde65ddc2016-09-16 15:02:15 -07001225 RETURN_ON_ERR(
1226 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1227 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001228
1229 // Ensure that the stream delay was set before the call to the
1230 // AEC ProcessCaptureAudio function.
1231 if (public_submodules_->echo_cancellation->is_enabled() &&
1232 !was_stream_delay_set()) {
1233 return AudioProcessing::kStreamParameterNotSetError;
1234 }
1235
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001236 if (private_submodules_->echo_controller) {
1237 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001238 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001239 } else {
1240 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1241 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001242 }
1243
peahdf3efa82015-11-28 12:35:15 -08001244 if (public_submodules_->echo_control_mobile->is_enabled() &&
1245 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001246 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001247 }
peahde65ddc2016-09-16 15:02:15 -07001248 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001249#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001250 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001251 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001252 int gain_db = public_submodules_->gain_control->is_enabled() ?
1253 public_submodules_->gain_control->compression_gain_db() :
1254 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001255 float gain = std::pow(10.f, gain_db / 20.f);
1256 gain *= capture_nonlocked_.level_controller_enabled ?
1257 private_submodules_->level_controller->GetLastGain() :
1258 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001259 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001260 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001261 }
peah1bcfce52016-08-26 07:16:04 -07001262#endif
peah253534d2016-03-15 04:32:28 -07001263
1264 // Ensure that the stream delay was set before the call to the
1265 // AECM ProcessCaptureAudio function.
1266 if (public_submodules_->echo_control_mobile->is_enabled() &&
1267 !was_stream_delay_set()) {
1268 return AudioProcessing::kStreamParameterNotSetError;
1269 }
1270
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001271 if (!(private_submodules_->echo_controller ||
Per Ã…hgren46537a32017-06-07 10:08:10 +02001272 public_submodules_->echo_cancellation->is_enabled())) {
1273 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1274 capture_buffer, stream_delay_ms()));
1275 }
ivoc9f4a4a02016-10-28 05:39:16 -07001276
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001277 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001278 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001279 }
1280
peahde65ddc2016-09-16 15:02:15 -07001281 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001282
peahbe615622016-02-13 16:40:47 -08001283 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001284 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001285 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001286 private_submodules_->beamformer->is_target_present())) {
1287 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001288 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1289 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001290 }
peahb8fbb542016-03-15 02:28:08 -07001291 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001292 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001293
peah2ace3f92016-09-10 04:42:27 -07001294 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1295 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001296 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1297 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001298 }
1299
peah9e6a2902017-05-15 07:19:21 -07001300 if (config_.residual_echo_detector.enabled) {
1301 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1302 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1303 capture_buffer->num_frames()));
1304 }
1305
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001306 // TODO(aluebs): Investigate if the transient suppression placement should be
1307 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001308 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001309 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001310 private_submodules_->agc_manager.get()
1311 ? private_submodules_->agc_manager->voice_probability()
1312 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001313
peahdf3efa82015-11-28 12:35:15 -08001314 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001315 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1316 capture_buffer->num_channels(),
1317 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1318 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1319 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001320 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001321 }
1322
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001323 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001324 private_submodules_->gain_controller2->Process(capture_buffer);
1325 }
1326
peahca4cac72016-06-29 15:26:12 -07001327 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001328 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001329 }
1330
Sam Zackrisson0beac582017-09-25 12:04:02 +02001331 if (private_submodules_->capture_post_processor) {
1332 private_submodules_->capture_post_processor->Process(capture_buffer);
1333 }
1334
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001335 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001336 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001337
peah1b08dc32016-12-20 13:45:58 -08001338 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1339 capture_buffer->channels_const()[0],
1340 capture_nonlocked_.capture_processing_format.num_frames()));
1341 if (log_rms) {
1342 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1343 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1344 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1345 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1346 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1347 }
1348
peahdf3efa82015-11-28 12:35:15 -08001349 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001350 return kNoError;
1351}
1352
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001353int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001354 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001355 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001356 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001357 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001358 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001359 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001360 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001361 };
1362 if (samples_per_channel != reverse_config.num_frames()) {
1363 return kBadDataLengthError;
1364 }
peahdf3efa82015-11-28 12:35:15 -08001365 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001366}
1367
peahde65ddc2016-09-16 15:02:15 -07001368int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1369 const StreamConfig& input_config,
1370 const StreamConfig& output_config,
1371 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001372 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001373 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001374 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001375 if (submodule_states_.RenderMultiBandProcessingActive() ||
1376 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001377 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1378 dest);
peah2ace3f92016-09-10 04:42:27 -07001379 } else if (formats_.api_format.reverse_input_stream() !=
1380 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001381 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1382 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001383 } else {
peahde65ddc2016-09-16 15:02:15 -07001384 CopyAudioIfNeeded(src, input_config.num_frames(),
1385 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001386 }
1387
1388 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001389}
1390
peahdf3efa82015-11-28 12:35:15 -08001391int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001392 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001393 const StreamConfig& input_config,
1394 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001395 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001396 return kNullPointerError;
1397 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001398
peahde65ddc2016-09-16 15:02:15 -07001399 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001400 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001401 }
1402
peahdf3efa82015-11-28 12:35:15 -08001403 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001404 processing_config.reverse_input_stream() = input_config;
1405 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001406
peahdf3efa82015-11-28 12:35:15 -08001407 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001408 assert(input_config.num_frames() ==
1409 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001410
aleloi868f32f2017-05-23 07:20:05 -07001411 if (aec_dump_) {
1412 const size_t channel_size =
1413 formats_.api_format.reverse_input_stream().num_frames();
1414 const size_t num_channels =
1415 formats_.api_format.reverse_input_stream().num_channels();
1416 aec_dump_->WriteRenderStreamMessage(
1417 FloatAudioFrame(src, num_channels, channel_size));
1418 }
peahdf3efa82015-11-28 12:35:15 -08001419 render_.render_audio->CopyFrom(src,
1420 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001421 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001422}
1423
1424int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001425 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001426 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001427 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001428 return kNullPointerError;
1429 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001430 // Must be a native rate.
1431 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1432 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001433 frame->sample_rate_hz_ != kSampleRate32kHz &&
1434 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001435 return kBadSampleRateError;
1436 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001437
Michael Graczyk86c6d332015-07-23 11:41:39 -07001438 if (frame->num_channels_ <= 0) {
1439 return kBadNumberChannelsError;
1440 }
1441
peahdf3efa82015-11-28 12:35:15 -08001442 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001443 processing_config.reverse_input_stream().set_sample_rate_hz(
1444 frame->sample_rate_hz_);
1445 processing_config.reverse_input_stream().set_num_channels(
1446 frame->num_channels_);
1447 processing_config.reverse_output_stream().set_sample_rate_hz(
1448 frame->sample_rate_hz_);
1449 processing_config.reverse_output_stream().set_num_channels(
1450 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001451
peahdf3efa82015-11-28 12:35:15 -08001452 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001453 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001454 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001455 return kBadDataLengthError;
1456 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001457
aleloi868f32f2017-05-23 07:20:05 -07001458 if (aec_dump_) {
1459 aec_dump_->WriteRenderStreamMessage(*frame);
1460 }
1461
peahdf3efa82015-11-28 12:35:15 -08001462 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001463 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001464 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001465 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1466 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001467 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001468}
niklase@google.com470e71d2011-07-07 08:21:25 +00001469
peahde65ddc2016-09-16 15:02:15 -07001470int AudioProcessingImpl::ProcessRenderStreamLocked() {
1471 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001472
1473 QueueNonbandedRenderAudio(render_buffer);
1474
Alex Loiko5825aa62017-12-18 16:02:40 +01001475 if (private_submodules_->render_pre_processor) {
1476 private_submodules_->render_pre_processor->Process(render_buffer);
1477 }
1478
peah2ace3f92016-09-10 04:42:27 -07001479 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001480 SampleRateSupportsMultiBand(
1481 formats_.render_processing_format.sample_rate_hz())) {
1482 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001483 }
1484
peah1bcfce52016-08-26 07:16:04 -07001485#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001486 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001487 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001488 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001489 }
peah1bcfce52016-08-26 07:16:04 -07001490#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001491
peahce4d9152017-05-19 01:28:05 -07001492 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1493 QueueBandedRenderAudio(render_buffer);
1494 }
1495
peahe0eae3c2016-12-14 01:16:23 -08001496 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001497 if (private_submodules_->echo_controller) {
1498 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001499 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001500
peah2ace3f92016-09-10 04:42:27 -07001501 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001502 SampleRateSupportsMultiBand(
1503 formats_.render_processing_format.sample_rate_hz())) {
1504 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001505 }
1506
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001507 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001508}
1509
1510int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001511 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001512 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001513 capture_.was_stream_delay_set = true;
1514 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001515
niklase@google.com470e71d2011-07-07 08:21:25 +00001516 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001517 delay = 0;
1518 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001519 }
1520
1521 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1522 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001523 delay = 500;
1524 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001525 }
1526
peahdf3efa82015-11-28 12:35:15 -08001527 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001528 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001529}
1530
1531int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001532 // Used as callback from submodules, hence locking is not allowed.
1533 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001534}
1535
1536bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001537 // Used as callback from submodules, hence locking is not allowed.
1538 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001539}
1540
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001541void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001542 rtc::CritScope cs(&crit_capture_);
1543 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001544}
1545
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001546void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001547 rtc::CritScope cs(&crit_capture_);
1548 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001549}
1550
1551int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001552 rtc::CritScope cs(&crit_capture_);
1553 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001554}
1555
aleloi868f32f2017-05-23 07:20:05 -07001556void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1557 RTC_DCHECK(aec_dump);
1558 rtc::CritScope cs_render(&crit_render_);
1559 rtc::CritScope cs_capture(&crit_capture_);
1560
1561 // The previously attached AecDump will be destroyed with the
1562 // 'aec_dump' parameter, which is after locks are released.
1563 aec_dump_.swap(aec_dump);
1564 WriteAecDumpConfigMessage(true);
1565 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1566}
1567
1568void AudioProcessingImpl::DetachAecDump() {
1569 // The d-tor of a task-queue based AecDump blocks until all pending
1570 // tasks are done. This construction avoids blocking while holding
1571 // the render and capture locks.
1572 std::unique_ptr<AecDump> aec_dump = nullptr;
1573 {
1574 rtc::CritScope cs_render(&crit_render_);
1575 rtc::CritScope cs_capture(&crit_capture_);
1576 aec_dump = std::move(aec_dump_);
1577 }
1578}
1579
ivoc4e477a12017-01-15 08:29:46 -08001580AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1581 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1582 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1583 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1584 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1585}
1586
1587AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1588 const AudioProcessingStatistics& other) = default;
1589
1590AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1591 default;
1592
ivoc3e9a5372016-10-28 07:55:33 -07001593// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1594AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1595 const {
1596 return AudioProcessingStatistics();
1597}
1598
Ivo Creusenae026092017-11-20 13:07:16 +01001599// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001600AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001601 bool has_remote_tracks) const {
1602 return AudioProcessingStats();
1603}
1604
ivoc3e9a5372016-10-28 07:55:33 -07001605AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1606 const {
1607 AudioProcessingStatistics stats;
1608 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001609 if (private_submodules_->echo_controller) {
1610 rtc::CritScope cs_capture(&crit_capture_);
1611 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1612 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1613 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1614 // Instant value will also be used for min, max and average.
1615 stats.echo_return_loss.Set(erl, erl, erl, erl);
1616 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1617 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1618 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001619 stats.a_nlp.Set(metrics.a_nlp);
1620 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1621 stats.echo_return_loss.Set(metrics.echo_return_loss);
1622 stats.echo_return_loss_enhancement.Set(
1623 metrics.echo_return_loss_enhancement);
1624 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1625 }
ivoc9c192b22017-03-16 04:22:14 -07001626 {
1627 rtc::CritScope cs_capture(&crit_capture_);
1628 stats.residual_echo_likelihood =
1629 private_submodules_->residual_echo_detector->echo_likelihood();
1630 stats.residual_echo_likelihood_recent_max =
1631 private_submodules_->residual_echo_detector
1632 ->echo_likelihood_recent_max();
1633 }
ivoc3e9a5372016-10-28 07:55:33 -07001634 public_submodules_->echo_cancellation->GetDelayMetrics(
1635 &stats.delay_median, &stats.delay_standard_deviation,
1636 &stats.fraction_poor_delays);
1637 return stats;
1638}
1639
Ivo Creusen56d46092017-11-24 17:29:59 +01001640AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001641 bool has_remote_tracks) const {
1642 AudioProcessingStats stats;
1643 if (has_remote_tracks) {
1644 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001645 if (private_submodules_->echo_controller) {
1646 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001647 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1648 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001649 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001650 ec_metrics.echo_return_loss_enhancement;
Per Ã…hgren83c4a022017-11-27 12:07:09 +01001651 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001652 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1653 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001654 if (metrics.divergent_filter_fraction != -1.0f) {
1655 stats.divergent_filter_fraction =
1656 rtc::Optional<double>(metrics.divergent_filter_fraction);
1657 }
1658 if (metrics.echo_return_loss.instant != -100) {
1659 stats.echo_return_loss =
1660 rtc::Optional<double>(metrics.echo_return_loss.instant);
1661 }
1662 if (metrics.echo_return_loss_enhancement.instant != -100) {
1663 stats.echo_return_loss_enhancement =
1664 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1665 }
1666 }
1667 if (config_.residual_echo_detector.enabled) {
1668 rtc::CritScope cs_capture(&crit_capture_);
1669 stats.residual_echo_likelihood = rtc::Optional<double>(
1670 private_submodules_->residual_echo_detector->echo_likelihood());
1671 stats.residual_echo_likelihood_recent_max =
1672 rtc::Optional<double>(private_submodules_->residual_echo_detector
1673 ->echo_likelihood_recent_max());
1674 }
1675 int delay_median, delay_std;
1676 float fraction_poor_delays;
1677 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1678 &delay_median, &delay_std, &fraction_poor_delays) ==
1679 Error::kNoError) {
1680 if (delay_median >= 0) {
1681 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1682 }
1683 if (delay_std >= 0) {
1684 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1685 }
1686 }
1687 }
1688 return stats;
1689}
1690
niklase@google.com470e71d2011-07-07 08:21:25 +00001691EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001692 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001693}
1694
1695EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001696 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001697}
1698
1699GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001700 if (constants_.use_experimental_agc) {
1701 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001702 }
peahbfa97112016-03-10 21:09:04 -08001703 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001704}
1705
1706HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001707 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001708}
1709
1710LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001711 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001712}
1713
1714NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001715 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001716}
1717
1718VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001719 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001720}
1721
peah8271d042016-11-22 07:24:52 -08001722void AudioProcessingImpl::MutateConfig(
1723 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1724 rtc::CritScope cs_render(&crit_render_);
1725 rtc::CritScope cs_capture(&crit_capture_);
1726 mutator(&config_);
1727 ApplyConfig(config_);
1728}
1729
1730AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1731 rtc::CritScope cs_render(&crit_render_);
1732 rtc::CritScope cs_capture(&crit_capture_);
1733 return config_;
1734}
1735
peah2ace3f92016-09-10 04:42:27 -07001736bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1737 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001738 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001739 public_submodules_->echo_cancellation->is_enabled(),
1740 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001741 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001742 public_submodules_->noise_suppression->is_enabled(),
1743 capture_nonlocked_.intelligibility_enabled,
1744 capture_nonlocked_.beamformer_enabled,
1745 public_submodules_->gain_control->is_enabled(),
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001746 config_.gain_controller2.enabled,
peah2ace3f92016-09-10 04:42:27 -07001747 capture_nonlocked_.level_controller_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001748 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001749 public_submodules_->voice_detection->is_enabled(),
1750 public_submodules_->level_estimator->is_enabled(),
1751 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001752}
1753
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001754
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001755void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001756 if (capture_.transient_suppressor_enabled) {
1757 if (!public_submodules_->transient_suppressor.get()) {
1758 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001759 }
peahdf3efa82015-11-28 12:35:15 -08001760 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001761 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1762 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001763 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001764}
1765
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001766void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001767 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001768 if (!private_submodules_->beamformer) {
1769 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001770 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001771 }
peahdf3efa82015-11-28 12:35:15 -08001772 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1773 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001774 }
1775}
1776
ekmeyerson60d9b332015-08-14 10:35:55 -07001777void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001778#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001779 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001780 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001781 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001782 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001783 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001784 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001785 }
peah1bcfce52016-08-26 07:16:04 -07001786#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001787}
1788
peah8271d042016-11-22 07:24:52 -08001789void AudioProcessingImpl::InitializeLowCutFilter() {
1790 if (config_.high_pass_filter.enabled) {
1791 private_submodules_->low_cut_filter.reset(
1792 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1793 } else {
1794 private_submodules_->low_cut_filter.reset();
1795 }
1796}
alessiob3ec96df2017-05-22 06:57:06 -07001797
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001798void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001799 if (echo_control_factory_) {
1800 private_submodules_->echo_controller =
1801 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001802 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001803 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001804 }
1805}
peah8271d042016-11-22 07:24:52 -08001806
alessiob3ec96df2017-05-22 06:57:06 -07001807void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001808 if (config_.gain_controller2.enabled) {
1809 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001810 }
1811}
1812
peahca4cac72016-06-29 15:26:12 -07001813void AudioProcessingImpl::InitializeLevelController() {
1814 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1815}
1816
ivoc9f4a4a02016-10-28 05:39:16 -07001817void AudioProcessingImpl::InitializeResidualEchoDetector() {
1818 private_submodules_->residual_echo_detector->Initialize();
1819}
1820
Sam Zackrisson0beac582017-09-25 12:04:02 +02001821void AudioProcessingImpl::InitializePostProcessor() {
1822 if (private_submodules_->capture_post_processor) {
1823 private_submodules_->capture_post_processor->Initialize(
1824 proc_sample_rate_hz(), num_proc_channels());
1825 }
1826}
1827
Alex Loiko5825aa62017-12-18 16:02:40 +01001828void AudioProcessingImpl::InitializePreProcessor() {
1829 if (private_submodules_->render_pre_processor) {
1830 private_submodules_->render_pre_processor->Initialize(
1831 formats_.render_processing_format.sample_rate_hz(),
1832 formats_.render_processing_format.num_channels());
1833 }
1834}
1835
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001836void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001837 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001838
1839 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001840 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001841 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001842 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001843 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001844 capture_.stream_delay_jumps = 0;
1845 }
1846 if (capture_.aec_system_delay_jumps == -1 &&
1847 echo_cancellation()->stream_has_echo()) {
1848 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001849 }
1850
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001851 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001852 const int diff_stream_delay_ms =
1853 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1854 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1855 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001856 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1857 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001858 if (capture_.stream_delay_jumps == -1) {
1859 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001860 }
peahdf3efa82015-11-28 12:35:15 -08001861 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001862 }
peahdf3efa82015-11-28 12:35:15 -08001863 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001864
1865 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001866 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001867 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001868 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001869 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001870 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1871 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001872 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001873 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001874 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001875 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001876 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1877 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1878 100);
peahdf3efa82015-11-28 12:35:15 -08001879 if (capture_.aec_system_delay_jumps == -1) {
1880 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001881 }
peahdf3efa82015-11-28 12:35:15 -08001882 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001883 }
peahdf3efa82015-11-28 12:35:15 -08001884 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001885 }
1886}
1887
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001888void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001889 // Run in a single-threaded manner.
1890 rtc::CritScope cs_render(&crit_render_);
1891 rtc::CritScope cs_capture(&crit_capture_);
1892
1893 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001894 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001895 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001896 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001897 }
peahdf3efa82015-11-28 12:35:15 -08001898 capture_.stream_delay_jumps = -1;
1899 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001900
peahdf3efa82015-11-28 12:35:15 -08001901 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001902 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1903 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001904 }
peahdf3efa82015-11-28 12:35:15 -08001905 capture_.aec_system_delay_jumps = -1;
1906 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001907}
1908
aleloi868f32f2017-05-23 07:20:05 -07001909void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1910 if (!aec_dump_) {
1911 return;
1912 }
1913 std::string experiments_description =
1914 public_submodules_->echo_cancellation->GetExperimentsDescription();
1915 // TODO(peah): Add semicolon-separated concatenations of experiment
1916 // descriptions for other submodules.
1917 if (capture_nonlocked_.level_controller_enabled) {
1918 experiments_description += "LevelController;";
1919 }
1920 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1921 experiments_description += "AgcClippingLevelExperiment;";
1922 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001923 if (capture_nonlocked_.echo_controller_enabled) {
1924 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001925 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001926 if (config_.gain_controller2.enabled) {
1927 experiments_description += "GainController2;";
1928 }
aleloi868f32f2017-05-23 07:20:05 -07001929
1930 InternalAPMConfig apm_config;
1931
1932 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1933 apm_config.aec_delay_agnostic_enabled =
1934 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1935 apm_config.aec_drift_compensation_enabled =
1936 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1937 apm_config.aec_extended_filter_enabled =
1938 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1939 apm_config.aec_suppression_level = static_cast<int>(
1940 public_submodules_->echo_cancellation->suppression_level());
1941
1942 apm_config.aecm_enabled =
1943 public_submodules_->echo_control_mobile->is_enabled();
1944 apm_config.aecm_comfort_noise_enabled =
1945 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1946 apm_config.aecm_routing_mode =
1947 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1948
1949 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1950 apm_config.agc_mode =
1951 static_cast<int>(public_submodules_->gain_control->mode());
1952 apm_config.agc_limiter_enabled =
1953 public_submodules_->gain_control->is_limiter_enabled();
1954 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1955
1956 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1957
1958 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1959 apm_config.ns_level =
1960 static_cast<int>(public_submodules_->noise_suppression->level());
1961
1962 apm_config.transient_suppression_enabled =
1963 capture_.transient_suppressor_enabled;
1964 apm_config.intelligibility_enhancer_enabled =
1965 capture_nonlocked_.intelligibility_enabled;
1966 apm_config.experiments_description = experiments_description;
1967
1968 if (!forced && apm_config == apm_config_for_aec_dump_) {
1969 return;
1970 }
1971 aec_dump_->WriteConfig(apm_config);
1972 apm_config_for_aec_dump_ = apm_config;
1973}
1974
1975void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1976 const float* const* src) {
1977 RTC_DCHECK(aec_dump_);
1978 WriteAecDumpConfigMessage(false);
1979
1980 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1981 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1982 aec_dump_->AddCaptureStreamInput(
1983 FloatAudioFrame(src, num_channels, channel_size));
1984 RecordAudioProcessingState();
1985}
1986
1987void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1988 const AudioFrame& capture_frame) {
1989 RTC_DCHECK(aec_dump_);
1990 WriteAecDumpConfigMessage(false);
1991
1992 aec_dump_->AddCaptureStreamInput(capture_frame);
1993 RecordAudioProcessingState();
1994}
1995
1996void AudioProcessingImpl::RecordProcessedCaptureStream(
1997 const float* const* processed_capture_stream) {
1998 RTC_DCHECK(aec_dump_);
1999
2000 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2001 const size_t num_channels =
2002 formats_.api_format.output_stream().num_channels();
2003 aec_dump_->AddCaptureStreamOutput(
2004 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
2005 aec_dump_->WriteCaptureStreamMessage();
2006}
2007
2008void AudioProcessingImpl::RecordProcessedCaptureStream(
2009 const AudioFrame& processed_capture_frame) {
2010 RTC_DCHECK(aec_dump_);
2011
2012 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2013 aec_dump_->WriteCaptureStreamMessage();
2014}
2015
2016void AudioProcessingImpl::RecordAudioProcessingState() {
2017 RTC_DCHECK(aec_dump_);
2018 AecDump::AudioProcessingState audio_proc_state;
2019 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2020 audio_proc_state.drift =
2021 public_submodules_->echo_cancellation->stream_drift_samples();
2022 audio_proc_state.level = gain_control()->stream_analog_level();
2023 audio_proc_state.keypress = capture_.key_pressed;
2024 aec_dump_->AddAudioProcessingState(audio_proc_state);
2025}
2026
kwiberg83ffe452016-08-29 14:46:07 -07002027AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2028 bool transient_suppressor_enabled,
2029 const std::vector<Point>& array_geometry,
2030 SphericalPointf target_direction)
2031 : aec_system_delay_jumps(-1),
2032 delay_offset_ms(0),
2033 was_stream_delay_set(false),
2034 last_stream_delay_ms(0),
2035 last_aec_system_delay_ms(0),
2036 stream_delay_jumps(-1),
2037 output_will_be_muted(false),
2038 key_pressed(false),
2039 transient_suppressor_enabled(transient_suppressor_enabled),
2040 array_geometry(array_geometry),
2041 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002042 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002043 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002044 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002045
2046AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2047
2048AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2049
2050AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2051
niklase@google.com470e71d2011-07-07 08:21:25 +00002052} // namespace webrtc