blob: d2d6668fabdadac298d285a4f5d5b10caed0fd7b [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"
35#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070036#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070038#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "modules/audio_processing/level_controller/level_controller.h"
40#include "modules/audio_processing/level_estimator_impl.h"
41#include "modules/audio_processing/low_cut_filter.h"
42#include "modules/audio_processing/noise_suppression_impl.h"
43#include "modules/audio_processing/residual_echo_detector.h"
44#include "modules/audio_processing/transient/transient_suppressor.h"
45#include "modules/audio_processing/voice_detection_impl.h"
46#include "modules/include/module_common_types.h"
47#include "system_wrappers/include/file_wrapper.h"
48#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000049
peah1bcfce52016-08-26 07:16:04 -070050// Check to verify that the define for the intelligibility enhancer is properly
51// set.
52#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
53 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
54 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
55#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
56#endif
57
Michael Graczyk86c6d332015-07-23 11:41:39 -070058#define RETURN_ON_ERR(expr) \
59 do { \
60 int err = (expr); \
61 if (err != kNoError) { \
62 return err; \
63 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000064 } while (0)
65
niklase@google.com470e71d2011-07-07 08:21:25 +000066namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070067
kwibergd59d3bb2016-09-13 07:49:33 -070068constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070069
Michael Graczyk86c6d332015-07-23 11:41:39 -070070namespace {
71
72static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
73 switch (layout) {
74 case AudioProcessing::kMono:
75 case AudioProcessing::kStereo:
76 return false;
77 case AudioProcessing::kMonoAndKeyboard:
78 case AudioProcessing::kStereoAndKeyboard:
79 return true;
80 }
81
kwiberg9e2be5f2016-09-14 05:23:22 -070082 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070083 return false;
84}
aluebsdf6416a2016-03-16 18:26:35 -070085
peah2ace3f92016-09-10 04:42:27 -070086bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070087 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
88 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
89}
90
peah2ace3f92016-09-10 04:42:27 -070091int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
92#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070093 constexpr int kMaxSplittingNativeProcessRate =
94 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070095#else
kwibergd59d3bb2016-09-13 07:49:33 -070096 constexpr int kMaxSplittingNativeProcessRate =
97 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070098#endif
kwibergd59d3bb2016-09-13 07:49:33 -070099 static_assert(
100 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
101 "");
peah2ace3f92016-09-10 04:42:27 -0700102 const int uppermost_native_rate = band_splitting_required
103 ? kMaxSplittingNativeProcessRate
104 : AudioProcessing::kSampleRate48kHz;
105
106 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
107 if (rate >= uppermost_native_rate) {
108 return uppermost_native_rate;
109 }
110 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700111 return rate;
112 }
113 }
peah2ace3f92016-09-10 04:42:27 -0700114 RTC_NOTREACHED();
115 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700116}
117
peah9e6a2902017-05-15 07:19:21 -0700118// Maximum lengths that frame of samples being passed from the render side to
119// the capture side can have (does not apply to AEC3).
120static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
121static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
122
peah764e3642016-10-22 05:04:30 -0700123// Maximum number of frames to buffer in the render queue.
124// TODO(peah): Decrease this once we properly handle hugely unbalanced
125// reverse and forward call numbers.
126static const size_t kMaxNumFramesToBuffer = 100;
127
peah8271d042016-11-22 07:24:52 -0800128class HighPassFilterImpl : public HighPassFilter {
129 public:
130 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
131 ~HighPassFilterImpl() override = default;
132
133 // HighPassFilter implementation.
134 int Enable(bool enable) override {
135 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
136 config->high_pass_filter.enabled = enable;
137 });
138
139 return AudioProcessing::kNoError;
140 }
141
142 bool is_enabled() const override {
143 return apm_->GetConfig().high_pass_filter.enabled;
144 }
145
146 private:
147 AudioProcessingImpl* apm_;
148 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
149};
150
aleloi868f32f2017-05-23 07:20:05 -0700151webrtc::InternalAPMStreamsConfig ToStreamsConfig(
152 const ProcessingConfig& api_format) {
153 webrtc::InternalAPMStreamsConfig result;
154 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
155 result.input_num_channels = api_format.input_stream().num_channels();
156 result.output_num_channels = api_format.output_stream().num_channels();
157 result.render_input_num_channels =
158 api_format.reverse_input_stream().num_channels();
159 result.render_input_sample_rate =
160 api_format.reverse_input_stream().sample_rate_hz();
161 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
162 result.render_output_sample_rate =
163 api_format.reverse_output_stream().sample_rate_hz();
164 result.render_output_num_channels =
165 api_format.reverse_output_stream().num_channels();
166 return result;
167}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700168} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000169
170// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000171static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000172
Sam Zackrisson0beac582017-09-25 12:04:02 +0200173AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
174 bool capture_post_processor_enabled)
175 : capture_post_processor_enabled_(capture_post_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700176
177bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800178 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700179 bool echo_canceller_enabled,
180 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700181 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700182 bool noise_suppressor_enabled,
183 bool intelligibility_enhancer_enabled,
184 bool beamformer_enabled,
185 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700186 bool gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -0700187 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800188 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700189 bool voice_activity_detector_enabled,
190 bool level_estimator_enabled,
191 bool transient_suppressor_enabled) {
192 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800193 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700194 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
195 changed |=
196 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700197 changed |=
198 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700199 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
200 changed |=
201 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
202 changed |= (beamformer_enabled != beamformer_enabled_);
203 changed |=
204 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700205 changed |=
206 (gain_controller2_enabled != gain_controller2_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700207 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800208 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700209 changed |= (level_estimator_enabled != level_estimator_enabled_);
210 changed |=
211 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
212 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
213 if (changed) {
peah8271d042016-11-22 07:24:52 -0800214 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700215 echo_canceller_enabled_ = echo_canceller_enabled;
216 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700217 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700218 noise_suppressor_enabled_ = noise_suppressor_enabled;
219 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
220 beamformer_enabled_ = beamformer_enabled;
221 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700222 gain_controller2_enabled_ = gain_controller2_enabled;
peah2ace3f92016-09-10 04:42:27 -0700223 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800224 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700225 level_estimator_enabled_ = level_estimator_enabled;
226 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
227 transient_suppressor_enabled_ = transient_suppressor_enabled;
228 }
229
230 changed |= first_update_;
231 first_update_ = false;
232 return changed;
233}
234
235bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
236 const {
237#if WEBRTC_INTELLIGIBILITY_ENHANCER
238 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700239 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700240#else
peah52775842017-05-16 06:14:09 -0700241 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700242#endif
243}
244
245bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
246 const {
peah8271d042016-11-22 07:24:52 -0800247 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700248 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800249 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
250 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700251}
252
peah23ac8b42017-05-23 05:33:56 -0700253bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
254 const {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200255 return level_controller_enabled_ || capture_post_processor_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700256}
257
peah2ace3f92016-09-10 04:42:27 -0700258bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
259 const {
260 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800261 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peah52775842017-05-16 06:14:09 -0700262 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700263}
264
265bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
266 const {
267#if WEBRTC_INTELLIGIBILITY_ENHANCER
268 return intelligibility_enhancer_enabled_;
269#else
270 return false;
271#endif
272}
273
solenberg5e465c32015-12-08 13:22:33 -0800274struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800275 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800276 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800277 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800278 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800279 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800280 std::unique_ptr<LevelEstimatorImpl> level_estimator;
281 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
282 std::unique_ptr<VoiceDetectionImpl> voice_detection;
283 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800284 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800285
286 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800287 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700288#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800289 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700290#endif
solenberg5e465c32015-12-08 13:22:33 -0800291};
292
293struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200294 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
295 std::unique_ptr<PostProcessing> capture_post_processor)
296 : beamformer(beamformer),
297 capture_post_processor(std::move(capture_post_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800298 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700299 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800300 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700301 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800302 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700303 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700304 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
Gustaf Ullbergc5222982017-10-05 10:25:05 +0200305 std::unique_ptr<EchoControl> echo_canceller3;
Sam Zackrisson0beac582017-09-25 12:04:02 +0200306 std::unique_ptr<PostProcessing> capture_post_processor;
solenberg5e465c32015-12-08 13:22:33 -0800307};
308
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000309AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700310 webrtc::Config config;
Sam Zackrisson0beac582017-09-25 12:04:02 +0200311 return Create(config, nullptr, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000312}
313
peah88ac8532016-09-12 16:47:25 -0700314AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200315 return Create(config, nullptr, nullptr);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000316}
317
peah88ac8532016-09-12 16:47:25 -0700318AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700319 NonlinearBeamformer* beamformer) {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200320 return Create(config, nullptr, beamformer);
321}
322
323AudioProcessing* AudioProcessing::Create(
324 const webrtc::Config& config,
325 std::unique_ptr<PostProcessing> capture_post_processor,
326 NonlinearBeamformer* beamformer) {
327 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
328 config, std::move(capture_post_processor), beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000329 if (apm->Initialize() != kNoError) {
330 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800331 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000332 }
333
334 return apm;
335}
336
peah88ac8532016-09-12 16:47:25 -0700337AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200338 : AudioProcessingImpl(config, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000339
Sam Zackrisson0beac582017-09-25 12:04:02 +0200340AudioProcessingImpl::AudioProcessingImpl(
341 const webrtc::Config& config,
342 std::unique_ptr<PostProcessing> capture_post_processor,
343 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800344 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200345 submodule_states_(!!capture_post_processor),
peah8271d042016-11-22 07:24:52 -0800346 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200347 private_submodules_(
348 new ApmPrivateSubmodules(beamformer,
349 std::move(capture_post_processor))),
peahdf3efa82015-11-28 12:35:15 -0800350 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800351 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000352#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700353 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000354#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700355 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000356#endif
andrew1c7075f2015-06-24 18:14:14 -0700357#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800358 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700359#else
aluebs2a346882016-01-11 18:04:30 -0800360 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700361#endif
aluebs2a346882016-01-11 18:04:30 -0800362 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800363 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700364 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700365 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800366 {
367 rtc::CritScope cs_render(&crit_render_);
368 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000369
peahb624d8c2016-03-05 03:01:14 -0800370 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700371 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800372 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700373 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800374 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700375 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800376 public_submodules_->level_estimator.reset(
377 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800378 public_submodules_->noise_suppression.reset(
379 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800380 public_submodules_->voice_detection.reset(
381 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800382 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800383 new GainControlForExperimentalAgc(
384 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700385 private_submodules_->residual_echo_detector.reset(
386 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700387
peahc19f3122016-10-07 14:54:10 -0700388 // TODO(peah): Move this creation to happen only when the level controller
389 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700390 private_submodules_->level_controller.reset(new LevelController());
Sam Zackrisson0beac582017-09-25 12:04:02 +0200391
392 LOG(LS_INFO) << "Capture post processor activated: "
393 << !!private_submodules_->capture_post_processor;
peahdf3efa82015-11-28 12:35:15 -0800394 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000395
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000396 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000397}
398
399AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800400 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800401 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800402 private_submodules_->agc_manager.reset();
403 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800404 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000405}
406
niklase@google.com470e71d2011-07-07 08:21:25 +0000407int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800408 // Run in a single-threaded manner during initialization.
409 rtc::CritScope cs_render(&crit_render_);
410 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000411 return InitializeLocked();
412}
413
peahde65ddc2016-09-16 15:02:15 -0700414int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
415 int capture_output_sample_rate_hz,
416 int render_input_sample_rate_hz,
417 ChannelLayout capture_input_layout,
418 ChannelLayout capture_output_layout,
419 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700420 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700421 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
422 LayoutHasKeyboard(capture_input_layout)},
423 {capture_output_sample_rate_hz,
424 ChannelsFromLayout(capture_output_layout),
425 LayoutHasKeyboard(capture_output_layout)},
426 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
427 LayoutHasKeyboard(render_input_layout)},
428 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
429 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700430
431 return Initialize(processing_config);
432}
433
434int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800435 // Run in a single-threaded manner during initialization.
436 rtc::CritScope cs_render(&crit_render_);
437 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700438 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000439}
440
peahdf3efa82015-11-28 12:35:15 -0800441int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800442 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700443 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800444}
445
peahdf3efa82015-11-28 12:35:15 -0800446int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700447 const ProcessingConfig& processing_config,
448 bool force_initialization) {
449 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800450}
451
peah192164e2015-11-17 02:16:45 -0800452// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800453// their current values (needs to be called while holding the crit_render_lock).
454int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700455 const ProcessingConfig& processing_config,
456 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800457 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700458 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800459 return kNoError;
460 }
peahdf3efa82015-11-28 12:35:15 -0800461
462 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800463 return InitializeLocked(processing_config);
464}
465
niklase@google.com470e71d2011-07-07 08:21:25 +0000466int AudioProcessingImpl::InitializeLocked() {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200467 UpdateActiveSubmoduleStates();
468
peah522d71b2017-02-23 05:16:26 -0800469 const int capture_audiobuffer_num_channels =
470 capture_nonlocked_.beamformer_enabled
471 ? formats_.api_format.input_stream().num_channels()
472 : formats_.api_format.output_stream().num_channels();
473
peahde65ddc2016-09-16 15:02:15 -0700474 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800475 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700476 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800477 : formats_.api_format.reverse_output_stream().num_frames();
478 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
479 render_.render_audio.reset(new AudioBuffer(
480 formats_.api_format.reverse_input_stream().num_frames(),
481 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700482 formats_.render_processing_format.num_frames(),
483 formats_.render_processing_format.num_channels(),
484 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700485 if (formats_.api_format.reverse_input_stream() !=
486 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800487 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800488 formats_.api_format.reverse_input_stream().num_channels(),
489 formats_.api_format.reverse_input_stream().num_frames(),
490 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800491 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700492 } else {
peahdf3efa82015-11-28 12:35:15 -0800493 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700494 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700495 } else {
peahdf3efa82015-11-28 12:35:15 -0800496 render_.render_audio.reset(nullptr);
497 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700498 }
peahce4d9152017-05-19 01:28:05 -0700499
peahdf3efa82015-11-28 12:35:15 -0800500 capture_.capture_audio.reset(
501 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
502 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700503 capture_nonlocked_.capture_processing_format.num_frames(),
504 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800505 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000506
peahde65ddc2016-09-16 15:02:15 -0700507 public_submodules_->echo_cancellation->Initialize(
508 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
509 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700510 AllocateRenderQueue();
511
ivoc3e9a5372016-10-28 07:55:33 -0700512 int success = public_submodules_->echo_cancellation->enable_metrics(true);
513 RTC_DCHECK_EQ(0, success);
514 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
515 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700516 public_submodules_->echo_control_mobile->Initialize(
517 proc_split_sample_rate_hz(), num_reverse_channels(),
518 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700519
520 public_submodules_->gain_control->Initialize(num_proc_channels(),
521 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700522 if (constants_.use_experimental_agc) {
523 if (!private_submodules_->agc_manager.get()) {
524 private_submodules_->agc_manager.reset(new AgcManagerDirect(
525 public_submodules_->gain_control.get(),
526 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800527 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700528 }
529 private_submodules_->agc_manager->Initialize();
530 private_submodules_->agc_manager->SetCaptureMuted(
531 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700532 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700533 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200534 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000535 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700536#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700537 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700538#endif
peah8271d042016-11-22 07:24:52 -0800539 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700540 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
541 proc_sample_rate_hz());
542 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
543 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700544 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700545 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800546 InitializeEchoCanceller3();
alessiob3ec96df2017-05-22 06:57:06 -0700547 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200548 InitializePostProcessor();
solenberg70f99032015-12-08 11:07:32 -0800549
aleloi868f32f2017-05-23 07:20:05 -0700550 if (aec_dump_) {
551 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
552 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000553 return kNoError;
554}
555
Michael Graczyk86c6d332015-07-23 11:41:39 -0700556int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200557 UpdateActiveSubmoduleStates();
558
Michael Graczyk86c6d332015-07-23 11:41:39 -0700559 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700560 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
561 return kBadSampleRateError;
562 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000563 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700564
Peter Kasting69558702016-01-12 16:26:35 -0800565 const size_t num_in_channels = config.input_stream().num_channels();
566 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700567
568 // Need at least one input channel.
569 // Need either one output channel or as many outputs as there are inputs.
570 if (num_in_channels == 0 ||
571 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700572 return kBadNumberChannelsError;
573 }
574
aluebsb2328d12016-01-11 20:32:29 -0800575 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800576 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700577 return kBadNumberChannelsError;
578 }
579
peahdf3efa82015-11-28 12:35:15 -0800580 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000581
peahde65ddc2016-09-16 15:02:15 -0700582 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700583 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700584 formats_.api_format.output_stream().sample_rate_hz()),
585 submodule_states_.CaptureMultiBandSubModulesActive() ||
586 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000587
peahde65ddc2016-09-16 15:02:15 -0700588 capture_nonlocked_.capture_processing_format =
589 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700590
peah2ce640f2017-04-07 03:57:48 -0700591 int render_processing_rate;
592 if (!config_.echo_canceller3.enabled) {
593 render_processing_rate = FindNativeProcessRateToUse(
594 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
595 formats_.api_format.reverse_output_stream().sample_rate_hz()),
596 submodule_states_.CaptureMultiBandSubModulesActive() ||
597 submodule_states_.RenderMultiBandSubModulesActive());
598 } else {
599 render_processing_rate = capture_processing_rate;
600 }
601
aluebseb3603b2016-04-20 15:27:58 -0700602 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
603 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700604 if (render_processing_rate > kSampleRate32kHz &&
605 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700606 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
607 ? kSampleRate32kHz
608 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700609 }
peah2ce640f2017-04-07 03:57:48 -0700610
peahde65ddc2016-09-16 15:02:15 -0700611 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700612 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700613 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
614 kSampleRate8kHz) {
615 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000616 } else {
peahde65ddc2016-09-16 15:02:15 -0700617 render_processing_rate =
618 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000619 }
620
peahde65ddc2016-09-16 15:02:15 -0700621 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000622 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700623 if (submodule_states_.RenderMultiBandSubModulesActive()) {
624 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
625 } else {
626 formats_.render_processing_format = StreamConfig(
627 formats_.api_format.reverse_input_stream().sample_rate_hz(),
628 formats_.api_format.reverse_input_stream().num_channels());
629 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000630
peahde65ddc2016-09-16 15:02:15 -0700631 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
632 kSampleRate32kHz ||
633 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
634 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800635 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000636 } else {
peahdf3efa82015-11-28 12:35:15 -0800637 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700638 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000639 }
640
641 return InitializeLocked();
642}
643
peah88ac8532016-09-12 16:47:25 -0700644void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700645 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700646
peahc19f3122016-10-07 14:54:10 -0700647 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700648 if (!config_ok) {
649 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
650 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700651 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700652 << std::endl
653 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700654 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700655 }
656
657 // Run in a single-threaded manner when applying the settings.
658 rtc::CritScope cs_render(&crit_render_);
659 rtc::CritScope cs_capture(&crit_capture_);
660
peahc19f3122016-10-07 14:54:10 -0700661 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
662 // with the value in config_ everywhere in the code.
663 if (capture_nonlocked_.level_controller_enabled !=
664 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700665 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700666 config_.level_controller.enabled;
667 // TODO(peah): Remove the conditional initialization to always initialize
668 // the level controller regardless of whether it is enabled or not.
669 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700670 }
peahc19f3122016-10-07 14:54:10 -0700671 LOG(LS_INFO) << "Level controller activated: "
672 << capture_nonlocked_.level_controller_enabled;
673
674 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800675
676 InitializeLowCutFilter();
677
678 LOG(LS_INFO) << "Highpass filter activated: "
679 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800680
681 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
682 if (!config_ok) {
683 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
684 << "echo canceller 3: "
685 << EchoCanceller3::ToString(config_.echo_canceller3)
686 << std::endl
687 << "Reverting to default parameter set";
688 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
689 }
690
691 if (config.echo_canceller3.enabled !=
692 capture_nonlocked_.echo_canceller3_enabled) {
693 capture_nonlocked_.echo_canceller3_enabled =
694 config_.echo_canceller3.enabled;
695 InitializeEchoCanceller3();
696 LOG(LS_INFO) << "Echo canceller 3 activated: "
697 << capture_nonlocked_.echo_canceller3_enabled;
698 }
alessiob3ec96df2017-05-22 06:57:06 -0700699
700 config_ok = GainController2::Validate(config_.gain_controller2);
701 if (!config_ok) {
702 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
703 << "gain_controller2: "
704 << GainController2::ToString(config_.gain_controller2)
705 << std::endl
706 << "Reverting to default parameter set";
707 config_.gain_controller2 = AudioProcessing::Config::GainController2();
708 }
709
710 if (config.gain_controller2.enabled !=
711 capture_nonlocked_.gain_controller2_enabled) {
712 capture_nonlocked_.gain_controller2_enabled =
713 config_.gain_controller2.enabled;
714 InitializeGainController2();
715 LOG(LS_INFO) << "Gain controller 2 activated: "
716 << capture_nonlocked_.gain_controller2_enabled;
717 }
peah88ac8532016-09-12 16:47:25 -0700718}
719
720void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800721 // Run in a single-threaded manner when setting the extra options.
722 rtc::CritScope cs_render(&crit_render_);
723 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000724
peahb624d8c2016-03-05 03:01:14 -0800725 public_submodules_->echo_cancellation->SetExtraOptions(config);
726
peahdf3efa82015-11-28 12:35:15 -0800727 if (capture_.transient_suppressor_enabled !=
728 config.Get<ExperimentalNs>().enabled) {
729 capture_.transient_suppressor_enabled =
730 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000731 InitializeTransient();
732 }
aluebs2a346882016-01-11 18:04:30 -0800733
peah1bcfce52016-08-26 07:16:04 -0700734#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700735 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700736 config.Get<Intelligibility>().enabled) {
737 capture_nonlocked_.intelligibility_enabled =
738 config.Get<Intelligibility>().enabled;
739 InitializeIntelligibility();
740 }
peah1bcfce52016-08-26 07:16:04 -0700741#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700742
aluebs2a346882016-01-11 18:04:30 -0800743#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800744 if (capture_nonlocked_.beamformer_enabled !=
745 config.Get<Beamforming>().enabled) {
746 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800747 if (config.Get<Beamforming>().array_geometry.size() > 1) {
748 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
749 }
750 capture_.target_direction = config.Get<Beamforming>().target_direction;
751 InitializeBeamformer();
752 }
753#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000754}
755
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000756int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800757 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700758 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000759}
760
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000761int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800762 // Used as callback from submodules, hence locking is not allowed.
763 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000764}
765
Peter Kasting69558702016-01-12 16:26:35 -0800766size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800767 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700768 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000769}
770
Peter Kasting69558702016-01-12 16:26:35 -0800771size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800772 // Used as callback from submodules, hence locking is not allowed.
773 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000774}
775
Peter Kasting69558702016-01-12 16:26:35 -0800776size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800777 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700778 return (capture_nonlocked_.beamformer_enabled ||
779 capture_nonlocked_.echo_canceller3_enabled)
780 ? 1
781 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800782}
783
Peter Kasting69558702016-01-12 16:26:35 -0800784size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800785 // Used as callback from submodules, hence locking is not allowed.
786 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000787}
788
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000789void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800790 rtc::CritScope cs(&crit_capture_);
791 capture_.output_will_be_muted = muted;
792 if (private_submodules_->agc_manager.get()) {
793 private_submodules_->agc_manager->SetCaptureMuted(
794 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000795 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000796}
797
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000798
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000799int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700800 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000801 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000802 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000803 int output_sample_rate_hz,
804 ChannelLayout output_layout,
805 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800806 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800807 StreamConfig input_stream;
808 StreamConfig output_stream;
809 {
810 // Access the formats_.api_format.input_stream beneath the capture lock.
811 // The lock must be released as it is later required in the call
812 // to ProcessStream(,,,);
813 rtc::CritScope cs(&crit_capture_);
814 input_stream = formats_.api_format.input_stream();
815 output_stream = formats_.api_format.output_stream();
816 }
817
Michael Graczyk86c6d332015-07-23 11:41:39 -0700818 input_stream.set_sample_rate_hz(input_sample_rate_hz);
819 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
820 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700821 output_stream.set_sample_rate_hz(output_sample_rate_hz);
822 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
823 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
824
825 if (samples_per_channel != input_stream.num_frames()) {
826 return kBadDataLengthError;
827 }
828 return ProcessStream(src, input_stream, output_stream, dest);
829}
830
831int AudioProcessingImpl::ProcessStream(const float* const* src,
832 const StreamConfig& input_config,
833 const StreamConfig& output_config,
834 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800835 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800836 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700837 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800838 {
839 // Acquire the capture lock in order to safely call the function
840 // that retrieves the render side data. This function accesses apm
841 // getters that need the capture lock held when being called.
842 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700843 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800844
845 if (!src || !dest) {
846 return kNullPointerError;
847 }
848
849 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700850 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000851 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000852
Michael Graczyk86c6d332015-07-23 11:41:39 -0700853 processing_config.input_stream() = input_config;
854 processing_config.output_stream() = output_config;
855
peahdf3efa82015-11-28 12:35:15 -0800856 {
857 // Do conditional reinitialization.
858 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700859 RETURN_ON_ERR(
860 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800861 }
862 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700863 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
864 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000865
aleloi868f32f2017-05-23 07:20:05 -0700866 if (aec_dump_) {
867 RecordUnprocessedCaptureStream(src);
868 }
869
peahdf3efa82015-11-28 12:35:15 -0800870 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700871 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800872 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000873
aleloi868f32f2017-05-23 07:20:05 -0700874 if (aec_dump_) {
875 RecordProcessedCaptureStream(dest);
876 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000877 return kNoError;
878}
879
peah9e6a2902017-05-15 07:19:21 -0700880void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700881 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
882 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700883 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700884
kwibergaf476c72016-11-28 15:21:39 -0800885 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700886
887 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700888 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700889 // The data queue is full and needs to be emptied.
890 EmptyQueuedRenderAudio();
891
892 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700893 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700894 RTC_DCHECK(result);
895 }
896
897 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
898 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700899 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700900
901 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700902 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700903 // The data queue is full and needs to be emptied.
904 EmptyQueuedRenderAudio();
905
906 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700907 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700908 RTC_DCHECK(result);
909 }
peah701d6282016-10-25 05:42:20 -0700910
911 if (!constants_.use_experimental_agc) {
912 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
913 // Insert the samples into the queue.
914 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
915 // The data queue is full and needs to be emptied.
916 EmptyQueuedRenderAudio();
917
918 // Retry the insert (should always work).
919 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
920 RTC_DCHECK(result);
921 }
922 }
peah9e6a2902017-05-15 07:19:21 -0700923}
ivoc9f4a4a02016-10-28 05:39:16 -0700924
peah9e6a2902017-05-15 07:19:21 -0700925void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700926 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
927
928 // Insert the samples into the queue.
929 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
930 // The data queue is full and needs to be emptied.
931 EmptyQueuedRenderAudio();
932
933 // Retry the insert (should always work).
934 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
935 RTC_DCHECK(result);
936 }
peah764e3642016-10-22 05:04:30 -0700937}
938
939void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700940 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700941 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700942 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700943 EchoCancellationImpl::NumCancellersRequired(
944 num_output_channels(), num_reverse_channels()));
945
peah701d6282016-10-25 05:42:20 -0700946 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700947 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700948 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700949 EchoControlMobileImpl::NumCancellersRequired(
950 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700951
peah701d6282016-10-25 05:42:20 -0700952 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700953 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700954
ivoc9f4a4a02016-10-28 05:39:16 -0700955 const size_t new_red_render_queue_element_max_size =
956 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
957
peaha0624602016-10-25 04:45:24 -0700958 // Reallocate the queues if the queue item sizes are too small to fit the
959 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700960 if (aec_render_queue_element_max_size_ <
961 new_aec_render_queue_element_max_size) {
962 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700963
peaha0624602016-10-25 04:45:24 -0700964 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700965 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700966
peah701d6282016-10-25 05:42:20 -0700967 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700968 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
969 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700970 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700971 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700972
peah701d6282016-10-25 05:42:20 -0700973 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
974 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700975 } else {
peah701d6282016-10-25 05:42:20 -0700976 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700977 }
978
peah701d6282016-10-25 05:42:20 -0700979 if (aecm_render_queue_element_max_size_ <
980 new_aecm_render_queue_element_max_size) {
981 aecm_render_queue_element_max_size_ =
982 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700983
984 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700985 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700986
peah701d6282016-10-25 05:42:20 -0700987 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700988 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
989 kMaxNumFramesToBuffer, template_queue_element,
990 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700991 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700992
peah701d6282016-10-25 05:42:20 -0700993 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
994 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700995 } else {
peah701d6282016-10-25 05:42:20 -0700996 aecm_render_signal_queue_->Clear();
997 }
998
999 if (agc_render_queue_element_max_size_ <
1000 new_agc_render_queue_element_max_size) {
1001 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1002
1003 std::vector<int16_t> template_queue_element(
1004 agc_render_queue_element_max_size_);
1005
1006 agc_render_signal_queue_.reset(
1007 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1008 kMaxNumFramesToBuffer, template_queue_element,
1009 RenderQueueItemVerifier<int16_t>(
1010 agc_render_queue_element_max_size_)));
1011
1012 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1013 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1014 } else {
1015 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001016 }
ivoc9f4a4a02016-10-28 05:39:16 -07001017
1018 if (red_render_queue_element_max_size_ <
1019 new_red_render_queue_element_max_size) {
1020 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1021
1022 std::vector<float> template_queue_element(
1023 red_render_queue_element_max_size_);
1024
1025 red_render_signal_queue_.reset(
1026 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1027 kMaxNumFramesToBuffer, template_queue_element,
1028 RenderQueueItemVerifier<float>(
1029 red_render_queue_element_max_size_)));
1030
1031 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1032 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1033 } else {
1034 red_render_signal_queue_->Clear();
1035 }
peah764e3642016-10-22 05:04:30 -07001036}
1037
1038void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1039 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001040 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001041 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001042 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001043 }
1044
peah701d6282016-10-25 05:42:20 -07001045 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001046 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001047 aecm_capture_queue_buffer_);
1048 }
1049
1050 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1051 public_submodules_->gain_control->ProcessRenderAudio(
1052 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001053 }
ivoc9f4a4a02016-10-28 05:39:16 -07001054
1055 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1056 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1057 red_capture_queue_buffer_);
1058 }
peah764e3642016-10-22 05:04:30 -07001059}
1060
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001061int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001062 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001063 {
1064 // Acquire the capture lock in order to safely call the function
1065 // that retrieves the render side data. This function accesses apm
1066 // getters that need the capture lock held when being called.
1067 // The lock needs to be released as
1068 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1069 // as well.
1070 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001071 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001072 }
peahfa6228e2015-11-16 16:27:42 -08001073
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001074 if (!frame) {
1075 return kNullPointerError;
1076 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001077 // Must be a native rate.
1078 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1079 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001080 frame->sample_rate_hz_ != kSampleRate32kHz &&
1081 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001082 return kBadSampleRateError;
1083 }
peah192164e2015-11-17 02:16:45 -08001084
peahdf3efa82015-11-28 12:35:15 -08001085 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001086 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001087 {
1088 // Aquire lock for the access of api_format.
1089 // The lock is released immediately due to the conditional
1090 // reinitialization.
1091 rtc::CritScope cs_capture(&crit_capture_);
1092 // TODO(ajm): The input and output rates and channels are currently
1093 // constrained to be identical in the int16 interface.
1094 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001095
1096 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001097 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001098 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1099 processing_config.input_stream().set_num_channels(frame->num_channels_);
1100 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1101 processing_config.output_stream().set_num_channels(frame->num_channels_);
1102
peahdf3efa82015-11-28 12:35:15 -08001103 {
1104 // Do conditional reinitialization.
1105 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001106 RETURN_ON_ERR(
1107 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001108 }
1109 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001110 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001111 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001112 return kBadDataLengthError;
1113 }
1114
aleloi868f32f2017-05-23 07:20:05 -07001115 if (aec_dump_) {
1116 RecordUnprocessedCaptureStream(*frame);
1117 }
1118
peahdf3efa82015-11-28 12:35:15 -08001119 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001120 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001121 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001122 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1123 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001124
aleloi868f32f2017-05-23 07:20:05 -07001125 if (aec_dump_) {
1126 RecordProcessedCaptureStream(*frame);
1127 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001128
1129 return kNoError;
1130}
1131
peahde65ddc2016-09-16 15:02:15 -07001132int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001133 // Ensure that not both the AEC and AECM are active at the same time.
1134 // TODO(peah): Simplify once the public API Enable functions for these
1135 // are moved to APM.
1136 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1137 public_submodules_->echo_control_mobile->is_enabled()));
1138
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001139 MaybeUpdateHistograms();
1140
peahde65ddc2016-09-16 15:02:15 -07001141 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001142
peah1b08dc32016-12-20 13:45:58 -08001143 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001144 capture_buffer->channels_const()[0],
1145 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001146 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1147 if (log_rms) {
1148 capture_rms_interval_counter_ = 0;
1149 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001150 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1151 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1152 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1153 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001154 }
1155
peahe0eae3c2016-12-14 01:16:23 -08001156 if (private_submodules_->echo_canceller3) {
Per Ã…hgren9aed31c2017-06-29 20:23:27 +02001157 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1158 // issues have been addressed.
1159 capture_.echo_path_gain_change = false;
peahe0eae3c2016-12-14 01:16:23 -08001160 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1161 }
1162
peahbe615622016-02-13 16:40:47 -08001163 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001164 public_submodules_->gain_control->is_enabled()) {
1165 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001166 capture_buffer->channels()[0], capture_buffer->num_channels(),
1167 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001168 }
1169
peah2ace3f92016-09-10 04:42:27 -07001170 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1171 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001172 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1173 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001174 }
1175
peah522d71b2017-02-23 05:16:26 -08001176 if (private_submodules_->echo_canceller3) {
1177 // Force down-mixing of the number of channels after the detection of
1178 // capture signal saturation.
1179 // TODO(peah): Look into ensuring that this kind of tampering with the
1180 // AudioBuffer functionality should not be needed.
1181 capture_buffer->set_num_channels(1);
1182 }
1183
aluebsb2328d12016-01-11 20:32:29 -08001184 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001185 private_submodules_->beamformer->AnalyzeChunk(
1186 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001187 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001188 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001189 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001190
peahe0eae3c2016-12-14 01:16:23 -08001191 // TODO(peah): Move the AEC3 low-cut filter to this place.
1192 if (private_submodules_->low_cut_filter &&
1193 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001194 private_submodules_->low_cut_filter->Process(capture_buffer);
1195 }
peahde65ddc2016-09-16 15:02:15 -07001196 RETURN_ON_ERR(
1197 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1198 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001199
1200 // Ensure that the stream delay was set before the call to the
1201 // AEC ProcessCaptureAudio function.
1202 if (public_submodules_->echo_cancellation->is_enabled() &&
1203 !was_stream_delay_set()) {
1204 return AudioProcessing::kStreamParameterNotSetError;
1205 }
1206
peahe0eae3c2016-12-14 01:16:23 -08001207 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001208 private_submodules_->echo_canceller3->ProcessCapture(
1209 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001210 } else {
1211 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1212 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001213 }
1214
peahdf3efa82015-11-28 12:35:15 -08001215 if (public_submodules_->echo_control_mobile->is_enabled() &&
1216 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001217 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001218 }
peahde65ddc2016-09-16 15:02:15 -07001219 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001220#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001221 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001222 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001223 int gain_db = public_submodules_->gain_control->is_enabled() ?
1224 public_submodules_->gain_control->compression_gain_db() :
1225 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001226 float gain = std::pow(10.f, gain_db / 20.f);
1227 gain *= capture_nonlocked_.level_controller_enabled ?
1228 private_submodules_->level_controller->GetLastGain() :
1229 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001230 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001231 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001232 }
peah1bcfce52016-08-26 07:16:04 -07001233#endif
peah253534d2016-03-15 04:32:28 -07001234
1235 // Ensure that the stream delay was set before the call to the
1236 // AECM ProcessCaptureAudio function.
1237 if (public_submodules_->echo_control_mobile->is_enabled() &&
1238 !was_stream_delay_set()) {
1239 return AudioProcessing::kStreamParameterNotSetError;
1240 }
1241
Per Ã…hgren46537a32017-06-07 10:08:10 +02001242 if (!(private_submodules_->echo_canceller3 ||
1243 public_submodules_->echo_cancellation->is_enabled())) {
1244 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1245 capture_buffer, stream_delay_ms()));
1246 }
ivoc9f4a4a02016-10-28 05:39:16 -07001247
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001248 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001249 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001250 }
1251
peahde65ddc2016-09-16 15:02:15 -07001252 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001253
peahbe615622016-02-13 16:40:47 -08001254 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001255 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001256 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001257 private_submodules_->beamformer->is_target_present())) {
1258 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001259 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1260 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001261 }
peahb8fbb542016-03-15 02:28:08 -07001262 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001263 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001264
peah2ace3f92016-09-10 04:42:27 -07001265 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1266 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001267 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1268 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001269 }
1270
peah9e6a2902017-05-15 07:19:21 -07001271 if (config_.residual_echo_detector.enabled) {
1272 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1273 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1274 capture_buffer->num_frames()));
1275 }
1276
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001277 // TODO(aluebs): Investigate if the transient suppression placement should be
1278 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001279 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001280 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001281 private_submodules_->agc_manager.get()
1282 ? private_submodules_->agc_manager->voice_probability()
1283 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001284
peahdf3efa82015-11-28 12:35:15 -08001285 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001286 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1287 capture_buffer->num_channels(),
1288 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1289 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1290 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001291 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001292 }
1293
alessiob3ec96df2017-05-22 06:57:06 -07001294 if (capture_nonlocked_.gain_controller2_enabled) {
1295 private_submodules_->gain_controller2->Process(capture_buffer);
1296 }
1297
peahca4cac72016-06-29 15:26:12 -07001298 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001299 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001300 }
1301
Sam Zackrisson0beac582017-09-25 12:04:02 +02001302 if (private_submodules_->capture_post_processor) {
1303 private_submodules_->capture_post_processor->Process(capture_buffer);
1304 }
1305
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001306 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001307 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001308
peah1b08dc32016-12-20 13:45:58 -08001309 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1310 capture_buffer->channels_const()[0],
1311 capture_nonlocked_.capture_processing_format.num_frames()));
1312 if (log_rms) {
1313 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1314 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1315 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1316 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1317 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1318 }
1319
peahdf3efa82015-11-28 12:35:15 -08001320 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001321 return kNoError;
1322}
1323
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001324int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001325 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001326 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001327 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001328 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001329 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001330 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001331 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001332 };
1333 if (samples_per_channel != reverse_config.num_frames()) {
1334 return kBadDataLengthError;
1335 }
peahdf3efa82015-11-28 12:35:15 -08001336 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001337}
1338
peahde65ddc2016-09-16 15:02:15 -07001339int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1340 const StreamConfig& input_config,
1341 const StreamConfig& output_config,
1342 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001343 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001344 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001345 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001346 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001347 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1348 dest);
peah2ace3f92016-09-10 04:42:27 -07001349 } else if (formats_.api_format.reverse_input_stream() !=
1350 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001351 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1352 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001353 } else {
peahde65ddc2016-09-16 15:02:15 -07001354 CopyAudioIfNeeded(src, input_config.num_frames(),
1355 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001356 }
1357
1358 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001359}
1360
peahdf3efa82015-11-28 12:35:15 -08001361int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001362 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001363 const StreamConfig& input_config,
1364 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001365 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001366 return kNullPointerError;
1367 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001368
peahde65ddc2016-09-16 15:02:15 -07001369 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001370 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001371 }
1372
peahdf3efa82015-11-28 12:35:15 -08001373 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001374 processing_config.reverse_input_stream() = input_config;
1375 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001376
peahdf3efa82015-11-28 12:35:15 -08001377 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001378 assert(input_config.num_frames() ==
1379 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001380
aleloi868f32f2017-05-23 07:20:05 -07001381 if (aec_dump_) {
1382 const size_t channel_size =
1383 formats_.api_format.reverse_input_stream().num_frames();
1384 const size_t num_channels =
1385 formats_.api_format.reverse_input_stream().num_channels();
1386 aec_dump_->WriteRenderStreamMessage(
1387 FloatAudioFrame(src, num_channels, channel_size));
1388 }
peahdf3efa82015-11-28 12:35:15 -08001389 render_.render_audio->CopyFrom(src,
1390 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001391 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001392}
1393
1394int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001395 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001396 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001397 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001398 return kNullPointerError;
1399 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001400 // Must be a native rate.
1401 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1402 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001403 frame->sample_rate_hz_ != kSampleRate32kHz &&
1404 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001405 return kBadSampleRateError;
1406 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001407
Michael Graczyk86c6d332015-07-23 11:41:39 -07001408 if (frame->num_channels_ <= 0) {
1409 return kBadNumberChannelsError;
1410 }
1411
peahdf3efa82015-11-28 12:35:15 -08001412 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001413 processing_config.reverse_input_stream().set_sample_rate_hz(
1414 frame->sample_rate_hz_);
1415 processing_config.reverse_input_stream().set_num_channels(
1416 frame->num_channels_);
1417 processing_config.reverse_output_stream().set_sample_rate_hz(
1418 frame->sample_rate_hz_);
1419 processing_config.reverse_output_stream().set_num_channels(
1420 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001421
peahdf3efa82015-11-28 12:35:15 -08001422 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001423 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001424 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001425 return kBadDataLengthError;
1426 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001427
aleloi868f32f2017-05-23 07:20:05 -07001428 if (aec_dump_) {
1429 aec_dump_->WriteRenderStreamMessage(*frame);
1430 }
1431
peahdf3efa82015-11-28 12:35:15 -08001432 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001433 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001434 render_.render_audio->InterleaveTo(
1435 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001436 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001437}
niklase@google.com470e71d2011-07-07 08:21:25 +00001438
peahde65ddc2016-09-16 15:02:15 -07001439int AudioProcessingImpl::ProcessRenderStreamLocked() {
1440 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001441
1442 QueueNonbandedRenderAudio(render_buffer);
1443
peah2ace3f92016-09-10 04:42:27 -07001444 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001445 SampleRateSupportsMultiBand(
1446 formats_.render_processing_format.sample_rate_hz())) {
1447 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001448 }
1449
peah1bcfce52016-08-26 07:16:04 -07001450#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001451 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001452 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001453 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001454 }
peah1bcfce52016-08-26 07:16:04 -07001455#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001456
peahce4d9152017-05-19 01:28:05 -07001457 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1458 QueueBandedRenderAudio(render_buffer);
1459 }
1460
peahe0eae3c2016-12-14 01:16:23 -08001461 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1462 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001463 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001464 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001465
peah2ace3f92016-09-10 04:42:27 -07001466 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001467 SampleRateSupportsMultiBand(
1468 formats_.render_processing_format.sample_rate_hz())) {
1469 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001470 }
1471
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001472 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001473}
1474
1475int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001476 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001477 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001478 capture_.was_stream_delay_set = true;
1479 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001480
niklase@google.com470e71d2011-07-07 08:21:25 +00001481 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001482 delay = 0;
1483 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001484 }
1485
1486 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1487 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001488 delay = 500;
1489 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001490 }
1491
peahdf3efa82015-11-28 12:35:15 -08001492 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001493 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001494}
1495
1496int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001497 // Used as callback from submodules, hence locking is not allowed.
1498 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001499}
1500
1501bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001502 // Used as callback from submodules, hence locking is not allowed.
1503 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001504}
1505
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001506void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001507 rtc::CritScope cs(&crit_capture_);
1508 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001509}
1510
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001511void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001512 rtc::CritScope cs(&crit_capture_);
1513 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001514}
1515
1516int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001517 rtc::CritScope cs(&crit_capture_);
1518 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001519}
1520
aleloi868f32f2017-05-23 07:20:05 -07001521void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1522 RTC_DCHECK(aec_dump);
1523 rtc::CritScope cs_render(&crit_render_);
1524 rtc::CritScope cs_capture(&crit_capture_);
1525
1526 // The previously attached AecDump will be destroyed with the
1527 // 'aec_dump' parameter, which is after locks are released.
1528 aec_dump_.swap(aec_dump);
1529 WriteAecDumpConfigMessage(true);
1530 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1531}
1532
1533void AudioProcessingImpl::DetachAecDump() {
1534 // The d-tor of a task-queue based AecDump blocks until all pending
1535 // tasks are done. This construction avoids blocking while holding
1536 // the render and capture locks.
1537 std::unique_ptr<AecDump> aec_dump = nullptr;
1538 {
1539 rtc::CritScope cs_render(&crit_render_);
1540 rtc::CritScope cs_capture(&crit_capture_);
1541 aec_dump = std::move(aec_dump_);
1542 }
1543}
1544
ivoc4e477a12017-01-15 08:29:46 -08001545AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1546 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1547 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1548 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1549 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1550}
1551
1552AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1553 const AudioProcessingStatistics& other) = default;
1554
1555AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1556 default;
1557
ivoc3e9a5372016-10-28 07:55:33 -07001558// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1559AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1560 const {
1561 return AudioProcessingStatistics();
1562}
1563
1564AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1565 const {
1566 AudioProcessingStatistics stats;
1567 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001568 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1569 if (success == Error::kNoError) {
1570 stats.a_nlp.Set(metrics.a_nlp);
1571 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1572 stats.echo_return_loss.Set(metrics.echo_return_loss);
1573 stats.echo_return_loss_enhancement.Set(
1574 metrics.echo_return_loss_enhancement);
1575 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1576 }
ivoc9c192b22017-03-16 04:22:14 -07001577 {
1578 rtc::CritScope cs_capture(&crit_capture_);
1579 stats.residual_echo_likelihood =
1580 private_submodules_->residual_echo_detector->echo_likelihood();
1581 stats.residual_echo_likelihood_recent_max =
1582 private_submodules_->residual_echo_detector
1583 ->echo_likelihood_recent_max();
1584 }
ivoc3e9a5372016-10-28 07:55:33 -07001585 public_submodules_->echo_cancellation->GetDelayMetrics(
1586 &stats.delay_median, &stats.delay_standard_deviation,
1587 &stats.fraction_poor_delays);
1588 return stats;
1589}
1590
niklase@google.com470e71d2011-07-07 08:21:25 +00001591EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001592 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001593}
1594
1595EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001596 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001597}
1598
1599GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001600 if (constants_.use_experimental_agc) {
1601 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001602 }
peahbfa97112016-03-10 21:09:04 -08001603 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001604}
1605
1606HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001607 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001608}
1609
1610LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001611 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001612}
1613
1614NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001615 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001616}
1617
1618VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001619 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001620}
1621
peah8271d042016-11-22 07:24:52 -08001622void AudioProcessingImpl::MutateConfig(
1623 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1624 rtc::CritScope cs_render(&crit_render_);
1625 rtc::CritScope cs_capture(&crit_capture_);
1626 mutator(&config_);
1627 ApplyConfig(config_);
1628}
1629
1630AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1631 rtc::CritScope cs_render(&crit_render_);
1632 rtc::CritScope cs_capture(&crit_capture_);
1633 return config_;
1634}
1635
peah2ace3f92016-09-10 04:42:27 -07001636bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1637 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001638 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001639 public_submodules_->echo_cancellation->is_enabled(),
1640 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001641 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001642 public_submodules_->noise_suppression->is_enabled(),
1643 capture_nonlocked_.intelligibility_enabled,
1644 capture_nonlocked_.beamformer_enabled,
1645 public_submodules_->gain_control->is_enabled(),
alessiob3ec96df2017-05-22 06:57:06 -07001646 capture_nonlocked_.gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -07001647 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001648 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001649 public_submodules_->voice_detection->is_enabled(),
1650 public_submodules_->level_estimator->is_enabled(),
1651 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001652}
1653
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001654
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001655void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001656 if (capture_.transient_suppressor_enabled) {
1657 if (!public_submodules_->transient_suppressor.get()) {
1658 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001659 }
peahdf3efa82015-11-28 12:35:15 -08001660 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001661 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1662 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001663 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001664}
1665
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001666void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001667 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001668 if (!private_submodules_->beamformer) {
1669 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001670 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001671 }
peahdf3efa82015-11-28 12:35:15 -08001672 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1673 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001674 }
1675}
1676
ekmeyerson60d9b332015-08-14 10:35:55 -07001677void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001678#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001679 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001680 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001681 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001682 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001683 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001684 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001685 }
peah1bcfce52016-08-26 07:16:04 -07001686#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001687}
1688
peah8271d042016-11-22 07:24:52 -08001689void AudioProcessingImpl::InitializeLowCutFilter() {
1690 if (config_.high_pass_filter.enabled) {
1691 private_submodules_->low_cut_filter.reset(
1692 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1693 } else {
1694 private_submodules_->low_cut_filter.reset();
1695 }
1696}
alessiob3ec96df2017-05-22 06:57:06 -07001697
peahe0eae3c2016-12-14 01:16:23 -08001698void AudioProcessingImpl::InitializeEchoCanceller3() {
1699 if (capture_nonlocked_.echo_canceller3_enabled) {
peah697a5902017-06-30 07:06:10 -07001700 private_submodules_->echo_canceller3.reset(new EchoCanceller3(
1701 config_.echo_canceller3, proc_sample_rate_hz(), true));
peahe0eae3c2016-12-14 01:16:23 -08001702 } else {
1703 private_submodules_->echo_canceller3.reset();
1704 }
1705}
peah8271d042016-11-22 07:24:52 -08001706
alessiob3ec96df2017-05-22 06:57:06 -07001707void AudioProcessingImpl::InitializeGainController2() {
1708 if (capture_nonlocked_.gain_controller2_enabled) {
1709 private_submodules_->gain_controller2.reset(
1710 new GainController2(proc_sample_rate_hz()));
1711 } else {
1712 private_submodules_->gain_controller2.reset();
1713 }
1714}
1715
peahca4cac72016-06-29 15:26:12 -07001716void AudioProcessingImpl::InitializeLevelController() {
1717 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1718}
1719
ivoc9f4a4a02016-10-28 05:39:16 -07001720void AudioProcessingImpl::InitializeResidualEchoDetector() {
1721 private_submodules_->residual_echo_detector->Initialize();
1722}
1723
Sam Zackrisson0beac582017-09-25 12:04:02 +02001724void AudioProcessingImpl::InitializePostProcessor() {
1725 if (private_submodules_->capture_post_processor) {
1726 private_submodules_->capture_post_processor->Initialize(
1727 proc_sample_rate_hz(), num_proc_channels());
1728 }
1729}
1730
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001731void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001732 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001733
1734 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001735 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1736 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001737 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001738 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001739 capture_.stream_delay_jumps = 0;
1740 }
1741 if (capture_.aec_system_delay_jumps == -1 &&
1742 echo_cancellation()->stream_has_echo()) {
1743 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001744 }
1745
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001746 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001747 const int diff_stream_delay_ms =
1748 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1749 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1750 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001751 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1752 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001753 if (capture_.stream_delay_jumps == -1) {
1754 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001755 }
peahdf3efa82015-11-28 12:35:15 -08001756 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001757 }
peahdf3efa82015-11-28 12:35:15 -08001758 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001759
1760 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001761 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001762 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001763 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001764 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001765 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1766 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001767 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001768 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001769 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001770 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001771 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1772 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1773 100);
peahdf3efa82015-11-28 12:35:15 -08001774 if (capture_.aec_system_delay_jumps == -1) {
1775 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001776 }
peahdf3efa82015-11-28 12:35:15 -08001777 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001778 }
peahdf3efa82015-11-28 12:35:15 -08001779 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001780 }
1781}
1782
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001783void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001784 // Run in a single-threaded manner.
1785 rtc::CritScope cs_render(&crit_render_);
1786 rtc::CritScope cs_capture(&crit_capture_);
1787
1788 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001789 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001790 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001791 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001792 }
peahdf3efa82015-11-28 12:35:15 -08001793 capture_.stream_delay_jumps = -1;
1794 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001795
peahdf3efa82015-11-28 12:35:15 -08001796 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001797 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1798 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001799 }
peahdf3efa82015-11-28 12:35:15 -08001800 capture_.aec_system_delay_jumps = -1;
1801 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001802}
1803
aleloi868f32f2017-05-23 07:20:05 -07001804void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1805 if (!aec_dump_) {
1806 return;
1807 }
1808 std::string experiments_description =
1809 public_submodules_->echo_cancellation->GetExperimentsDescription();
1810 // TODO(peah): Add semicolon-separated concatenations of experiment
1811 // descriptions for other submodules.
1812 if (capture_nonlocked_.level_controller_enabled) {
1813 experiments_description += "LevelController;";
1814 }
1815 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1816 experiments_description += "AgcClippingLevelExperiment;";
1817 }
1818 if (capture_nonlocked_.echo_canceller3_enabled) {
1819 experiments_description += "EchoCanceller3;";
1820 }
1821
1822 InternalAPMConfig apm_config;
1823
1824 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1825 apm_config.aec_delay_agnostic_enabled =
1826 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1827 apm_config.aec_drift_compensation_enabled =
1828 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1829 apm_config.aec_extended_filter_enabled =
1830 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1831 apm_config.aec_suppression_level = static_cast<int>(
1832 public_submodules_->echo_cancellation->suppression_level());
1833
1834 apm_config.aecm_enabled =
1835 public_submodules_->echo_control_mobile->is_enabled();
1836 apm_config.aecm_comfort_noise_enabled =
1837 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1838 apm_config.aecm_routing_mode =
1839 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1840
1841 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1842 apm_config.agc_mode =
1843 static_cast<int>(public_submodules_->gain_control->mode());
1844 apm_config.agc_limiter_enabled =
1845 public_submodules_->gain_control->is_limiter_enabled();
1846 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1847
1848 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1849
1850 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1851 apm_config.ns_level =
1852 static_cast<int>(public_submodules_->noise_suppression->level());
1853
1854 apm_config.transient_suppression_enabled =
1855 capture_.transient_suppressor_enabled;
1856 apm_config.intelligibility_enhancer_enabled =
1857 capture_nonlocked_.intelligibility_enabled;
1858 apm_config.experiments_description = experiments_description;
1859
1860 if (!forced && apm_config == apm_config_for_aec_dump_) {
1861 return;
1862 }
1863 aec_dump_->WriteConfig(apm_config);
1864 apm_config_for_aec_dump_ = apm_config;
1865}
1866
1867void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1868 const float* const* src) {
1869 RTC_DCHECK(aec_dump_);
1870 WriteAecDumpConfigMessage(false);
1871
1872 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1873 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1874 aec_dump_->AddCaptureStreamInput(
1875 FloatAudioFrame(src, num_channels, channel_size));
1876 RecordAudioProcessingState();
1877}
1878
1879void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1880 const AudioFrame& capture_frame) {
1881 RTC_DCHECK(aec_dump_);
1882 WriteAecDumpConfigMessage(false);
1883
1884 aec_dump_->AddCaptureStreamInput(capture_frame);
1885 RecordAudioProcessingState();
1886}
1887
1888void AudioProcessingImpl::RecordProcessedCaptureStream(
1889 const float* const* processed_capture_stream) {
1890 RTC_DCHECK(aec_dump_);
1891
1892 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1893 const size_t num_channels =
1894 formats_.api_format.output_stream().num_channels();
1895 aec_dump_->AddCaptureStreamOutput(
1896 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
1897 aec_dump_->WriteCaptureStreamMessage();
1898}
1899
1900void AudioProcessingImpl::RecordProcessedCaptureStream(
1901 const AudioFrame& processed_capture_frame) {
1902 RTC_DCHECK(aec_dump_);
1903
1904 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1905 aec_dump_->WriteCaptureStreamMessage();
1906}
1907
1908void AudioProcessingImpl::RecordAudioProcessingState() {
1909 RTC_DCHECK(aec_dump_);
1910 AecDump::AudioProcessingState audio_proc_state;
1911 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
1912 audio_proc_state.drift =
1913 public_submodules_->echo_cancellation->stream_drift_samples();
1914 audio_proc_state.level = gain_control()->stream_analog_level();
1915 audio_proc_state.keypress = capture_.key_pressed;
1916 aec_dump_->AddAudioProcessingState(audio_proc_state);
1917}
1918
kwiberg83ffe452016-08-29 14:46:07 -07001919AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1920 bool transient_suppressor_enabled,
1921 const std::vector<Point>& array_geometry,
1922 SphericalPointf target_direction)
1923 : aec_system_delay_jumps(-1),
1924 delay_offset_ms(0),
1925 was_stream_delay_set(false),
1926 last_stream_delay_ms(0),
1927 last_aec_system_delay_ms(0),
1928 stream_delay_jumps(-1),
1929 output_will_be_muted(false),
1930 key_pressed(false),
1931 transient_suppressor_enabled(transient_suppressor_enabled),
1932 array_geometry(array_geometry),
1933 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001934 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001935 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001936 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07001937
1938AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1939
1940AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1941
1942AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1943
niklase@google.com470e71d2011-07-07 08:21:25 +00001944} // namespace webrtc