blob: e82223fe823351d4b794206e5571befb963746cb [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(
175 bool capture_post_processor_enabled)
176 : capture_post_processor_enabled_(capture_post_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700177
178bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800179 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700180 bool echo_canceller_enabled,
181 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700182 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700183 bool noise_suppressor_enabled,
184 bool intelligibility_enhancer_enabled,
185 bool beamformer_enabled,
186 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700187 bool gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -0700188 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800189 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700190 bool voice_activity_detector_enabled,
191 bool level_estimator_enabled,
192 bool transient_suppressor_enabled) {
193 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800194 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700195 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
196 changed |=
197 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700198 changed |=
199 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700200 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
201 changed |=
202 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
203 changed |= (beamformer_enabled != beamformer_enabled_);
204 changed |=
205 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700206 changed |=
207 (gain_controller2_enabled != gain_controller2_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700208 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800209 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700210 changed |= (level_estimator_enabled != level_estimator_enabled_);
211 changed |=
212 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
213 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
214 if (changed) {
peah8271d042016-11-22 07:24:52 -0800215 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700216 echo_canceller_enabled_ = echo_canceller_enabled;
217 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700218 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700219 noise_suppressor_enabled_ = noise_suppressor_enabled;
220 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
221 beamformer_enabled_ = beamformer_enabled;
222 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700223 gain_controller2_enabled_ = gain_controller2_enabled;
peah2ace3f92016-09-10 04:42:27 -0700224 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800225 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700226 level_estimator_enabled_ = level_estimator_enabled;
227 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
228 transient_suppressor_enabled_ = transient_suppressor_enabled;
229 }
230
231 changed |= first_update_;
232 first_update_ = false;
233 return changed;
234}
235
236bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
237 const {
238#if WEBRTC_INTELLIGIBILITY_ENHANCER
239 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700240 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700241#else
peah52775842017-05-16 06:14:09 -0700242 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700243#endif
244}
245
246bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
247 const {
peah8271d042016-11-22 07:24:52 -0800248 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700249 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800250 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
251 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700252}
253
peah23ac8b42017-05-23 05:33:56 -0700254bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
255 const {
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200256 return level_controller_enabled_ || gain_controller2_enabled_ ||
257 capture_post_processor_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700258}
259
peah2ace3f92016-09-10 04:42:27 -0700260bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
261 const {
262 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800263 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peah52775842017-05-16 06:14:09 -0700264 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700265}
266
267bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
268 const {
269#if WEBRTC_INTELLIGIBILITY_ENHANCER
270 return intelligibility_enhancer_enabled_;
271#else
272 return false;
273#endif
274}
275
solenberg5e465c32015-12-08 13:22:33 -0800276struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800277 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800278 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800279 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800280 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800281 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800282 std::unique_ptr<LevelEstimatorImpl> level_estimator;
283 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
284 std::unique_ptr<VoiceDetectionImpl> voice_detection;
285 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800286 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800287
288 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800289 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700290#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800291 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700292#endif
solenberg5e465c32015-12-08 13:22:33 -0800293};
294
295struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200296 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
297 std::unique_ptr<PostProcessing> capture_post_processor)
298 : beamformer(beamformer),
299 capture_post_processor(std::move(capture_post_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800300 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700301 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800302 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700303 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800304 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700305 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700306 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200307 std::unique_ptr<EchoControl> echo_controller;
Sam Zackrisson0beac582017-09-25 12:04:02 +0200308 std::unique_ptr<PostProcessing> capture_post_processor;
solenberg5e465c32015-12-08 13:22:33 -0800309};
310
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000311AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700312 webrtc::Config config;
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200313 return Create(config, nullptr, nullptr, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000314}
315
peah88ac8532016-09-12 16:47:25 -0700316AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200317 return Create(config, nullptr, nullptr, nullptr);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000318}
319
peah88ac8532016-09-12 16:47:25 -0700320AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700321 NonlinearBeamformer* beamformer) {
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200322 return Create(config, nullptr, nullptr, beamformer);
Sam Zackrisson0beac582017-09-25 12:04:02 +0200323}
324
325AudioProcessing* AudioProcessing::Create(
326 const webrtc::Config& config,
327 std::unique_ptr<PostProcessing> capture_post_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200328 std::unique_ptr<EchoControlFactory> echo_control_factory,
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200329 NonlinearBeamformer* beamformer) {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200330 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200331 config, std::move(capture_post_processor),
332 std::move(echo_control_factory), beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000333 if (apm->Initialize() != kNoError) {
334 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800335 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000336 }
337
338 return apm;
339}
340
peah88ac8532016-09-12 16:47:25 -0700341AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200342 : AudioProcessingImpl(config, nullptr, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000343
Sam Zackrisson0beac582017-09-25 12:04:02 +0200344AudioProcessingImpl::AudioProcessingImpl(
345 const webrtc::Config& config,
346 std::unique_ptr<PostProcessing> capture_post_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200347 std::unique_ptr<EchoControlFactory> echo_control_factory,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200348 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800349 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200350 echo_control_factory_(std::move(echo_control_factory)),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200351 submodule_states_(!!capture_post_processor),
peah8271d042016-11-22 07:24:52 -0800352 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200353 private_submodules_(
354 new ApmPrivateSubmodules(beamformer,
355 std::move(capture_post_processor))),
peahdf3efa82015-11-28 12:35:15 -0800356 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800357 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000358#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700359 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000360#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700361 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000362#endif
andrew1c7075f2015-06-24 18:14:14 -0700363#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800364 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700365#else
aluebs2a346882016-01-11 18:04:30 -0800366 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700367#endif
aluebs2a346882016-01-11 18:04:30 -0800368 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800369 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700370 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700371 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800372 {
373 rtc::CritScope cs_render(&crit_render_);
374 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000375
peahb624d8c2016-03-05 03:01:14 -0800376 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700377 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800378 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700379 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800380 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700381 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800382 public_submodules_->level_estimator.reset(
383 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800384 public_submodules_->noise_suppression.reset(
385 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800386 public_submodules_->voice_detection.reset(
387 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800388 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800389 new GainControlForExperimentalAgc(
390 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700391 private_submodules_->residual_echo_detector.reset(
392 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700393
peahc19f3122016-10-07 14:54:10 -0700394 // TODO(peah): Move this creation to happen only when the level controller
395 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700396 private_submodules_->level_controller.reset(new LevelController());
Sam Zackrisson0beac582017-09-25 12:04:02 +0200397
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200398 // TODO(alessiob): Move the injected gain controller once injection is
399 // implemented.
400 private_submodules_->gain_controller2.reset(new GainController2());
401
Sam Zackrisson0beac582017-09-25 12:04:02 +0200402 LOG(LS_INFO) << "Capture post processor activated: "
403 << !!private_submodules_->capture_post_processor;
peahdf3efa82015-11-28 12:35:15 -0800404 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000405
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000406 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000407}
408
409AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800410 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800411 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800412 private_submodules_->agc_manager.reset();
413 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800414 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000415}
416
niklase@google.com470e71d2011-07-07 08:21:25 +0000417int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800418 // Run in a single-threaded manner during initialization.
419 rtc::CritScope cs_render(&crit_render_);
420 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000421 return InitializeLocked();
422}
423
peahde65ddc2016-09-16 15:02:15 -0700424int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
425 int capture_output_sample_rate_hz,
426 int render_input_sample_rate_hz,
427 ChannelLayout capture_input_layout,
428 ChannelLayout capture_output_layout,
429 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700430 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700431 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
432 LayoutHasKeyboard(capture_input_layout)},
433 {capture_output_sample_rate_hz,
434 ChannelsFromLayout(capture_output_layout),
435 LayoutHasKeyboard(capture_output_layout)},
436 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
437 LayoutHasKeyboard(render_input_layout)},
438 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
439 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700440
441 return Initialize(processing_config);
442}
443
444int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800445 // Run in a single-threaded manner during initialization.
446 rtc::CritScope cs_render(&crit_render_);
447 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700448 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000449}
450
peahdf3efa82015-11-28 12:35:15 -0800451int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800452 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700453 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800454}
455
peahdf3efa82015-11-28 12:35:15 -0800456int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700457 const ProcessingConfig& processing_config,
458 bool force_initialization) {
459 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800460}
461
peah192164e2015-11-17 02:16:45 -0800462// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800463// their current values (needs to be called while holding the crit_render_lock).
464int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700465 const ProcessingConfig& processing_config,
466 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800467 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700468 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800469 return kNoError;
470 }
peahdf3efa82015-11-28 12:35:15 -0800471
472 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800473 return InitializeLocked(processing_config);
474}
475
niklase@google.com470e71d2011-07-07 08:21:25 +0000476int AudioProcessingImpl::InitializeLocked() {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200477 UpdateActiveSubmoduleStates();
478
peah522d71b2017-02-23 05:16:26 -0800479 const int capture_audiobuffer_num_channels =
480 capture_nonlocked_.beamformer_enabled
481 ? formats_.api_format.input_stream().num_channels()
482 : formats_.api_format.output_stream().num_channels();
483
peahde65ddc2016-09-16 15:02:15 -0700484 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800485 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700486 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800487 : formats_.api_format.reverse_output_stream().num_frames();
488 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
489 render_.render_audio.reset(new AudioBuffer(
490 formats_.api_format.reverse_input_stream().num_frames(),
491 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700492 formats_.render_processing_format.num_frames(),
493 formats_.render_processing_format.num_channels(),
494 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700495 if (formats_.api_format.reverse_input_stream() !=
496 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800497 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800498 formats_.api_format.reverse_input_stream().num_channels(),
499 formats_.api_format.reverse_input_stream().num_frames(),
500 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800501 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700502 } else {
peahdf3efa82015-11-28 12:35:15 -0800503 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700504 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700505 } else {
peahdf3efa82015-11-28 12:35:15 -0800506 render_.render_audio.reset(nullptr);
507 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700508 }
peahce4d9152017-05-19 01:28:05 -0700509
peahdf3efa82015-11-28 12:35:15 -0800510 capture_.capture_audio.reset(
511 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
512 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700513 capture_nonlocked_.capture_processing_format.num_frames(),
514 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800515 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000516
peahde65ddc2016-09-16 15:02:15 -0700517 public_submodules_->echo_cancellation->Initialize(
518 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
519 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700520 AllocateRenderQueue();
521
ivoc3e9a5372016-10-28 07:55:33 -0700522 int success = public_submodules_->echo_cancellation->enable_metrics(true);
523 RTC_DCHECK_EQ(0, success);
524 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
525 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700526 public_submodules_->echo_control_mobile->Initialize(
527 proc_split_sample_rate_hz(), num_reverse_channels(),
528 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700529
530 public_submodules_->gain_control->Initialize(num_proc_channels(),
531 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700532 if (constants_.use_experimental_agc) {
533 if (!private_submodules_->agc_manager.get()) {
534 private_submodules_->agc_manager.reset(new AgcManagerDirect(
535 public_submodules_->gain_control.get(),
536 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800537 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700538 }
539 private_submodules_->agc_manager->Initialize();
540 private_submodules_->agc_manager->SetCaptureMuted(
541 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700542 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700543 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200544 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000545 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700546#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700547 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700548#endif
peah8271d042016-11-22 07:24:52 -0800549 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700550 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
551 proc_sample_rate_hz());
552 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
553 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700554 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700555 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200556 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700557 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200558 InitializePostProcessor();
solenberg70f99032015-12-08 11:07:32 -0800559
aleloi868f32f2017-05-23 07:20:05 -0700560 if (aec_dump_) {
561 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
562 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000563 return kNoError;
564}
565
Michael Graczyk86c6d332015-07-23 11:41:39 -0700566int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200567 UpdateActiveSubmoduleStates();
568
Michael Graczyk86c6d332015-07-23 11:41:39 -0700569 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700570 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
571 return kBadSampleRateError;
572 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000573 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700574
Peter Kasting69558702016-01-12 16:26:35 -0800575 const size_t num_in_channels = config.input_stream().num_channels();
576 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700577
578 // Need at least one input channel.
579 // Need either one output channel or as many outputs as there are inputs.
580 if (num_in_channels == 0 ||
581 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700582 return kBadNumberChannelsError;
583 }
584
aluebsb2328d12016-01-11 20:32:29 -0800585 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800586 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700587 return kBadNumberChannelsError;
588 }
589
peahdf3efa82015-11-28 12:35:15 -0800590 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000591
peahde65ddc2016-09-16 15:02:15 -0700592 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700593 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700594 formats_.api_format.output_stream().sample_rate_hz()),
595 submodule_states_.CaptureMultiBandSubModulesActive() ||
596 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000597
peahde65ddc2016-09-16 15:02:15 -0700598 capture_nonlocked_.capture_processing_format =
599 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700600
peah2ce640f2017-04-07 03:57:48 -0700601 int render_processing_rate;
602 if (!config_.echo_canceller3.enabled) {
603 render_processing_rate = FindNativeProcessRateToUse(
604 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
605 formats_.api_format.reverse_output_stream().sample_rate_hz()),
606 submodule_states_.CaptureMultiBandSubModulesActive() ||
607 submodule_states_.RenderMultiBandSubModulesActive());
608 } else {
609 render_processing_rate = capture_processing_rate;
610 }
611
aluebseb3603b2016-04-20 15:27:58 -0700612 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
613 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700614 if (render_processing_rate > kSampleRate32kHz &&
615 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700616 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
617 ? kSampleRate32kHz
618 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700619 }
peah2ce640f2017-04-07 03:57:48 -0700620
peahde65ddc2016-09-16 15:02:15 -0700621 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700622 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700623 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
624 kSampleRate8kHz) {
625 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000626 } else {
peahde65ddc2016-09-16 15:02:15 -0700627 render_processing_rate =
628 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000629 }
630
peahde65ddc2016-09-16 15:02:15 -0700631 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000632 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700633 if (submodule_states_.RenderMultiBandSubModulesActive()) {
634 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
635 } else {
636 formats_.render_processing_format = StreamConfig(
637 formats_.api_format.reverse_input_stream().sample_rate_hz(),
638 formats_.api_format.reverse_input_stream().num_channels());
639 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000640
peahde65ddc2016-09-16 15:02:15 -0700641 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
642 kSampleRate32kHz ||
643 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
644 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800645 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000646 } else {
peahdf3efa82015-11-28 12:35:15 -0800647 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700648 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000649 }
650
651 return InitializeLocked();
652}
653
peah88ac8532016-09-12 16:47:25 -0700654void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700655 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700656
peahc19f3122016-10-07 14:54:10 -0700657 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700658 if (!config_ok) {
659 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
660 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700661 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700662 << std::endl
663 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700664 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700665 }
666
667 // Run in a single-threaded manner when applying the settings.
668 rtc::CritScope cs_render(&crit_render_);
669 rtc::CritScope cs_capture(&crit_capture_);
670
peahc19f3122016-10-07 14:54:10 -0700671 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
672 // with the value in config_ everywhere in the code.
673 if (capture_nonlocked_.level_controller_enabled !=
674 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700675 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700676 config_.level_controller.enabled;
677 // TODO(peah): Remove the conditional initialization to always initialize
678 // the level controller regardless of whether it is enabled or not.
679 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700680 }
peahc19f3122016-10-07 14:54:10 -0700681 LOG(LS_INFO) << "Level controller activated: "
682 << capture_nonlocked_.level_controller_enabled;
683
684 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800685
686 InitializeLowCutFilter();
687
688 LOG(LS_INFO) << "Highpass filter activated: "
689 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800690
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200691 // Inject EchoCanceller3 if requested.
692 if (config.echo_canceller3.enabled && !echo_control_factory_) {
peahe0eae3c2016-12-14 01:16:23 -0800693 capture_nonlocked_.echo_canceller3_enabled =
694 config_.echo_canceller3.enabled;
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200695 echo_control_factory_ = std::unique_ptr<EchoControlFactory>(
696 new EchoCanceller3Factory(config.echo_canceller3));
697 InitializeEchoController();
peahe0eae3c2016-12-14 01:16:23 -0800698 LOG(LS_INFO) << "Echo canceller 3 activated: "
699 << capture_nonlocked_.echo_canceller3_enabled;
700 }
alessiob3ec96df2017-05-22 06:57:06 -0700701
702 config_ok = GainController2::Validate(config_.gain_controller2);
703 if (!config_ok) {
704 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200705 << "Gain Controller 2: "
alessiob3ec96df2017-05-22 06:57:06 -0700706 << GainController2::ToString(config_.gain_controller2)
707 << std::endl
708 << "Reverting to default parameter set";
709 config_.gain_controller2 = AudioProcessing::Config::GainController2();
710 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200711 InitializeGainController2();
712 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
713 LOG(LS_INFO) << "Gain Controller 2 activated: "
714 << config_.gain_controller2.enabled;
peah88ac8532016-09-12 16:47:25 -0700715}
716
717void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800718 // Run in a single-threaded manner when setting the extra options.
719 rtc::CritScope cs_render(&crit_render_);
720 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000721
peahb624d8c2016-03-05 03:01:14 -0800722 public_submodules_->echo_cancellation->SetExtraOptions(config);
723
peahdf3efa82015-11-28 12:35:15 -0800724 if (capture_.transient_suppressor_enabled !=
725 config.Get<ExperimentalNs>().enabled) {
726 capture_.transient_suppressor_enabled =
727 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000728 InitializeTransient();
729 }
aluebs2a346882016-01-11 18:04:30 -0800730
peah1bcfce52016-08-26 07:16:04 -0700731#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700732 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700733 config.Get<Intelligibility>().enabled) {
734 capture_nonlocked_.intelligibility_enabled =
735 config.Get<Intelligibility>().enabled;
736 InitializeIntelligibility();
737 }
peah1bcfce52016-08-26 07:16:04 -0700738#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700739
aluebs2a346882016-01-11 18:04:30 -0800740#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800741 if (capture_nonlocked_.beamformer_enabled !=
742 config.Get<Beamforming>().enabled) {
743 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800744 if (config.Get<Beamforming>().array_geometry.size() > 1) {
745 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
746 }
747 capture_.target_direction = config.Get<Beamforming>().target_direction;
748 InitializeBeamformer();
749 }
750#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000751}
752
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000753int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800754 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700755 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000756}
757
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000758int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800759 // Used as callback from submodules, hence locking is not allowed.
760 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000761}
762
Peter Kasting69558702016-01-12 16:26:35 -0800763size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800764 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700765 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000766}
767
Peter Kasting69558702016-01-12 16:26:35 -0800768size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800769 // Used as callback from submodules, hence locking is not allowed.
770 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000771}
772
Peter Kasting69558702016-01-12 16:26:35 -0800773size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800774 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700775 return (capture_nonlocked_.beamformer_enabled ||
776 capture_nonlocked_.echo_canceller3_enabled)
777 ? 1
778 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800779}
780
Peter Kasting69558702016-01-12 16:26:35 -0800781size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800782 // Used as callback from submodules, hence locking is not allowed.
783 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000784}
785
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000786void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800787 rtc::CritScope cs(&crit_capture_);
788 capture_.output_will_be_muted = muted;
789 if (private_submodules_->agc_manager.get()) {
790 private_submodules_->agc_manager->SetCaptureMuted(
791 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000792 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000793}
794
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000795
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000796int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700797 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000798 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000799 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000800 int output_sample_rate_hz,
801 ChannelLayout output_layout,
802 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800803 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800804 StreamConfig input_stream;
805 StreamConfig output_stream;
806 {
807 // Access the formats_.api_format.input_stream beneath the capture lock.
808 // The lock must be released as it is later required in the call
809 // to ProcessStream(,,,);
810 rtc::CritScope cs(&crit_capture_);
811 input_stream = formats_.api_format.input_stream();
812 output_stream = formats_.api_format.output_stream();
813 }
814
Michael Graczyk86c6d332015-07-23 11:41:39 -0700815 input_stream.set_sample_rate_hz(input_sample_rate_hz);
816 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
817 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700818 output_stream.set_sample_rate_hz(output_sample_rate_hz);
819 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
820 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
821
822 if (samples_per_channel != input_stream.num_frames()) {
823 return kBadDataLengthError;
824 }
825 return ProcessStream(src, input_stream, output_stream, dest);
826}
827
828int AudioProcessingImpl::ProcessStream(const float* const* src,
829 const StreamConfig& input_config,
830 const StreamConfig& output_config,
831 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800832 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800833 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700834 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800835 {
836 // Acquire the capture lock in order to safely call the function
837 // that retrieves the render side data. This function accesses apm
838 // getters that need the capture lock held when being called.
839 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700840 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800841
842 if (!src || !dest) {
843 return kNullPointerError;
844 }
845
846 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700847 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000848 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000849
Michael Graczyk86c6d332015-07-23 11:41:39 -0700850 processing_config.input_stream() = input_config;
851 processing_config.output_stream() = output_config;
852
peahdf3efa82015-11-28 12:35:15 -0800853 {
854 // Do conditional reinitialization.
855 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700856 RETURN_ON_ERR(
857 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800858 }
859 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700860 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
861 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000862
aleloi868f32f2017-05-23 07:20:05 -0700863 if (aec_dump_) {
864 RecordUnprocessedCaptureStream(src);
865 }
866
peahdf3efa82015-11-28 12:35:15 -0800867 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700868 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800869 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000870
aleloi868f32f2017-05-23 07:20:05 -0700871 if (aec_dump_) {
872 RecordProcessedCaptureStream(dest);
873 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000874 return kNoError;
875}
876
peah9e6a2902017-05-15 07:19:21 -0700877void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700878 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
879 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700880 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700881
kwibergaf476c72016-11-28 15:21:39 -0800882 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700883
884 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700885 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700886 // The data queue is full and needs to be emptied.
887 EmptyQueuedRenderAudio();
888
889 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700890 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700891 RTC_DCHECK(result);
892 }
893
894 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
895 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700896 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700897
898 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700899 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700900 // The data queue is full and needs to be emptied.
901 EmptyQueuedRenderAudio();
902
903 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700904 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700905 RTC_DCHECK(result);
906 }
peah701d6282016-10-25 05:42:20 -0700907
908 if (!constants_.use_experimental_agc) {
909 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
910 // Insert the samples into the queue.
911 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
912 // The data queue is full and needs to be emptied.
913 EmptyQueuedRenderAudio();
914
915 // Retry the insert (should always work).
916 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
917 RTC_DCHECK(result);
918 }
919 }
peah9e6a2902017-05-15 07:19:21 -0700920}
ivoc9f4a4a02016-10-28 05:39:16 -0700921
peah9e6a2902017-05-15 07:19:21 -0700922void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700923 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
924
925 // Insert the samples into the queue.
926 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
927 // The data queue is full and needs to be emptied.
928 EmptyQueuedRenderAudio();
929
930 // Retry the insert (should always work).
931 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
932 RTC_DCHECK(result);
933 }
peah764e3642016-10-22 05:04:30 -0700934}
935
936void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700937 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700938 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700939 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700940 EchoCancellationImpl::NumCancellersRequired(
941 num_output_channels(), num_reverse_channels()));
942
peah701d6282016-10-25 05:42:20 -0700943 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700944 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700945 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700946 EchoControlMobileImpl::NumCancellersRequired(
947 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700948
peah701d6282016-10-25 05:42:20 -0700949 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700950 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700951
ivoc9f4a4a02016-10-28 05:39:16 -0700952 const size_t new_red_render_queue_element_max_size =
953 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
954
peaha0624602016-10-25 04:45:24 -0700955 // Reallocate the queues if the queue item sizes are too small to fit the
956 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700957 if (aec_render_queue_element_max_size_ <
958 new_aec_render_queue_element_max_size) {
959 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700960
peaha0624602016-10-25 04:45:24 -0700961 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700962 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700963
peah701d6282016-10-25 05:42:20 -0700964 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700965 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
966 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700967 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700968 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700969
peah701d6282016-10-25 05:42:20 -0700970 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
971 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700972 } else {
peah701d6282016-10-25 05:42:20 -0700973 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700974 }
975
peah701d6282016-10-25 05:42:20 -0700976 if (aecm_render_queue_element_max_size_ <
977 new_aecm_render_queue_element_max_size) {
978 aecm_render_queue_element_max_size_ =
979 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700980
981 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700982 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700983
peah701d6282016-10-25 05:42:20 -0700984 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700985 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
986 kMaxNumFramesToBuffer, template_queue_element,
987 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700988 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700989
peah701d6282016-10-25 05:42:20 -0700990 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
991 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700992 } else {
peah701d6282016-10-25 05:42:20 -0700993 aecm_render_signal_queue_->Clear();
994 }
995
996 if (agc_render_queue_element_max_size_ <
997 new_agc_render_queue_element_max_size) {
998 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
999
1000 std::vector<int16_t> template_queue_element(
1001 agc_render_queue_element_max_size_);
1002
1003 agc_render_signal_queue_.reset(
1004 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1005 kMaxNumFramesToBuffer, template_queue_element,
1006 RenderQueueItemVerifier<int16_t>(
1007 agc_render_queue_element_max_size_)));
1008
1009 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1010 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1011 } else {
1012 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001013 }
ivoc9f4a4a02016-10-28 05:39:16 -07001014
1015 if (red_render_queue_element_max_size_ <
1016 new_red_render_queue_element_max_size) {
1017 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1018
1019 std::vector<float> template_queue_element(
1020 red_render_queue_element_max_size_);
1021
1022 red_render_signal_queue_.reset(
1023 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1024 kMaxNumFramesToBuffer, template_queue_element,
1025 RenderQueueItemVerifier<float>(
1026 red_render_queue_element_max_size_)));
1027
1028 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1029 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1030 } else {
1031 red_render_signal_queue_->Clear();
1032 }
peah764e3642016-10-22 05:04:30 -07001033}
1034
1035void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1036 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001037 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001038 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001039 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001040 }
1041
peah701d6282016-10-25 05:42:20 -07001042 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001043 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001044 aecm_capture_queue_buffer_);
1045 }
1046
1047 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1048 public_submodules_->gain_control->ProcessRenderAudio(
1049 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001050 }
ivoc9f4a4a02016-10-28 05:39:16 -07001051
1052 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1053 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1054 red_capture_queue_buffer_);
1055 }
peah764e3642016-10-22 05:04:30 -07001056}
1057
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001058int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001059 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001060 {
1061 // Acquire the capture lock in order to safely call the function
1062 // that retrieves the render side data. This function accesses apm
1063 // getters that need the capture lock held when being called.
1064 // The lock needs to be released as
1065 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1066 // as well.
1067 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001068 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001069 }
peahfa6228e2015-11-16 16:27:42 -08001070
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001071 if (!frame) {
1072 return kNullPointerError;
1073 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001074 // Must be a native rate.
1075 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1076 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001077 frame->sample_rate_hz_ != kSampleRate32kHz &&
1078 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001079 return kBadSampleRateError;
1080 }
peah192164e2015-11-17 02:16:45 -08001081
peahdf3efa82015-11-28 12:35:15 -08001082 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001083 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001084 {
1085 // Aquire lock for the access of api_format.
1086 // The lock is released immediately due to the conditional
1087 // reinitialization.
1088 rtc::CritScope cs_capture(&crit_capture_);
1089 // TODO(ajm): The input and output rates and channels are currently
1090 // constrained to be identical in the int16 interface.
1091 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001092
1093 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001094 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001095 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1096 processing_config.input_stream().set_num_channels(frame->num_channels_);
1097 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1098 processing_config.output_stream().set_num_channels(frame->num_channels_);
1099
peahdf3efa82015-11-28 12:35:15 -08001100 {
1101 // Do conditional reinitialization.
1102 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001103 RETURN_ON_ERR(
1104 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001105 }
1106 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001107 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001108 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001109 return kBadDataLengthError;
1110 }
1111
aleloi868f32f2017-05-23 07:20:05 -07001112 if (aec_dump_) {
1113 RecordUnprocessedCaptureStream(*frame);
1114 }
1115
peahdf3efa82015-11-28 12:35:15 -08001116 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001117 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001118 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001119 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1120 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001121
aleloi868f32f2017-05-23 07:20:05 -07001122 if (aec_dump_) {
1123 RecordProcessedCaptureStream(*frame);
1124 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001125
1126 return kNoError;
1127}
1128
peahde65ddc2016-09-16 15:02:15 -07001129int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001130 // Ensure that not both the AEC and AECM are active at the same time.
1131 // TODO(peah): Simplify once the public API Enable functions for these
1132 // are moved to APM.
1133 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1134 public_submodules_->echo_control_mobile->is_enabled()));
1135
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001136 MaybeUpdateHistograms();
1137
peahde65ddc2016-09-16 15:02:15 -07001138 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001139
peah1b08dc32016-12-20 13:45:58 -08001140 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001141 capture_buffer->channels_const()[0],
1142 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001143 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1144 if (log_rms) {
1145 capture_rms_interval_counter_ = 0;
1146 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001147 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1148 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1149 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1150 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001151 }
1152
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001153 if (private_submodules_->echo_controller) {
Per Ã…hgren9aed31c2017-06-29 20:23:27 +02001154 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1155 // issues have been addressed.
1156 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001157 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001158 }
1159
peahbe615622016-02-13 16:40:47 -08001160 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001161 public_submodules_->gain_control->is_enabled()) {
1162 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001163 capture_buffer->channels()[0], capture_buffer->num_channels(),
1164 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001165 }
1166
peah2ace3f92016-09-10 04:42:27 -07001167 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1168 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001169 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1170 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001171 }
1172
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001173 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001174 // Force down-mixing of the number of channels after the detection of
1175 // capture signal saturation.
1176 // TODO(peah): Look into ensuring that this kind of tampering with the
1177 // AudioBuffer functionality should not be needed.
1178 capture_buffer->set_num_channels(1);
1179 }
1180
aluebsb2328d12016-01-11 20:32:29 -08001181 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001182 private_submodules_->beamformer->AnalyzeChunk(
1183 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001184 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001185 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001186 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001187
peahe0eae3c2016-12-14 01:16:23 -08001188 // TODO(peah): Move the AEC3 low-cut filter to this place.
1189 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001190 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001191 private_submodules_->low_cut_filter->Process(capture_buffer);
1192 }
peahde65ddc2016-09-16 15:02:15 -07001193 RETURN_ON_ERR(
1194 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1195 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001196
1197 // Ensure that the stream delay was set before the call to the
1198 // AEC ProcessCaptureAudio function.
1199 if (public_submodules_->echo_cancellation->is_enabled() &&
1200 !was_stream_delay_set()) {
1201 return AudioProcessing::kStreamParameterNotSetError;
1202 }
1203
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001204 if (private_submodules_->echo_controller) {
1205 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001206 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001207 } else {
1208 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1209 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001210 }
1211
peahdf3efa82015-11-28 12:35:15 -08001212 if (public_submodules_->echo_control_mobile->is_enabled() &&
1213 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001214 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001215 }
peahde65ddc2016-09-16 15:02:15 -07001216 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001217#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001218 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001219 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001220 int gain_db = public_submodules_->gain_control->is_enabled() ?
1221 public_submodules_->gain_control->compression_gain_db() :
1222 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001223 float gain = std::pow(10.f, gain_db / 20.f);
1224 gain *= capture_nonlocked_.level_controller_enabled ?
1225 private_submodules_->level_controller->GetLastGain() :
1226 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001227 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001228 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001229 }
peah1bcfce52016-08-26 07:16:04 -07001230#endif
peah253534d2016-03-15 04:32:28 -07001231
1232 // Ensure that the stream delay was set before the call to the
1233 // AECM ProcessCaptureAudio function.
1234 if (public_submodules_->echo_control_mobile->is_enabled() &&
1235 !was_stream_delay_set()) {
1236 return AudioProcessing::kStreamParameterNotSetError;
1237 }
1238
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001239 if (!(private_submodules_->echo_controller ||
Per Ã…hgren46537a32017-06-07 10:08:10 +02001240 public_submodules_->echo_cancellation->is_enabled())) {
1241 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1242 capture_buffer, stream_delay_ms()));
1243 }
ivoc9f4a4a02016-10-28 05:39:16 -07001244
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001245 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001246 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001247 }
1248
peahde65ddc2016-09-16 15:02:15 -07001249 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001250
peahbe615622016-02-13 16:40:47 -08001251 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001252 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001253 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001254 private_submodules_->beamformer->is_target_present())) {
1255 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001256 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1257 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001258 }
peahb8fbb542016-03-15 02:28:08 -07001259 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001260 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001261
peah2ace3f92016-09-10 04:42:27 -07001262 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1263 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001264 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1265 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001266 }
1267
peah9e6a2902017-05-15 07:19:21 -07001268 if (config_.residual_echo_detector.enabled) {
1269 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1270 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1271 capture_buffer->num_frames()));
1272 }
1273
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001274 // TODO(aluebs): Investigate if the transient suppression placement should be
1275 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001276 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001277 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001278 private_submodules_->agc_manager.get()
1279 ? private_submodules_->agc_manager->voice_probability()
1280 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001281
peahdf3efa82015-11-28 12:35:15 -08001282 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001283 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1284 capture_buffer->num_channels(),
1285 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1286 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1287 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001288 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001289 }
1290
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001291 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001292 private_submodules_->gain_controller2->Process(capture_buffer);
1293 }
1294
peahca4cac72016-06-29 15:26:12 -07001295 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001296 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001297 }
1298
Sam Zackrisson0beac582017-09-25 12:04:02 +02001299 if (private_submodules_->capture_post_processor) {
1300 private_submodules_->capture_post_processor->Process(capture_buffer);
1301 }
1302
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001303 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001304 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001305
peah1b08dc32016-12-20 13:45:58 -08001306 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1307 capture_buffer->channels_const()[0],
1308 capture_nonlocked_.capture_processing_format.num_frames()));
1309 if (log_rms) {
1310 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1311 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1312 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1313 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1314 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1315 }
1316
peahdf3efa82015-11-28 12:35:15 -08001317 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001318 return kNoError;
1319}
1320
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001321int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001322 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001323 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001324 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001325 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001326 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001327 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001328 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001329 };
1330 if (samples_per_channel != reverse_config.num_frames()) {
1331 return kBadDataLengthError;
1332 }
peahdf3efa82015-11-28 12:35:15 -08001333 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001334}
1335
peahde65ddc2016-09-16 15:02:15 -07001336int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1337 const StreamConfig& input_config,
1338 const StreamConfig& output_config,
1339 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001340 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001341 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001342 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001343 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001344 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1345 dest);
peah2ace3f92016-09-10 04:42:27 -07001346 } else if (formats_.api_format.reverse_input_stream() !=
1347 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001348 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1349 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001350 } else {
peahde65ddc2016-09-16 15:02:15 -07001351 CopyAudioIfNeeded(src, input_config.num_frames(),
1352 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001353 }
1354
1355 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001356}
1357
peahdf3efa82015-11-28 12:35:15 -08001358int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001359 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001360 const StreamConfig& input_config,
1361 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001362 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001363 return kNullPointerError;
1364 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001365
peahde65ddc2016-09-16 15:02:15 -07001366 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001367 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001368 }
1369
peahdf3efa82015-11-28 12:35:15 -08001370 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001371 processing_config.reverse_input_stream() = input_config;
1372 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001373
peahdf3efa82015-11-28 12:35:15 -08001374 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001375 assert(input_config.num_frames() ==
1376 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001377
aleloi868f32f2017-05-23 07:20:05 -07001378 if (aec_dump_) {
1379 const size_t channel_size =
1380 formats_.api_format.reverse_input_stream().num_frames();
1381 const size_t num_channels =
1382 formats_.api_format.reverse_input_stream().num_channels();
1383 aec_dump_->WriteRenderStreamMessage(
1384 FloatAudioFrame(src, num_channels, channel_size));
1385 }
peahdf3efa82015-11-28 12:35:15 -08001386 render_.render_audio->CopyFrom(src,
1387 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001388 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001389}
1390
1391int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001392 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001393 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001394 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001395 return kNullPointerError;
1396 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001397 // Must be a native rate.
1398 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1399 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001400 frame->sample_rate_hz_ != kSampleRate32kHz &&
1401 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001402 return kBadSampleRateError;
1403 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001404
Michael Graczyk86c6d332015-07-23 11:41:39 -07001405 if (frame->num_channels_ <= 0) {
1406 return kBadNumberChannelsError;
1407 }
1408
peahdf3efa82015-11-28 12:35:15 -08001409 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001410 processing_config.reverse_input_stream().set_sample_rate_hz(
1411 frame->sample_rate_hz_);
1412 processing_config.reverse_input_stream().set_num_channels(
1413 frame->num_channels_);
1414 processing_config.reverse_output_stream().set_sample_rate_hz(
1415 frame->sample_rate_hz_);
1416 processing_config.reverse_output_stream().set_num_channels(
1417 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001418
peahdf3efa82015-11-28 12:35:15 -08001419 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001420 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001421 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001422 return kBadDataLengthError;
1423 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001424
aleloi868f32f2017-05-23 07:20:05 -07001425 if (aec_dump_) {
1426 aec_dump_->WriteRenderStreamMessage(*frame);
1427 }
1428
peahdf3efa82015-11-28 12:35:15 -08001429 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001430 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001431 render_.render_audio->InterleaveTo(
1432 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001433 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001434}
niklase@google.com470e71d2011-07-07 08:21:25 +00001435
peahde65ddc2016-09-16 15:02:15 -07001436int AudioProcessingImpl::ProcessRenderStreamLocked() {
1437 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001438
1439 QueueNonbandedRenderAudio(render_buffer);
1440
peah2ace3f92016-09-10 04:42:27 -07001441 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001442 SampleRateSupportsMultiBand(
1443 formats_.render_processing_format.sample_rate_hz())) {
1444 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001445 }
1446
peah1bcfce52016-08-26 07:16:04 -07001447#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001448 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001449 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001450 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001451 }
peah1bcfce52016-08-26 07:16:04 -07001452#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001453
peahce4d9152017-05-19 01:28:05 -07001454 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1455 QueueBandedRenderAudio(render_buffer);
1456 }
1457
peahe0eae3c2016-12-14 01:16:23 -08001458 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001459 if (private_submodules_->echo_controller) {
1460 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001461 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001462
peah2ace3f92016-09-10 04:42:27 -07001463 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001464 SampleRateSupportsMultiBand(
1465 formats_.render_processing_format.sample_rate_hz())) {
1466 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001467 }
1468
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001469 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001470}
1471
1472int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001473 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001474 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001475 capture_.was_stream_delay_set = true;
1476 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001477
niklase@google.com470e71d2011-07-07 08:21:25 +00001478 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001479 delay = 0;
1480 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001481 }
1482
1483 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1484 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001485 delay = 500;
1486 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001487 }
1488
peahdf3efa82015-11-28 12:35:15 -08001489 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001490 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001491}
1492
1493int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001494 // Used as callback from submodules, hence locking is not allowed.
1495 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001496}
1497
1498bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001499 // Used as callback from submodules, hence locking is not allowed.
1500 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001501}
1502
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001503void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001504 rtc::CritScope cs(&crit_capture_);
1505 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001506}
1507
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001508void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001509 rtc::CritScope cs(&crit_capture_);
1510 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001511}
1512
1513int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001514 rtc::CritScope cs(&crit_capture_);
1515 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001516}
1517
aleloi868f32f2017-05-23 07:20:05 -07001518void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1519 RTC_DCHECK(aec_dump);
1520 rtc::CritScope cs_render(&crit_render_);
1521 rtc::CritScope cs_capture(&crit_capture_);
1522
1523 // The previously attached AecDump will be destroyed with the
1524 // 'aec_dump' parameter, which is after locks are released.
1525 aec_dump_.swap(aec_dump);
1526 WriteAecDumpConfigMessage(true);
1527 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1528}
1529
1530void AudioProcessingImpl::DetachAecDump() {
1531 // The d-tor of a task-queue based AecDump blocks until all pending
1532 // tasks are done. This construction avoids blocking while holding
1533 // the render and capture locks.
1534 std::unique_ptr<AecDump> aec_dump = nullptr;
1535 {
1536 rtc::CritScope cs_render(&crit_render_);
1537 rtc::CritScope cs_capture(&crit_capture_);
1538 aec_dump = std::move(aec_dump_);
1539 }
1540}
1541
ivoc4e477a12017-01-15 08:29:46 -08001542AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1543 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1544 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1545 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1546 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1547}
1548
1549AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1550 const AudioProcessingStatistics& other) = default;
1551
1552AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1553 default;
1554
ivoc3e9a5372016-10-28 07:55:33 -07001555// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1556AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1557 const {
1558 return AudioProcessingStatistics();
1559}
1560
1561AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1562 const {
1563 AudioProcessingStatistics stats;
1564 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001565 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1566 if (success == Error::kNoError) {
1567 stats.a_nlp.Set(metrics.a_nlp);
1568 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1569 stats.echo_return_loss.Set(metrics.echo_return_loss);
1570 stats.echo_return_loss_enhancement.Set(
1571 metrics.echo_return_loss_enhancement);
1572 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1573 }
ivoc9c192b22017-03-16 04:22:14 -07001574 {
1575 rtc::CritScope cs_capture(&crit_capture_);
1576 stats.residual_echo_likelihood =
1577 private_submodules_->residual_echo_detector->echo_likelihood();
1578 stats.residual_echo_likelihood_recent_max =
1579 private_submodules_->residual_echo_detector
1580 ->echo_likelihood_recent_max();
1581 }
ivoc3e9a5372016-10-28 07:55:33 -07001582 public_submodules_->echo_cancellation->GetDelayMetrics(
1583 &stats.delay_median, &stats.delay_standard_deviation,
1584 &stats.fraction_poor_delays);
1585 return stats;
1586}
1587
niklase@google.com470e71d2011-07-07 08:21:25 +00001588EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001589 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001590}
1591
1592EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001593 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001594}
1595
1596GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001597 if (constants_.use_experimental_agc) {
1598 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001599 }
peahbfa97112016-03-10 21:09:04 -08001600 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001601}
1602
1603HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001604 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001605}
1606
1607LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001608 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001609}
1610
1611NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001612 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001613}
1614
1615VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001616 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001617}
1618
peah8271d042016-11-22 07:24:52 -08001619void AudioProcessingImpl::MutateConfig(
1620 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1621 rtc::CritScope cs_render(&crit_render_);
1622 rtc::CritScope cs_capture(&crit_capture_);
1623 mutator(&config_);
1624 ApplyConfig(config_);
1625}
1626
1627AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1628 rtc::CritScope cs_render(&crit_render_);
1629 rtc::CritScope cs_capture(&crit_capture_);
1630 return config_;
1631}
1632
peah2ace3f92016-09-10 04:42:27 -07001633bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1634 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001635 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001636 public_submodules_->echo_cancellation->is_enabled(),
1637 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001638 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001639 public_submodules_->noise_suppression->is_enabled(),
1640 capture_nonlocked_.intelligibility_enabled,
1641 capture_nonlocked_.beamformer_enabled,
1642 public_submodules_->gain_control->is_enabled(),
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001643 config_.gain_controller2.enabled,
peah2ace3f92016-09-10 04:42:27 -07001644 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001645 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001646 public_submodules_->voice_detection->is_enabled(),
1647 public_submodules_->level_estimator->is_enabled(),
1648 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001649}
1650
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001651
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001652void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001653 if (capture_.transient_suppressor_enabled) {
1654 if (!public_submodules_->transient_suppressor.get()) {
1655 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001656 }
peahdf3efa82015-11-28 12:35:15 -08001657 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001658 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1659 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001660 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001661}
1662
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001663void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001664 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001665 if (!private_submodules_->beamformer) {
1666 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001667 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001668 }
peahdf3efa82015-11-28 12:35:15 -08001669 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1670 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001671 }
1672}
1673
ekmeyerson60d9b332015-08-14 10:35:55 -07001674void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001675#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001676 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001677 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001678 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001679 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001680 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001681 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001682 }
peah1bcfce52016-08-26 07:16:04 -07001683#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001684}
1685
peah8271d042016-11-22 07:24:52 -08001686void AudioProcessingImpl::InitializeLowCutFilter() {
1687 if (config_.high_pass_filter.enabled) {
1688 private_submodules_->low_cut_filter.reset(
1689 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1690 } else {
1691 private_submodules_->low_cut_filter.reset();
1692 }
1693}
alessiob3ec96df2017-05-22 06:57:06 -07001694
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001695void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001696 if (echo_control_factory_) {
1697 private_submodules_->echo_controller =
1698 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001699 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001700 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001701 }
1702}
peah8271d042016-11-22 07:24:52 -08001703
alessiob3ec96df2017-05-22 06:57:06 -07001704void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001705 if (config_.gain_controller2.enabled) {
1706 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001707 }
1708}
1709
peahca4cac72016-06-29 15:26:12 -07001710void AudioProcessingImpl::InitializeLevelController() {
1711 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1712}
1713
ivoc9f4a4a02016-10-28 05:39:16 -07001714void AudioProcessingImpl::InitializeResidualEchoDetector() {
1715 private_submodules_->residual_echo_detector->Initialize();
1716}
1717
Sam Zackrisson0beac582017-09-25 12:04:02 +02001718void AudioProcessingImpl::InitializePostProcessor() {
1719 if (private_submodules_->capture_post_processor) {
1720 private_submodules_->capture_post_processor->Initialize(
1721 proc_sample_rate_hz(), num_proc_channels());
1722 }
1723}
1724
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001725void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001726 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001727
1728 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001729 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001730 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001731 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001732 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001733 capture_.stream_delay_jumps = 0;
1734 }
1735 if (capture_.aec_system_delay_jumps == -1 &&
1736 echo_cancellation()->stream_has_echo()) {
1737 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001738 }
1739
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001740 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001741 const int diff_stream_delay_ms =
1742 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1743 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1744 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001745 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1746 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001747 if (capture_.stream_delay_jumps == -1) {
1748 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001749 }
peahdf3efa82015-11-28 12:35:15 -08001750 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001751 }
peahdf3efa82015-11-28 12:35:15 -08001752 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001753
1754 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001755 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001756 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001757 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001758 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001759 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1760 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001761 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001762 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001763 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001764 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001765 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1766 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1767 100);
peahdf3efa82015-11-28 12:35:15 -08001768 if (capture_.aec_system_delay_jumps == -1) {
1769 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001770 }
peahdf3efa82015-11-28 12:35:15 -08001771 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001772 }
peahdf3efa82015-11-28 12:35:15 -08001773 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001774 }
1775}
1776
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001777void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001778 // Run in a single-threaded manner.
1779 rtc::CritScope cs_render(&crit_render_);
1780 rtc::CritScope cs_capture(&crit_capture_);
1781
1782 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001783 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001784 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001785 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001786 }
peahdf3efa82015-11-28 12:35:15 -08001787 capture_.stream_delay_jumps = -1;
1788 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001789
peahdf3efa82015-11-28 12:35:15 -08001790 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001791 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1792 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001793 }
peahdf3efa82015-11-28 12:35:15 -08001794 capture_.aec_system_delay_jumps = -1;
1795 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001796}
1797
aleloi868f32f2017-05-23 07:20:05 -07001798void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1799 if (!aec_dump_) {
1800 return;
1801 }
1802 std::string experiments_description =
1803 public_submodules_->echo_cancellation->GetExperimentsDescription();
1804 // TODO(peah): Add semicolon-separated concatenations of experiment
1805 // descriptions for other submodules.
1806 if (capture_nonlocked_.level_controller_enabled) {
1807 experiments_description += "LevelController;";
1808 }
1809 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1810 experiments_description += "AgcClippingLevelExperiment;";
1811 }
1812 if (capture_nonlocked_.echo_canceller3_enabled) {
1813 experiments_description += "EchoCanceller3;";
1814 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001815 if (config_.gain_controller2.enabled) {
1816 experiments_description += "GainController2;";
1817 }
aleloi868f32f2017-05-23 07:20:05 -07001818
1819 InternalAPMConfig apm_config;
1820
1821 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1822 apm_config.aec_delay_agnostic_enabled =
1823 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1824 apm_config.aec_drift_compensation_enabled =
1825 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1826 apm_config.aec_extended_filter_enabled =
1827 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1828 apm_config.aec_suppression_level = static_cast<int>(
1829 public_submodules_->echo_cancellation->suppression_level());
1830
1831 apm_config.aecm_enabled =
1832 public_submodules_->echo_control_mobile->is_enabled();
1833 apm_config.aecm_comfort_noise_enabled =
1834 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1835 apm_config.aecm_routing_mode =
1836 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1837
1838 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1839 apm_config.agc_mode =
1840 static_cast<int>(public_submodules_->gain_control->mode());
1841 apm_config.agc_limiter_enabled =
1842 public_submodules_->gain_control->is_limiter_enabled();
1843 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1844
1845 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1846
1847 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1848 apm_config.ns_level =
1849 static_cast<int>(public_submodules_->noise_suppression->level());
1850
1851 apm_config.transient_suppression_enabled =
1852 capture_.transient_suppressor_enabled;
1853 apm_config.intelligibility_enhancer_enabled =
1854 capture_nonlocked_.intelligibility_enabled;
1855 apm_config.experiments_description = experiments_description;
1856
1857 if (!forced && apm_config == apm_config_for_aec_dump_) {
1858 return;
1859 }
1860 aec_dump_->WriteConfig(apm_config);
1861 apm_config_for_aec_dump_ = apm_config;
1862}
1863
1864void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1865 const float* const* src) {
1866 RTC_DCHECK(aec_dump_);
1867 WriteAecDumpConfigMessage(false);
1868
1869 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1870 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1871 aec_dump_->AddCaptureStreamInput(
1872 FloatAudioFrame(src, num_channels, channel_size));
1873 RecordAudioProcessingState();
1874}
1875
1876void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1877 const AudioFrame& capture_frame) {
1878 RTC_DCHECK(aec_dump_);
1879 WriteAecDumpConfigMessage(false);
1880
1881 aec_dump_->AddCaptureStreamInput(capture_frame);
1882 RecordAudioProcessingState();
1883}
1884
1885void AudioProcessingImpl::RecordProcessedCaptureStream(
1886 const float* const* processed_capture_stream) {
1887 RTC_DCHECK(aec_dump_);
1888
1889 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1890 const size_t num_channels =
1891 formats_.api_format.output_stream().num_channels();
1892 aec_dump_->AddCaptureStreamOutput(
1893 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
1894 aec_dump_->WriteCaptureStreamMessage();
1895}
1896
1897void AudioProcessingImpl::RecordProcessedCaptureStream(
1898 const AudioFrame& processed_capture_frame) {
1899 RTC_DCHECK(aec_dump_);
1900
1901 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1902 aec_dump_->WriteCaptureStreamMessage();
1903}
1904
1905void AudioProcessingImpl::RecordAudioProcessingState() {
1906 RTC_DCHECK(aec_dump_);
1907 AecDump::AudioProcessingState audio_proc_state;
1908 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
1909 audio_proc_state.drift =
1910 public_submodules_->echo_cancellation->stream_drift_samples();
1911 audio_proc_state.level = gain_control()->stream_analog_level();
1912 audio_proc_state.keypress = capture_.key_pressed;
1913 aec_dump_->AddAudioProcessingState(audio_proc_state);
1914}
1915
kwiberg83ffe452016-08-29 14:46:07 -07001916AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1917 bool transient_suppressor_enabled,
1918 const std::vector<Point>& array_geometry,
1919 SphericalPointf target_direction)
1920 : aec_system_delay_jumps(-1),
1921 delay_offset_ms(0),
1922 was_stream_delay_set(false),
1923 last_stream_delay_ms(0),
1924 last_aec_system_delay_ms(0),
1925 stream_delay_jumps(-1),
1926 output_will_be_muted(false),
1927 key_pressed(false),
1928 transient_suppressor_enabled(transient_suppressor_enabled),
1929 array_geometry(array_geometry),
1930 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001931 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001932 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001933 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07001934
1935AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1936
1937AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1938
1939AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1940
niklase@google.com470e71d2011-07-07 08:21:25 +00001941} // namespace webrtc