blob: 48c5107f2b2501d637c8ef66b7e2b8e3170656c0 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
22#include "modules/audio_processing/aec3/echo_canceller3.h"
23#include "modules/audio_processing/agc/agc_manager_direct.h"
24#include "modules/audio_processing/agc2/gain_controller2.h"
25#include "modules/audio_processing/audio_buffer.h"
26#include "modules/audio_processing/beamformer/nonlinear_beamformer.h"
27#include "modules/audio_processing/common.h"
28#include "modules/audio_processing/echo_cancellation_impl.h"
29#include "modules/audio_processing/echo_control_mobile_impl.h"
30#include "modules/audio_processing/gain_control_for_experimental_agc.h"
31#include "modules/audio_processing/gain_control_impl.h"
32#include "rtc_base/checks.h"
33#include "rtc_base/logging.h"
34#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020035#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070037#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070039#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "modules/audio_processing/level_controller/level_controller.h"
41#include "modules/audio_processing/level_estimator_impl.h"
42#include "modules/audio_processing/low_cut_filter.h"
43#include "modules/audio_processing/noise_suppression_impl.h"
44#include "modules/audio_processing/residual_echo_detector.h"
45#include "modules/audio_processing/transient/transient_suppressor.h"
46#include "modules/audio_processing/voice_detection_impl.h"
47#include "modules/include/module_common_types.h"
48#include "system_wrappers/include/file_wrapper.h"
49#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000050
peah1bcfce52016-08-26 07:16:04 -070051// Check to verify that the define for the intelligibility enhancer is properly
52// set.
53#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
54 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
55 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
56#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
57#endif
58
Michael Graczyk86c6d332015-07-23 11:41:39 -070059#define RETURN_ON_ERR(expr) \
60 do { \
61 int err = (expr); \
62 if (err != kNoError) { \
63 return err; \
64 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000065 } while (0)
66
niklase@google.com470e71d2011-07-07 08:21:25 +000067namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070068
kwibergd59d3bb2016-09-13 07:49:33 -070069constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070070
Michael Graczyk86c6d332015-07-23 11:41:39 -070071namespace {
72
73static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
74 switch (layout) {
75 case AudioProcessing::kMono:
76 case AudioProcessing::kStereo:
77 return false;
78 case AudioProcessing::kMonoAndKeyboard:
79 case AudioProcessing::kStereoAndKeyboard:
80 return true;
81 }
82
kwiberg9e2be5f2016-09-14 05:23:22 -070083 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070084 return false;
85}
aluebsdf6416a2016-03-16 18:26:35 -070086
peah2ace3f92016-09-10 04:42:27 -070087bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070088 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
89 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
90}
91
peah2ace3f92016-09-10 04:42:27 -070092int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
93#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070094 constexpr int kMaxSplittingNativeProcessRate =
95 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070096#else
kwibergd59d3bb2016-09-13 07:49:33 -070097 constexpr int kMaxSplittingNativeProcessRate =
98 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070099#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700100 static_assert(
101 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
102 "");
peah2ace3f92016-09-10 04:42:27 -0700103 const int uppermost_native_rate = band_splitting_required
104 ? kMaxSplittingNativeProcessRate
105 : AudioProcessing::kSampleRate48kHz;
106
107 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
108 if (rate >= uppermost_native_rate) {
109 return uppermost_native_rate;
110 }
111 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700112 return rate;
113 }
114 }
peah2ace3f92016-09-10 04:42:27 -0700115 RTC_NOTREACHED();
116 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700117}
118
peah9e6a2902017-05-15 07:19:21 -0700119// Maximum lengths that frame of samples being passed from the render side to
120// the capture side can have (does not apply to AEC3).
121static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
122static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum number of frames to buffer in the render queue.
125// TODO(peah): Decrease this once we properly handle hugely unbalanced
126// reverse and forward call numbers.
127static const size_t kMaxNumFramesToBuffer = 100;
128
peah8271d042016-11-22 07:24:52 -0800129class HighPassFilterImpl : public HighPassFilter {
130 public:
131 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
132 ~HighPassFilterImpl() override = default;
133
134 // HighPassFilter implementation.
135 int Enable(bool enable) override {
136 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
137 config->high_pass_filter.enabled = enable;
138 });
139
140 return AudioProcessing::kNoError;
141 }
142
143 bool is_enabled() const override {
144 return apm_->GetConfig().high_pass_filter.enabled;
145 }
146
147 private:
148 AudioProcessingImpl* apm_;
149 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
150};
151
aleloi868f32f2017-05-23 07:20:05 -0700152webrtc::InternalAPMStreamsConfig ToStreamsConfig(
153 const ProcessingConfig& api_format) {
154 webrtc::InternalAPMStreamsConfig result;
155 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
156 result.input_num_channels = api_format.input_stream().num_channels();
157 result.output_num_channels = api_format.output_stream().num_channels();
158 result.render_input_num_channels =
159 api_format.reverse_input_stream().num_channels();
160 result.render_input_sample_rate =
161 api_format.reverse_input_stream().sample_rate_hz();
162 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
163 result.render_output_sample_rate =
164 api_format.reverse_output_stream().sample_rate_hz();
165 result.render_output_num_channels =
166 api_format.reverse_output_stream().num_channels();
167 return result;
168}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700169} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000170
171// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000172static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000173
Sam Zackrisson0beac582017-09-25 12:04:02 +0200174AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
175 bool capture_post_processor_enabled)
176 : capture_post_processor_enabled_(capture_post_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700177
178bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800179 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700180 bool echo_canceller_enabled,
181 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700182 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700183 bool noise_suppressor_enabled,
184 bool intelligibility_enhancer_enabled,
185 bool beamformer_enabled,
186 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700187 bool gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -0700188 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800189 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700190 bool voice_activity_detector_enabled,
191 bool level_estimator_enabled,
192 bool transient_suppressor_enabled) {
193 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800194 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700195 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
196 changed |=
197 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700198 changed |=
199 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700200 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
201 changed |=
202 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
203 changed |= (beamformer_enabled != beamformer_enabled_);
204 changed |=
205 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700206 changed |=
207 (gain_controller2_enabled != gain_controller2_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700208 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800209 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700210 changed |= (level_estimator_enabled != level_estimator_enabled_);
211 changed |=
212 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
213 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
214 if (changed) {
peah8271d042016-11-22 07:24:52 -0800215 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700216 echo_canceller_enabled_ = echo_canceller_enabled;
217 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700218 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700219 noise_suppressor_enabled_ = noise_suppressor_enabled;
220 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
221 beamformer_enabled_ = beamformer_enabled;
222 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700223 gain_controller2_enabled_ = gain_controller2_enabled;
peah2ace3f92016-09-10 04:42:27 -0700224 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800225 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700226 level_estimator_enabled_ = level_estimator_enabled;
227 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
228 transient_suppressor_enabled_ = transient_suppressor_enabled;
229 }
230
231 changed |= first_update_;
232 first_update_ = false;
233 return changed;
234}
235
236bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
237 const {
238#if WEBRTC_INTELLIGIBILITY_ENHANCER
239 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700240 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700241#else
peah52775842017-05-16 06:14:09 -0700242 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700243#endif
244}
245
246bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
247 const {
peah8271d042016-11-22 07:24:52 -0800248 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700249 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800250 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
251 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700252}
253
peah23ac8b42017-05-23 05:33:56 -0700254bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
255 const {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200256 return level_controller_enabled_ || capture_post_processor_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700257}
258
peah2ace3f92016-09-10 04:42:27 -0700259bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
260 const {
261 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800262 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peah52775842017-05-16 06:14:09 -0700263 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700264}
265
266bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
267 const {
268#if WEBRTC_INTELLIGIBILITY_ENHANCER
269 return intelligibility_enhancer_enabled_;
270#else
271 return false;
272#endif
273}
274
solenberg5e465c32015-12-08 13:22:33 -0800275struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800276 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800277 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800278 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800279 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800280 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800281 std::unique_ptr<LevelEstimatorImpl> level_estimator;
282 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
283 std::unique_ptr<VoiceDetectionImpl> voice_detection;
284 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800285 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800286
287 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800288 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700289#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800290 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700291#endif
solenberg5e465c32015-12-08 13:22:33 -0800292};
293
294struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200295 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
296 std::unique_ptr<PostProcessing> capture_post_processor)
297 : beamformer(beamformer),
298 capture_post_processor(std::move(capture_post_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800299 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700300 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800301 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700302 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800303 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700304 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700305 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
Gustaf Ullbergc5222982017-10-05 10:25:05 +0200306 std::unique_ptr<EchoControl> echo_canceller3;
Sam Zackrisson0beac582017-09-25 12:04:02 +0200307 std::unique_ptr<PostProcessing> capture_post_processor;
solenberg5e465c32015-12-08 13:22:33 -0800308};
309
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000310AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700311 webrtc::Config config;
Sam Zackrisson0beac582017-09-25 12:04:02 +0200312 return Create(config, nullptr, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000313}
314
peah88ac8532016-09-12 16:47:25 -0700315AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200316 return Create(config, nullptr, nullptr);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000317}
318
peah88ac8532016-09-12 16:47:25 -0700319AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700320 NonlinearBeamformer* beamformer) {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200321 return Create(config, nullptr, beamformer);
322}
323
324AudioProcessing* AudioProcessing::Create(
325 const webrtc::Config& config,
326 std::unique_ptr<PostProcessing> capture_post_processor,
327 NonlinearBeamformer* beamformer) {
328 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
329 config, std::move(capture_post_processor), beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000330 if (apm->Initialize() != kNoError) {
331 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800332 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000333 }
334
335 return apm;
336}
337
peah88ac8532016-09-12 16:47:25 -0700338AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200339 : AudioProcessingImpl(config, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000340
Sam Zackrisson0beac582017-09-25 12:04:02 +0200341AudioProcessingImpl::AudioProcessingImpl(
342 const webrtc::Config& config,
343 std::unique_ptr<PostProcessing> capture_post_processor,
344 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800345 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200346 submodule_states_(!!capture_post_processor),
peah8271d042016-11-22 07:24:52 -0800347 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200348 private_submodules_(
349 new ApmPrivateSubmodules(beamformer,
350 std::move(capture_post_processor))),
peahdf3efa82015-11-28 12:35:15 -0800351 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800352 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000353#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700354 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000355#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700356 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000357#endif
andrew1c7075f2015-06-24 18:14:14 -0700358#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800359 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700360#else
aluebs2a346882016-01-11 18:04:30 -0800361 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700362#endif
aluebs2a346882016-01-11 18:04:30 -0800363 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800364 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700365 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700366 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800367 {
368 rtc::CritScope cs_render(&crit_render_);
369 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000370
peahb624d8c2016-03-05 03:01:14 -0800371 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700372 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800373 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700374 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800375 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700376 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800377 public_submodules_->level_estimator.reset(
378 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800379 public_submodules_->noise_suppression.reset(
380 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800381 public_submodules_->voice_detection.reset(
382 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800383 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800384 new GainControlForExperimentalAgc(
385 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700386 private_submodules_->residual_echo_detector.reset(
387 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700388
peahc19f3122016-10-07 14:54:10 -0700389 // TODO(peah): Move this creation to happen only when the level controller
390 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700391 private_submodules_->level_controller.reset(new LevelController());
Sam Zackrisson0beac582017-09-25 12:04:02 +0200392
393 LOG(LS_INFO) << "Capture post processor activated: "
394 << !!private_submodules_->capture_post_processor;
peahdf3efa82015-11-28 12:35:15 -0800395 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000396
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000397 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000398}
399
400AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800401 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800402 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800403 private_submodules_->agc_manager.reset();
404 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800405 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000406}
407
niklase@google.com470e71d2011-07-07 08:21:25 +0000408int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800409 // Run in a single-threaded manner during initialization.
410 rtc::CritScope cs_render(&crit_render_);
411 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000412 return InitializeLocked();
413}
414
peahde65ddc2016-09-16 15:02:15 -0700415int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
416 int capture_output_sample_rate_hz,
417 int render_input_sample_rate_hz,
418 ChannelLayout capture_input_layout,
419 ChannelLayout capture_output_layout,
420 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700421 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700422 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
423 LayoutHasKeyboard(capture_input_layout)},
424 {capture_output_sample_rate_hz,
425 ChannelsFromLayout(capture_output_layout),
426 LayoutHasKeyboard(capture_output_layout)},
427 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
428 LayoutHasKeyboard(render_input_layout)},
429 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
430 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700431
432 return Initialize(processing_config);
433}
434
435int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800436 // Run in a single-threaded manner during initialization.
437 rtc::CritScope cs_render(&crit_render_);
438 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700439 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000440}
441
peahdf3efa82015-11-28 12:35:15 -0800442int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800443 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700444 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800445}
446
peahdf3efa82015-11-28 12:35:15 -0800447int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700448 const ProcessingConfig& processing_config,
449 bool force_initialization) {
450 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800451}
452
peah192164e2015-11-17 02:16:45 -0800453// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800454// their current values (needs to be called while holding the crit_render_lock).
455int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700456 const ProcessingConfig& processing_config,
457 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800458 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700459 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800460 return kNoError;
461 }
peahdf3efa82015-11-28 12:35:15 -0800462
463 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800464 return InitializeLocked(processing_config);
465}
466
niklase@google.com470e71d2011-07-07 08:21:25 +0000467int AudioProcessingImpl::InitializeLocked() {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200468 UpdateActiveSubmoduleStates();
469
peah522d71b2017-02-23 05:16:26 -0800470 const int capture_audiobuffer_num_channels =
471 capture_nonlocked_.beamformer_enabled
472 ? formats_.api_format.input_stream().num_channels()
473 : formats_.api_format.output_stream().num_channels();
474
peahde65ddc2016-09-16 15:02:15 -0700475 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800476 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700477 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800478 : formats_.api_format.reverse_output_stream().num_frames();
479 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
480 render_.render_audio.reset(new AudioBuffer(
481 formats_.api_format.reverse_input_stream().num_frames(),
482 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700483 formats_.render_processing_format.num_frames(),
484 formats_.render_processing_format.num_channels(),
485 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700486 if (formats_.api_format.reverse_input_stream() !=
487 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800488 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800489 formats_.api_format.reverse_input_stream().num_channels(),
490 formats_.api_format.reverse_input_stream().num_frames(),
491 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800492 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700493 } else {
peahdf3efa82015-11-28 12:35:15 -0800494 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700495 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700496 } else {
peahdf3efa82015-11-28 12:35:15 -0800497 render_.render_audio.reset(nullptr);
498 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700499 }
peahce4d9152017-05-19 01:28:05 -0700500
peahdf3efa82015-11-28 12:35:15 -0800501 capture_.capture_audio.reset(
502 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
503 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700504 capture_nonlocked_.capture_processing_format.num_frames(),
505 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800506 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000507
peahde65ddc2016-09-16 15:02:15 -0700508 public_submodules_->echo_cancellation->Initialize(
509 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
510 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700511 AllocateRenderQueue();
512
ivoc3e9a5372016-10-28 07:55:33 -0700513 int success = public_submodules_->echo_cancellation->enable_metrics(true);
514 RTC_DCHECK_EQ(0, success);
515 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
516 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700517 public_submodules_->echo_control_mobile->Initialize(
518 proc_split_sample_rate_hz(), num_reverse_channels(),
519 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700520
521 public_submodules_->gain_control->Initialize(num_proc_channels(),
522 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700523 if (constants_.use_experimental_agc) {
524 if (!private_submodules_->agc_manager.get()) {
525 private_submodules_->agc_manager.reset(new AgcManagerDirect(
526 public_submodules_->gain_control.get(),
527 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800528 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700529 }
530 private_submodules_->agc_manager->Initialize();
531 private_submodules_->agc_manager->SetCaptureMuted(
532 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700533 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700534 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200535 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000536 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700537#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700538 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700539#endif
peah8271d042016-11-22 07:24:52 -0800540 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700541 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
542 proc_sample_rate_hz());
543 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
544 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700545 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700546 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800547 InitializeEchoCanceller3();
alessiob3ec96df2017-05-22 06:57:06 -0700548 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200549 InitializePostProcessor();
solenberg70f99032015-12-08 11:07:32 -0800550
aleloi868f32f2017-05-23 07:20:05 -0700551 if (aec_dump_) {
552 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
553 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000554 return kNoError;
555}
556
Michael Graczyk86c6d332015-07-23 11:41:39 -0700557int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200558 UpdateActiveSubmoduleStates();
559
Michael Graczyk86c6d332015-07-23 11:41:39 -0700560 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700561 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
562 return kBadSampleRateError;
563 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000564 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700565
Peter Kasting69558702016-01-12 16:26:35 -0800566 const size_t num_in_channels = config.input_stream().num_channels();
567 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700568
569 // Need at least one input channel.
570 // Need either one output channel or as many outputs as there are inputs.
571 if (num_in_channels == 0 ||
572 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700573 return kBadNumberChannelsError;
574 }
575
aluebsb2328d12016-01-11 20:32:29 -0800576 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800577 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700578 return kBadNumberChannelsError;
579 }
580
peahdf3efa82015-11-28 12:35:15 -0800581 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000582
peahde65ddc2016-09-16 15:02:15 -0700583 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700584 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700585 formats_.api_format.output_stream().sample_rate_hz()),
586 submodule_states_.CaptureMultiBandSubModulesActive() ||
587 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000588
peahde65ddc2016-09-16 15:02:15 -0700589 capture_nonlocked_.capture_processing_format =
590 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700591
peah2ce640f2017-04-07 03:57:48 -0700592 int render_processing_rate;
593 if (!config_.echo_canceller3.enabled) {
594 render_processing_rate = FindNativeProcessRateToUse(
595 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
596 formats_.api_format.reverse_output_stream().sample_rate_hz()),
597 submodule_states_.CaptureMultiBandSubModulesActive() ||
598 submodule_states_.RenderMultiBandSubModulesActive());
599 } else {
600 render_processing_rate = capture_processing_rate;
601 }
602
aluebseb3603b2016-04-20 15:27:58 -0700603 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
604 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700605 if (render_processing_rate > kSampleRate32kHz &&
606 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700607 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
608 ? kSampleRate32kHz
609 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700610 }
peah2ce640f2017-04-07 03:57:48 -0700611
peahde65ddc2016-09-16 15:02:15 -0700612 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700613 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700614 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
615 kSampleRate8kHz) {
616 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000617 } else {
peahde65ddc2016-09-16 15:02:15 -0700618 render_processing_rate =
619 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000620 }
621
peahde65ddc2016-09-16 15:02:15 -0700622 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000623 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700624 if (submodule_states_.RenderMultiBandSubModulesActive()) {
625 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
626 } else {
627 formats_.render_processing_format = StreamConfig(
628 formats_.api_format.reverse_input_stream().sample_rate_hz(),
629 formats_.api_format.reverse_input_stream().num_channels());
630 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000631
peahde65ddc2016-09-16 15:02:15 -0700632 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
633 kSampleRate32kHz ||
634 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
635 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800636 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000637 } else {
peahdf3efa82015-11-28 12:35:15 -0800638 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700639 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000640 }
641
642 return InitializeLocked();
643}
644
peah88ac8532016-09-12 16:47:25 -0700645void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700646 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700647
peahc19f3122016-10-07 14:54:10 -0700648 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700649 if (!config_ok) {
650 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
651 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700652 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700653 << std::endl
654 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700655 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700656 }
657
658 // Run in a single-threaded manner when applying the settings.
659 rtc::CritScope cs_render(&crit_render_);
660 rtc::CritScope cs_capture(&crit_capture_);
661
peahc19f3122016-10-07 14:54:10 -0700662 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
663 // with the value in config_ everywhere in the code.
664 if (capture_nonlocked_.level_controller_enabled !=
665 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700666 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700667 config_.level_controller.enabled;
668 // TODO(peah): Remove the conditional initialization to always initialize
669 // the level controller regardless of whether it is enabled or not.
670 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700671 }
peahc19f3122016-10-07 14:54:10 -0700672 LOG(LS_INFO) << "Level controller activated: "
673 << capture_nonlocked_.level_controller_enabled;
674
675 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800676
677 InitializeLowCutFilter();
678
679 LOG(LS_INFO) << "Highpass filter activated: "
680 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800681
682 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
683 if (!config_ok) {
684 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
685 << "echo canceller 3: "
686 << EchoCanceller3::ToString(config_.echo_canceller3)
687 << std::endl
688 << "Reverting to default parameter set";
689 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
690 }
691
692 if (config.echo_canceller3.enabled !=
693 capture_nonlocked_.echo_canceller3_enabled) {
694 capture_nonlocked_.echo_canceller3_enabled =
695 config_.echo_canceller3.enabled;
696 InitializeEchoCanceller3();
697 LOG(LS_INFO) << "Echo canceller 3 activated: "
698 << capture_nonlocked_.echo_canceller3_enabled;
699 }
alessiob3ec96df2017-05-22 06:57:06 -0700700
701 config_ok = GainController2::Validate(config_.gain_controller2);
702 if (!config_ok) {
703 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
704 << "gain_controller2: "
705 << GainController2::ToString(config_.gain_controller2)
706 << std::endl
707 << "Reverting to default parameter set";
708 config_.gain_controller2 = AudioProcessing::Config::GainController2();
709 }
710
711 if (config.gain_controller2.enabled !=
712 capture_nonlocked_.gain_controller2_enabled) {
713 capture_nonlocked_.gain_controller2_enabled =
714 config_.gain_controller2.enabled;
715 InitializeGainController2();
716 LOG(LS_INFO) << "Gain controller 2 activated: "
717 << capture_nonlocked_.gain_controller2_enabled;
718 }
peah88ac8532016-09-12 16:47:25 -0700719}
720
721void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800722 // Run in a single-threaded manner when setting the extra options.
723 rtc::CritScope cs_render(&crit_render_);
724 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000725
peahb624d8c2016-03-05 03:01:14 -0800726 public_submodules_->echo_cancellation->SetExtraOptions(config);
727
peahdf3efa82015-11-28 12:35:15 -0800728 if (capture_.transient_suppressor_enabled !=
729 config.Get<ExperimentalNs>().enabled) {
730 capture_.transient_suppressor_enabled =
731 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000732 InitializeTransient();
733 }
aluebs2a346882016-01-11 18:04:30 -0800734
peah1bcfce52016-08-26 07:16:04 -0700735#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700736 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700737 config.Get<Intelligibility>().enabled) {
738 capture_nonlocked_.intelligibility_enabled =
739 config.Get<Intelligibility>().enabled;
740 InitializeIntelligibility();
741 }
peah1bcfce52016-08-26 07:16:04 -0700742#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700743
aluebs2a346882016-01-11 18:04:30 -0800744#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800745 if (capture_nonlocked_.beamformer_enabled !=
746 config.Get<Beamforming>().enabled) {
747 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800748 if (config.Get<Beamforming>().array_geometry.size() > 1) {
749 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
750 }
751 capture_.target_direction = config.Get<Beamforming>().target_direction;
752 InitializeBeamformer();
753 }
754#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000755}
756
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000757int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800758 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700759 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000760}
761
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000762int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800763 // Used as callback from submodules, hence locking is not allowed.
764 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000765}
766
Peter Kasting69558702016-01-12 16:26:35 -0800767size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800768 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700769 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000770}
771
Peter Kasting69558702016-01-12 16:26:35 -0800772size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800773 // Used as callback from submodules, hence locking is not allowed.
774 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000775}
776
Peter Kasting69558702016-01-12 16:26:35 -0800777size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800778 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700779 return (capture_nonlocked_.beamformer_enabled ||
780 capture_nonlocked_.echo_canceller3_enabled)
781 ? 1
782 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800783}
784
Peter Kasting69558702016-01-12 16:26:35 -0800785size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800786 // Used as callback from submodules, hence locking is not allowed.
787 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000788}
789
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000790void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800791 rtc::CritScope cs(&crit_capture_);
792 capture_.output_will_be_muted = muted;
793 if (private_submodules_->agc_manager.get()) {
794 private_submodules_->agc_manager->SetCaptureMuted(
795 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000796 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000797}
798
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000799
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000800int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700801 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000802 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000803 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000804 int output_sample_rate_hz,
805 ChannelLayout output_layout,
806 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800807 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800808 StreamConfig input_stream;
809 StreamConfig output_stream;
810 {
811 // Access the formats_.api_format.input_stream beneath the capture lock.
812 // The lock must be released as it is later required in the call
813 // to ProcessStream(,,,);
814 rtc::CritScope cs(&crit_capture_);
815 input_stream = formats_.api_format.input_stream();
816 output_stream = formats_.api_format.output_stream();
817 }
818
Michael Graczyk86c6d332015-07-23 11:41:39 -0700819 input_stream.set_sample_rate_hz(input_sample_rate_hz);
820 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
821 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700822 output_stream.set_sample_rate_hz(output_sample_rate_hz);
823 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
824 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
825
826 if (samples_per_channel != input_stream.num_frames()) {
827 return kBadDataLengthError;
828 }
829 return ProcessStream(src, input_stream, output_stream, dest);
830}
831
832int AudioProcessingImpl::ProcessStream(const float* const* src,
833 const StreamConfig& input_config,
834 const StreamConfig& output_config,
835 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800836 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800837 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700838 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800839 {
840 // Acquire the capture lock in order to safely call the function
841 // that retrieves the render side data. This function accesses apm
842 // getters that need the capture lock held when being called.
843 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700844 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800845
846 if (!src || !dest) {
847 return kNullPointerError;
848 }
849
850 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700851 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000852 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000853
Michael Graczyk86c6d332015-07-23 11:41:39 -0700854 processing_config.input_stream() = input_config;
855 processing_config.output_stream() = output_config;
856
peahdf3efa82015-11-28 12:35:15 -0800857 {
858 // Do conditional reinitialization.
859 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700860 RETURN_ON_ERR(
861 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800862 }
863 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700864 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
865 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000866
aleloi868f32f2017-05-23 07:20:05 -0700867 if (aec_dump_) {
868 RecordUnprocessedCaptureStream(src);
869 }
870
peahdf3efa82015-11-28 12:35:15 -0800871 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700872 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800873 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000874
aleloi868f32f2017-05-23 07:20:05 -0700875 if (aec_dump_) {
876 RecordProcessedCaptureStream(dest);
877 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000878 return kNoError;
879}
880
peah9e6a2902017-05-15 07:19:21 -0700881void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700882 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
883 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700884 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700885
kwibergaf476c72016-11-28 15:21:39 -0800886 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700887
888 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700889 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700890 // The data queue is full and needs to be emptied.
891 EmptyQueuedRenderAudio();
892
893 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700894 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700895 RTC_DCHECK(result);
896 }
897
898 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
899 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700900 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700901
902 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700903 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700904 // The data queue is full and needs to be emptied.
905 EmptyQueuedRenderAudio();
906
907 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700908 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700909 RTC_DCHECK(result);
910 }
peah701d6282016-10-25 05:42:20 -0700911
912 if (!constants_.use_experimental_agc) {
913 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
914 // Insert the samples into the queue.
915 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
916 // The data queue is full and needs to be emptied.
917 EmptyQueuedRenderAudio();
918
919 // Retry the insert (should always work).
920 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
921 RTC_DCHECK(result);
922 }
923 }
peah9e6a2902017-05-15 07:19:21 -0700924}
ivoc9f4a4a02016-10-28 05:39:16 -0700925
peah9e6a2902017-05-15 07:19:21 -0700926void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700927 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
928
929 // Insert the samples into the queue.
930 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
931 // The data queue is full and needs to be emptied.
932 EmptyQueuedRenderAudio();
933
934 // Retry the insert (should always work).
935 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
936 RTC_DCHECK(result);
937 }
peah764e3642016-10-22 05:04:30 -0700938}
939
940void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700941 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700942 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700943 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700944 EchoCancellationImpl::NumCancellersRequired(
945 num_output_channels(), num_reverse_channels()));
946
peah701d6282016-10-25 05:42:20 -0700947 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700948 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700949 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700950 EchoControlMobileImpl::NumCancellersRequired(
951 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700952
peah701d6282016-10-25 05:42:20 -0700953 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700954 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700955
ivoc9f4a4a02016-10-28 05:39:16 -0700956 const size_t new_red_render_queue_element_max_size =
957 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
958
peaha0624602016-10-25 04:45:24 -0700959 // Reallocate the queues if the queue item sizes are too small to fit the
960 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700961 if (aec_render_queue_element_max_size_ <
962 new_aec_render_queue_element_max_size) {
963 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700964
peaha0624602016-10-25 04:45:24 -0700965 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700966 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700967
peah701d6282016-10-25 05:42:20 -0700968 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700969 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
970 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700971 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700972 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700973
peah701d6282016-10-25 05:42:20 -0700974 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
975 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700976 } else {
peah701d6282016-10-25 05:42:20 -0700977 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700978 }
979
peah701d6282016-10-25 05:42:20 -0700980 if (aecm_render_queue_element_max_size_ <
981 new_aecm_render_queue_element_max_size) {
982 aecm_render_queue_element_max_size_ =
983 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700984
985 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700986 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700987
peah701d6282016-10-25 05:42:20 -0700988 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700989 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
990 kMaxNumFramesToBuffer, template_queue_element,
991 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700992 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700993
peah701d6282016-10-25 05:42:20 -0700994 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
995 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700996 } else {
peah701d6282016-10-25 05:42:20 -0700997 aecm_render_signal_queue_->Clear();
998 }
999
1000 if (agc_render_queue_element_max_size_ <
1001 new_agc_render_queue_element_max_size) {
1002 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1003
1004 std::vector<int16_t> template_queue_element(
1005 agc_render_queue_element_max_size_);
1006
1007 agc_render_signal_queue_.reset(
1008 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1009 kMaxNumFramesToBuffer, template_queue_element,
1010 RenderQueueItemVerifier<int16_t>(
1011 agc_render_queue_element_max_size_)));
1012
1013 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1014 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1015 } else {
1016 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001017 }
ivoc9f4a4a02016-10-28 05:39:16 -07001018
1019 if (red_render_queue_element_max_size_ <
1020 new_red_render_queue_element_max_size) {
1021 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1022
1023 std::vector<float> template_queue_element(
1024 red_render_queue_element_max_size_);
1025
1026 red_render_signal_queue_.reset(
1027 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1028 kMaxNumFramesToBuffer, template_queue_element,
1029 RenderQueueItemVerifier<float>(
1030 red_render_queue_element_max_size_)));
1031
1032 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1033 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1034 } else {
1035 red_render_signal_queue_->Clear();
1036 }
peah764e3642016-10-22 05:04:30 -07001037}
1038
1039void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1040 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001041 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001042 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001043 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001044 }
1045
peah701d6282016-10-25 05:42:20 -07001046 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001047 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001048 aecm_capture_queue_buffer_);
1049 }
1050
1051 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1052 public_submodules_->gain_control->ProcessRenderAudio(
1053 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001054 }
ivoc9f4a4a02016-10-28 05:39:16 -07001055
1056 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1057 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1058 red_capture_queue_buffer_);
1059 }
peah764e3642016-10-22 05:04:30 -07001060}
1061
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001062int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001063 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001064 {
1065 // Acquire the capture lock in order to safely call the function
1066 // that retrieves the render side data. This function accesses apm
1067 // getters that need the capture lock held when being called.
1068 // The lock needs to be released as
1069 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1070 // as well.
1071 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001072 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001073 }
peahfa6228e2015-11-16 16:27:42 -08001074
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001075 if (!frame) {
1076 return kNullPointerError;
1077 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001078 // Must be a native rate.
1079 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1080 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001081 frame->sample_rate_hz_ != kSampleRate32kHz &&
1082 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001083 return kBadSampleRateError;
1084 }
peah192164e2015-11-17 02:16:45 -08001085
peahdf3efa82015-11-28 12:35:15 -08001086 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001087 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001088 {
1089 // Aquire lock for the access of api_format.
1090 // The lock is released immediately due to the conditional
1091 // reinitialization.
1092 rtc::CritScope cs_capture(&crit_capture_);
1093 // TODO(ajm): The input and output rates and channels are currently
1094 // constrained to be identical in the int16 interface.
1095 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001096
1097 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001098 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001099 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1100 processing_config.input_stream().set_num_channels(frame->num_channels_);
1101 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1102 processing_config.output_stream().set_num_channels(frame->num_channels_);
1103
peahdf3efa82015-11-28 12:35:15 -08001104 {
1105 // Do conditional reinitialization.
1106 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001107 RETURN_ON_ERR(
1108 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001109 }
1110 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001111 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001112 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001113 return kBadDataLengthError;
1114 }
1115
aleloi868f32f2017-05-23 07:20:05 -07001116 if (aec_dump_) {
1117 RecordUnprocessedCaptureStream(*frame);
1118 }
1119
peahdf3efa82015-11-28 12:35:15 -08001120 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001121 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001122 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001123 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1124 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001125
aleloi868f32f2017-05-23 07:20:05 -07001126 if (aec_dump_) {
1127 RecordProcessedCaptureStream(*frame);
1128 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001129
1130 return kNoError;
1131}
1132
peahde65ddc2016-09-16 15:02:15 -07001133int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001134 // Ensure that not both the AEC and AECM are active at the same time.
1135 // TODO(peah): Simplify once the public API Enable functions for these
1136 // are moved to APM.
1137 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1138 public_submodules_->echo_control_mobile->is_enabled()));
1139
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001140 MaybeUpdateHistograms();
1141
peahde65ddc2016-09-16 15:02:15 -07001142 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001143
peah1b08dc32016-12-20 13:45:58 -08001144 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001145 capture_buffer->channels_const()[0],
1146 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001147 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1148 if (log_rms) {
1149 capture_rms_interval_counter_ = 0;
1150 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001151 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1152 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1153 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1154 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001155 }
1156
peahe0eae3c2016-12-14 01:16:23 -08001157 if (private_submodules_->echo_canceller3) {
Per Ã…hgren9aed31c2017-06-29 20:23:27 +02001158 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1159 // issues have been addressed.
1160 capture_.echo_path_gain_change = false;
peahe0eae3c2016-12-14 01:16:23 -08001161 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1162 }
1163
peahbe615622016-02-13 16:40:47 -08001164 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001165 public_submodules_->gain_control->is_enabled()) {
1166 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001167 capture_buffer->channels()[0], capture_buffer->num_channels(),
1168 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001169 }
1170
peah2ace3f92016-09-10 04:42:27 -07001171 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1172 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001173 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1174 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001175 }
1176
peah522d71b2017-02-23 05:16:26 -08001177 if (private_submodules_->echo_canceller3) {
1178 // Force down-mixing of the number of channels after the detection of
1179 // capture signal saturation.
1180 // TODO(peah): Look into ensuring that this kind of tampering with the
1181 // AudioBuffer functionality should not be needed.
1182 capture_buffer->set_num_channels(1);
1183 }
1184
aluebsb2328d12016-01-11 20:32:29 -08001185 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001186 private_submodules_->beamformer->AnalyzeChunk(
1187 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001188 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001189 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001190 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001191
peahe0eae3c2016-12-14 01:16:23 -08001192 // TODO(peah): Move the AEC3 low-cut filter to this place.
1193 if (private_submodules_->low_cut_filter &&
1194 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001195 private_submodules_->low_cut_filter->Process(capture_buffer);
1196 }
peahde65ddc2016-09-16 15:02:15 -07001197 RETURN_ON_ERR(
1198 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1199 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001200
1201 // Ensure that the stream delay was set before the call to the
1202 // AEC ProcessCaptureAudio function.
1203 if (public_submodules_->echo_cancellation->is_enabled() &&
1204 !was_stream_delay_set()) {
1205 return AudioProcessing::kStreamParameterNotSetError;
1206 }
1207
peahe0eae3c2016-12-14 01:16:23 -08001208 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001209 private_submodules_->echo_canceller3->ProcessCapture(
1210 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001211 } else {
1212 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1213 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001214 }
1215
peahdf3efa82015-11-28 12:35:15 -08001216 if (public_submodules_->echo_control_mobile->is_enabled() &&
1217 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001218 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001219 }
peahde65ddc2016-09-16 15:02:15 -07001220 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001221#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001222 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001223 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001224 int gain_db = public_submodules_->gain_control->is_enabled() ?
1225 public_submodules_->gain_control->compression_gain_db() :
1226 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001227 float gain = std::pow(10.f, gain_db / 20.f);
1228 gain *= capture_nonlocked_.level_controller_enabled ?
1229 private_submodules_->level_controller->GetLastGain() :
1230 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001231 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001232 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001233 }
peah1bcfce52016-08-26 07:16:04 -07001234#endif
peah253534d2016-03-15 04:32:28 -07001235
1236 // Ensure that the stream delay was set before the call to the
1237 // AECM ProcessCaptureAudio function.
1238 if (public_submodules_->echo_control_mobile->is_enabled() &&
1239 !was_stream_delay_set()) {
1240 return AudioProcessing::kStreamParameterNotSetError;
1241 }
1242
Per Ã…hgren46537a32017-06-07 10:08:10 +02001243 if (!(private_submodules_->echo_canceller3 ||
1244 public_submodules_->echo_cancellation->is_enabled())) {
1245 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1246 capture_buffer, stream_delay_ms()));
1247 }
ivoc9f4a4a02016-10-28 05:39:16 -07001248
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001249 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001250 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001251 }
1252
peahde65ddc2016-09-16 15:02:15 -07001253 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001254
peahbe615622016-02-13 16:40:47 -08001255 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001256 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001257 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001258 private_submodules_->beamformer->is_target_present())) {
1259 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001260 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1261 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001262 }
peahb8fbb542016-03-15 02:28:08 -07001263 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001264 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001265
peah2ace3f92016-09-10 04:42:27 -07001266 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1267 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001268 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1269 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001270 }
1271
peah9e6a2902017-05-15 07:19:21 -07001272 if (config_.residual_echo_detector.enabled) {
1273 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1274 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1275 capture_buffer->num_frames()));
1276 }
1277
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001278 // TODO(aluebs): Investigate if the transient suppression placement should be
1279 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001280 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001281 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001282 private_submodules_->agc_manager.get()
1283 ? private_submodules_->agc_manager->voice_probability()
1284 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001285
peahdf3efa82015-11-28 12:35:15 -08001286 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001287 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1288 capture_buffer->num_channels(),
1289 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1290 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1291 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001292 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001293 }
1294
alessiob3ec96df2017-05-22 06:57:06 -07001295 if (capture_nonlocked_.gain_controller2_enabled) {
1296 private_submodules_->gain_controller2->Process(capture_buffer);
1297 }
1298
peahca4cac72016-06-29 15:26:12 -07001299 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001300 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001301 }
1302
Sam Zackrisson0beac582017-09-25 12:04:02 +02001303 if (private_submodules_->capture_post_processor) {
1304 private_submodules_->capture_post_processor->Process(capture_buffer);
1305 }
1306
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001307 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001308 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001309
peah1b08dc32016-12-20 13:45:58 -08001310 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1311 capture_buffer->channels_const()[0],
1312 capture_nonlocked_.capture_processing_format.num_frames()));
1313 if (log_rms) {
1314 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1315 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1316 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1317 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1318 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1319 }
1320
peahdf3efa82015-11-28 12:35:15 -08001321 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001322 return kNoError;
1323}
1324
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001325int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001326 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001327 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001328 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001329 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001330 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001331 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001332 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001333 };
1334 if (samples_per_channel != reverse_config.num_frames()) {
1335 return kBadDataLengthError;
1336 }
peahdf3efa82015-11-28 12:35:15 -08001337 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001338}
1339
peahde65ddc2016-09-16 15:02:15 -07001340int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1341 const StreamConfig& input_config,
1342 const StreamConfig& output_config,
1343 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001344 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001345 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001346 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001347 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001348 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1349 dest);
peah2ace3f92016-09-10 04:42:27 -07001350 } else if (formats_.api_format.reverse_input_stream() !=
1351 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001352 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1353 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001354 } else {
peahde65ddc2016-09-16 15:02:15 -07001355 CopyAudioIfNeeded(src, input_config.num_frames(),
1356 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001357 }
1358
1359 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001360}
1361
peahdf3efa82015-11-28 12:35:15 -08001362int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001363 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001364 const StreamConfig& input_config,
1365 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001366 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001367 return kNullPointerError;
1368 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001369
peahde65ddc2016-09-16 15:02:15 -07001370 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001371 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001372 }
1373
peahdf3efa82015-11-28 12:35:15 -08001374 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001375 processing_config.reverse_input_stream() = input_config;
1376 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001377
peahdf3efa82015-11-28 12:35:15 -08001378 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001379 assert(input_config.num_frames() ==
1380 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001381
aleloi868f32f2017-05-23 07:20:05 -07001382 if (aec_dump_) {
1383 const size_t channel_size =
1384 formats_.api_format.reverse_input_stream().num_frames();
1385 const size_t num_channels =
1386 formats_.api_format.reverse_input_stream().num_channels();
1387 aec_dump_->WriteRenderStreamMessage(
1388 FloatAudioFrame(src, num_channels, channel_size));
1389 }
peahdf3efa82015-11-28 12:35:15 -08001390 render_.render_audio->CopyFrom(src,
1391 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001392 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001393}
1394
1395int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001396 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001397 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001398 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001399 return kNullPointerError;
1400 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001401 // Must be a native rate.
1402 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1403 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001404 frame->sample_rate_hz_ != kSampleRate32kHz &&
1405 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001406 return kBadSampleRateError;
1407 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001408
Michael Graczyk86c6d332015-07-23 11:41:39 -07001409 if (frame->num_channels_ <= 0) {
1410 return kBadNumberChannelsError;
1411 }
1412
peahdf3efa82015-11-28 12:35:15 -08001413 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001414 processing_config.reverse_input_stream().set_sample_rate_hz(
1415 frame->sample_rate_hz_);
1416 processing_config.reverse_input_stream().set_num_channels(
1417 frame->num_channels_);
1418 processing_config.reverse_output_stream().set_sample_rate_hz(
1419 frame->sample_rate_hz_);
1420 processing_config.reverse_output_stream().set_num_channels(
1421 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001422
peahdf3efa82015-11-28 12:35:15 -08001423 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001424 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001425 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001426 return kBadDataLengthError;
1427 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001428
aleloi868f32f2017-05-23 07:20:05 -07001429 if (aec_dump_) {
1430 aec_dump_->WriteRenderStreamMessage(*frame);
1431 }
1432
peahdf3efa82015-11-28 12:35:15 -08001433 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001434 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001435 render_.render_audio->InterleaveTo(
1436 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001437 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001438}
niklase@google.com470e71d2011-07-07 08:21:25 +00001439
peahde65ddc2016-09-16 15:02:15 -07001440int AudioProcessingImpl::ProcessRenderStreamLocked() {
1441 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001442
1443 QueueNonbandedRenderAudio(render_buffer);
1444
peah2ace3f92016-09-10 04:42:27 -07001445 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001446 SampleRateSupportsMultiBand(
1447 formats_.render_processing_format.sample_rate_hz())) {
1448 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001449 }
1450
peah1bcfce52016-08-26 07:16:04 -07001451#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001452 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001453 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001454 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001455 }
peah1bcfce52016-08-26 07:16:04 -07001456#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001457
peahce4d9152017-05-19 01:28:05 -07001458 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1459 QueueBandedRenderAudio(render_buffer);
1460 }
1461
peahe0eae3c2016-12-14 01:16:23 -08001462 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1463 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001464 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001465 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001466
peah2ace3f92016-09-10 04:42:27 -07001467 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001468 SampleRateSupportsMultiBand(
1469 formats_.render_processing_format.sample_rate_hz())) {
1470 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001471 }
1472
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001473 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001474}
1475
1476int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001477 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001478 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001479 capture_.was_stream_delay_set = true;
1480 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001481
niklase@google.com470e71d2011-07-07 08:21:25 +00001482 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001483 delay = 0;
1484 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001485 }
1486
1487 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1488 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001489 delay = 500;
1490 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001491 }
1492
peahdf3efa82015-11-28 12:35:15 -08001493 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001494 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001495}
1496
1497int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001498 // Used as callback from submodules, hence locking is not allowed.
1499 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001500}
1501
1502bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001503 // Used as callback from submodules, hence locking is not allowed.
1504 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001505}
1506
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001507void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001508 rtc::CritScope cs(&crit_capture_);
1509 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001510}
1511
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001512void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001513 rtc::CritScope cs(&crit_capture_);
1514 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001515}
1516
1517int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001518 rtc::CritScope cs(&crit_capture_);
1519 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001520}
1521
aleloi868f32f2017-05-23 07:20:05 -07001522void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1523 RTC_DCHECK(aec_dump);
1524 rtc::CritScope cs_render(&crit_render_);
1525 rtc::CritScope cs_capture(&crit_capture_);
1526
1527 // The previously attached AecDump will be destroyed with the
1528 // 'aec_dump' parameter, which is after locks are released.
1529 aec_dump_.swap(aec_dump);
1530 WriteAecDumpConfigMessage(true);
1531 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1532}
1533
1534void AudioProcessingImpl::DetachAecDump() {
1535 // The d-tor of a task-queue based AecDump blocks until all pending
1536 // tasks are done. This construction avoids blocking while holding
1537 // the render and capture locks.
1538 std::unique_ptr<AecDump> aec_dump = nullptr;
1539 {
1540 rtc::CritScope cs_render(&crit_render_);
1541 rtc::CritScope cs_capture(&crit_capture_);
1542 aec_dump = std::move(aec_dump_);
1543 }
1544}
1545
ivoc4e477a12017-01-15 08:29:46 -08001546AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1547 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1548 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1549 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1550 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1551}
1552
1553AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1554 const AudioProcessingStatistics& other) = default;
1555
1556AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1557 default;
1558
ivoc3e9a5372016-10-28 07:55:33 -07001559// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1560AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1561 const {
1562 return AudioProcessingStatistics();
1563}
1564
1565AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1566 const {
1567 AudioProcessingStatistics stats;
1568 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001569 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1570 if (success == Error::kNoError) {
1571 stats.a_nlp.Set(metrics.a_nlp);
1572 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1573 stats.echo_return_loss.Set(metrics.echo_return_loss);
1574 stats.echo_return_loss_enhancement.Set(
1575 metrics.echo_return_loss_enhancement);
1576 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1577 }
ivoc9c192b22017-03-16 04:22:14 -07001578 {
1579 rtc::CritScope cs_capture(&crit_capture_);
1580 stats.residual_echo_likelihood =
1581 private_submodules_->residual_echo_detector->echo_likelihood();
1582 stats.residual_echo_likelihood_recent_max =
1583 private_submodules_->residual_echo_detector
1584 ->echo_likelihood_recent_max();
1585 }
ivoc3e9a5372016-10-28 07:55:33 -07001586 public_submodules_->echo_cancellation->GetDelayMetrics(
1587 &stats.delay_median, &stats.delay_standard_deviation,
1588 &stats.fraction_poor_delays);
1589 return stats;
1590}
1591
niklase@google.com470e71d2011-07-07 08:21:25 +00001592EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001593 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001594}
1595
1596EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001597 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001598}
1599
1600GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001601 if (constants_.use_experimental_agc) {
1602 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001603 }
peahbfa97112016-03-10 21:09:04 -08001604 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001605}
1606
1607HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001608 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001609}
1610
1611LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001612 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001613}
1614
1615NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001616 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001617}
1618
1619VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001620 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001621}
1622
peah8271d042016-11-22 07:24:52 -08001623void AudioProcessingImpl::MutateConfig(
1624 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1625 rtc::CritScope cs_render(&crit_render_);
1626 rtc::CritScope cs_capture(&crit_capture_);
1627 mutator(&config_);
1628 ApplyConfig(config_);
1629}
1630
1631AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1632 rtc::CritScope cs_render(&crit_render_);
1633 rtc::CritScope cs_capture(&crit_capture_);
1634 return config_;
1635}
1636
peah2ace3f92016-09-10 04:42:27 -07001637bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1638 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001639 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001640 public_submodules_->echo_cancellation->is_enabled(),
1641 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001642 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001643 public_submodules_->noise_suppression->is_enabled(),
1644 capture_nonlocked_.intelligibility_enabled,
1645 capture_nonlocked_.beamformer_enabled,
1646 public_submodules_->gain_control->is_enabled(),
alessiob3ec96df2017-05-22 06:57:06 -07001647 capture_nonlocked_.gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -07001648 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001649 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001650 public_submodules_->voice_detection->is_enabled(),
1651 public_submodules_->level_estimator->is_enabled(),
1652 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001653}
1654
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001655
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001656void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001657 if (capture_.transient_suppressor_enabled) {
1658 if (!public_submodules_->transient_suppressor.get()) {
1659 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001660 }
peahdf3efa82015-11-28 12:35:15 -08001661 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001662 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1663 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001664 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001665}
1666
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001667void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001668 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001669 if (!private_submodules_->beamformer) {
1670 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001671 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001672 }
peahdf3efa82015-11-28 12:35:15 -08001673 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1674 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001675 }
1676}
1677
ekmeyerson60d9b332015-08-14 10:35:55 -07001678void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001679#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001680 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001681 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001682 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001683 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001684 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001685 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001686 }
peah1bcfce52016-08-26 07:16:04 -07001687#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001688}
1689
peah8271d042016-11-22 07:24:52 -08001690void AudioProcessingImpl::InitializeLowCutFilter() {
1691 if (config_.high_pass_filter.enabled) {
1692 private_submodules_->low_cut_filter.reset(
1693 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1694 } else {
1695 private_submodules_->low_cut_filter.reset();
1696 }
1697}
alessiob3ec96df2017-05-22 06:57:06 -07001698
peahe0eae3c2016-12-14 01:16:23 -08001699void AudioProcessingImpl::InitializeEchoCanceller3() {
1700 if (capture_nonlocked_.echo_canceller3_enabled) {
peah697a5902017-06-30 07:06:10 -07001701 private_submodules_->echo_canceller3.reset(new EchoCanceller3(
1702 config_.echo_canceller3, proc_sample_rate_hz(), true));
peahe0eae3c2016-12-14 01:16:23 -08001703 } else {
1704 private_submodules_->echo_canceller3.reset();
1705 }
1706}
peah8271d042016-11-22 07:24:52 -08001707
alessiob3ec96df2017-05-22 06:57:06 -07001708void AudioProcessingImpl::InitializeGainController2() {
1709 if (capture_nonlocked_.gain_controller2_enabled) {
1710 private_submodules_->gain_controller2.reset(
1711 new GainController2(proc_sample_rate_hz()));
1712 } else {
1713 private_submodules_->gain_controller2.reset();
1714 }
1715}
1716
peahca4cac72016-06-29 15:26:12 -07001717void AudioProcessingImpl::InitializeLevelController() {
1718 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1719}
1720
ivoc9f4a4a02016-10-28 05:39:16 -07001721void AudioProcessingImpl::InitializeResidualEchoDetector() {
1722 private_submodules_->residual_echo_detector->Initialize();
1723}
1724
Sam Zackrisson0beac582017-09-25 12:04:02 +02001725void AudioProcessingImpl::InitializePostProcessor() {
1726 if (private_submodules_->capture_post_processor) {
1727 private_submodules_->capture_post_processor->Initialize(
1728 proc_sample_rate_hz(), num_proc_channels());
1729 }
1730}
1731
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001732void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001733 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001734
1735 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001736 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1737 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001738 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001739 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001740 capture_.stream_delay_jumps = 0;
1741 }
1742 if (capture_.aec_system_delay_jumps == -1 &&
1743 echo_cancellation()->stream_has_echo()) {
1744 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001745 }
1746
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001747 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001748 const int diff_stream_delay_ms =
1749 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1750 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1751 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001752 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1753 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001754 if (capture_.stream_delay_jumps == -1) {
1755 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001756 }
peahdf3efa82015-11-28 12:35:15 -08001757 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001758 }
peahdf3efa82015-11-28 12:35:15 -08001759 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001760
1761 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001762 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001763 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001764 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001765 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001766 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1767 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001768 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001769 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001770 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001771 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001772 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1773 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1774 100);
peahdf3efa82015-11-28 12:35:15 -08001775 if (capture_.aec_system_delay_jumps == -1) {
1776 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001777 }
peahdf3efa82015-11-28 12:35:15 -08001778 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001779 }
peahdf3efa82015-11-28 12:35:15 -08001780 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001781 }
1782}
1783
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001784void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001785 // Run in a single-threaded manner.
1786 rtc::CritScope cs_render(&crit_render_);
1787 rtc::CritScope cs_capture(&crit_capture_);
1788
1789 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001790 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001791 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001792 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001793 }
peahdf3efa82015-11-28 12:35:15 -08001794 capture_.stream_delay_jumps = -1;
1795 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001796
peahdf3efa82015-11-28 12:35:15 -08001797 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001798 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1799 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001800 }
peahdf3efa82015-11-28 12:35:15 -08001801 capture_.aec_system_delay_jumps = -1;
1802 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001803}
1804
aleloi868f32f2017-05-23 07:20:05 -07001805void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1806 if (!aec_dump_) {
1807 return;
1808 }
1809 std::string experiments_description =
1810 public_submodules_->echo_cancellation->GetExperimentsDescription();
1811 // TODO(peah): Add semicolon-separated concatenations of experiment
1812 // descriptions for other submodules.
1813 if (capture_nonlocked_.level_controller_enabled) {
1814 experiments_description += "LevelController;";
1815 }
1816 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1817 experiments_description += "AgcClippingLevelExperiment;";
1818 }
1819 if (capture_nonlocked_.echo_canceller3_enabled) {
1820 experiments_description += "EchoCanceller3;";
1821 }
1822
1823 InternalAPMConfig apm_config;
1824
1825 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1826 apm_config.aec_delay_agnostic_enabled =
1827 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1828 apm_config.aec_drift_compensation_enabled =
1829 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1830 apm_config.aec_extended_filter_enabled =
1831 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1832 apm_config.aec_suppression_level = static_cast<int>(
1833 public_submodules_->echo_cancellation->suppression_level());
1834
1835 apm_config.aecm_enabled =
1836 public_submodules_->echo_control_mobile->is_enabled();
1837 apm_config.aecm_comfort_noise_enabled =
1838 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1839 apm_config.aecm_routing_mode =
1840 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1841
1842 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1843 apm_config.agc_mode =
1844 static_cast<int>(public_submodules_->gain_control->mode());
1845 apm_config.agc_limiter_enabled =
1846 public_submodules_->gain_control->is_limiter_enabled();
1847 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1848
1849 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1850
1851 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1852 apm_config.ns_level =
1853 static_cast<int>(public_submodules_->noise_suppression->level());
1854
1855 apm_config.transient_suppression_enabled =
1856 capture_.transient_suppressor_enabled;
1857 apm_config.intelligibility_enhancer_enabled =
1858 capture_nonlocked_.intelligibility_enabled;
1859 apm_config.experiments_description = experiments_description;
1860
1861 if (!forced && apm_config == apm_config_for_aec_dump_) {
1862 return;
1863 }
1864 aec_dump_->WriteConfig(apm_config);
1865 apm_config_for_aec_dump_ = apm_config;
1866}
1867
1868void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1869 const float* const* src) {
1870 RTC_DCHECK(aec_dump_);
1871 WriteAecDumpConfigMessage(false);
1872
1873 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1874 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1875 aec_dump_->AddCaptureStreamInput(
1876 FloatAudioFrame(src, num_channels, channel_size));
1877 RecordAudioProcessingState();
1878}
1879
1880void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1881 const AudioFrame& capture_frame) {
1882 RTC_DCHECK(aec_dump_);
1883 WriteAecDumpConfigMessage(false);
1884
1885 aec_dump_->AddCaptureStreamInput(capture_frame);
1886 RecordAudioProcessingState();
1887}
1888
1889void AudioProcessingImpl::RecordProcessedCaptureStream(
1890 const float* const* processed_capture_stream) {
1891 RTC_DCHECK(aec_dump_);
1892
1893 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1894 const size_t num_channels =
1895 formats_.api_format.output_stream().num_channels();
1896 aec_dump_->AddCaptureStreamOutput(
1897 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
1898 aec_dump_->WriteCaptureStreamMessage();
1899}
1900
1901void AudioProcessingImpl::RecordProcessedCaptureStream(
1902 const AudioFrame& processed_capture_frame) {
1903 RTC_DCHECK(aec_dump_);
1904
1905 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1906 aec_dump_->WriteCaptureStreamMessage();
1907}
1908
1909void AudioProcessingImpl::RecordAudioProcessingState() {
1910 RTC_DCHECK(aec_dump_);
1911 AecDump::AudioProcessingState audio_proc_state;
1912 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
1913 audio_proc_state.drift =
1914 public_submodules_->echo_cancellation->stream_drift_samples();
1915 audio_proc_state.level = gain_control()->stream_analog_level();
1916 audio_proc_state.keypress = capture_.key_pressed;
1917 aec_dump_->AddAudioProcessingState(audio_proc_state);
1918}
1919
kwiberg83ffe452016-08-29 14:46:07 -07001920AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1921 bool transient_suppressor_enabled,
1922 const std::vector<Point>& array_geometry,
1923 SphericalPointf target_direction)
1924 : aec_system_delay_jumps(-1),
1925 delay_offset_ms(0),
1926 was_stream_delay_set(false),
1927 last_stream_delay_ms(0),
1928 last_aec_system_delay_ms(0),
1929 stream_delay_jumps(-1),
1930 output_will_be_muted(false),
1931 key_pressed(false),
1932 transient_suppressor_enabled(transient_suppressor_enabled),
1933 array_geometry(array_geometry),
1934 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001935 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001936 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001937 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07001938
1939AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1940
1941AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1942
1943AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1944
niklase@google.com470e71d2011-07-07 08:21:25 +00001945} // namespace webrtc