blob: 7d123555ef073a0ffe5d7ae26fbd7fad64fb42a4 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "modules/audio_processing/audio_buffer.h"
24#include "modules/audio_processing/beamformer/nonlinear_beamformer.h"
25#include "modules/audio_processing/common.h"
26#include "modules/audio_processing/echo_cancellation_impl.h"
27#include "modules/audio_processing/echo_control_mobile_impl.h"
28#include "modules/audio_processing/gain_control_for_experimental_agc.h"
29#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010030#include "modules/audio_processing/gain_controller2.h"
Per Åhgren13735822018-02-12 21:42:56 +010031#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#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_estimator_impl.h"
41#include "modules/audio_processing/low_cut_filter.h"
42#include "modules/audio_processing/noise_suppression_impl.h"
43#include "modules/audio_processing/residual_echo_detector.h"
44#include "modules/audio_processing/transient/transient_suppressor.h"
45#include "modules/audio_processing/voice_detection_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010046#include "rtc_base/atomicops.h"
Karl Wiberg6a4d4112018-03-23 10:39:34 +010047#include "rtc_base/system/file_wrapper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000049
peah1bcfce52016-08-26 07:16:04 -070050// Check to verify that the define for the intelligibility enhancer is properly
51// set.
52#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
53 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
54 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
55#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
56#endif
57
Michael Graczyk86c6d332015-07-23 11:41:39 -070058#define RETURN_ON_ERR(expr) \
59 do { \
60 int err = (expr); \
61 if (err != kNoError) { \
62 return err; \
63 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000064 } while (0)
65
niklase@google.com470e71d2011-07-07 08:21:25 +000066namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070067
kwibergd59d3bb2016-09-13 07:49:33 -070068constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070069
Michael Graczyk86c6d332015-07-23 11:41:39 -070070namespace {
71
72static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
73 switch (layout) {
74 case AudioProcessing::kMono:
75 case AudioProcessing::kStereo:
76 return false;
77 case AudioProcessing::kMonoAndKeyboard:
78 case AudioProcessing::kStereoAndKeyboard:
79 return true;
80 }
81
kwiberg9e2be5f2016-09-14 05:23:22 -070082 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070083 return false;
84}
aluebsdf6416a2016-03-16 18:26:35 -070085
peah2ace3f92016-09-10 04:42:27 -070086bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070087 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
88 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
89}
90
peah2ace3f92016-09-10 04:42:27 -070091int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
92#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070093 constexpr int kMaxSplittingNativeProcessRate =
94 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070095#else
kwibergd59d3bb2016-09-13 07:49:33 -070096 constexpr int kMaxSplittingNativeProcessRate =
97 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070098#endif
kwibergd59d3bb2016-09-13 07:49:33 -070099 static_assert(
100 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
101 "");
peah2ace3f92016-09-10 04:42:27 -0700102 const int uppermost_native_rate = band_splitting_required
103 ? kMaxSplittingNativeProcessRate
104 : AudioProcessing::kSampleRate48kHz;
105
106 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
107 if (rate >= uppermost_native_rate) {
108 return uppermost_native_rate;
109 }
110 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700111 return rate;
112 }
113 }
peah2ace3f92016-09-10 04:42:27 -0700114 RTC_NOTREACHED();
115 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700116}
117
peah9e6a2902017-05-15 07:19:21 -0700118// Maximum lengths that frame of samples being passed from the render side to
119// the capture side can have (does not apply to AEC3).
120static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
121static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
122
peah764e3642016-10-22 05:04:30 -0700123// Maximum number of frames to buffer in the render queue.
124// TODO(peah): Decrease this once we properly handle hugely unbalanced
125// reverse and forward call numbers.
126static const size_t kMaxNumFramesToBuffer = 100;
127
peah8271d042016-11-22 07:24:52 -0800128class HighPassFilterImpl : public HighPassFilter {
129 public:
130 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
131 ~HighPassFilterImpl() override = default;
132
133 // HighPassFilter implementation.
134 int Enable(bool enable) override {
135 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
136 config->high_pass_filter.enabled = enable;
137 });
138
139 return AudioProcessing::kNoError;
140 }
141
142 bool is_enabled() const override {
143 return apm_->GetConfig().high_pass_filter.enabled;
144 }
145
146 private:
147 AudioProcessingImpl* apm_;
148 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
149};
150
aleloi868f32f2017-05-23 07:20:05 -0700151webrtc::InternalAPMStreamsConfig ToStreamsConfig(
152 const ProcessingConfig& api_format) {
153 webrtc::InternalAPMStreamsConfig result;
154 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
155 result.input_num_channels = api_format.input_stream().num_channels();
156 result.output_num_channels = api_format.output_stream().num_channels();
157 result.render_input_num_channels =
158 api_format.reverse_input_stream().num_channels();
159 result.render_input_sample_rate =
160 api_format.reverse_input_stream().sample_rate_hz();
161 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
162 result.render_output_sample_rate =
163 api_format.reverse_output_stream().sample_rate_hz();
164 result.render_output_num_channels =
165 api_format.reverse_output_stream().num_channels();
166 return result;
167}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700168} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000169
170// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000171static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000172
Sam Zackrisson0beac582017-09-25 12:04:02 +0200173AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100174 bool capture_post_processor_enabled,
175 bool render_pre_processor_enabled)
176 : capture_post_processor_enabled_(capture_post_processor_enabled),
177 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700178
179bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800180 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700181 bool echo_canceller_enabled,
182 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700183 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700184 bool noise_suppressor_enabled,
185 bool intelligibility_enhancer_enabled,
186 bool beamformer_enabled,
187 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700188 bool gain_controller2_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200189 bool echo_controller_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_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200208 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700209 changed |= (level_estimator_enabled != level_estimator_enabled_);
210 changed |=
211 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
212 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
213 if (changed) {
peah8271d042016-11-22 07:24:52 -0800214 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700215 echo_canceller_enabled_ = echo_canceller_enabled;
216 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700217 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700218 noise_suppressor_enabled_ = noise_suppressor_enabled;
219 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
220 beamformer_enabled_ = beamformer_enabled;
221 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700222 gain_controller2_enabled_ = gain_controller2_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200223 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700224 level_estimator_enabled_ = level_estimator_enabled;
225 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
226 transient_suppressor_enabled_ = transient_suppressor_enabled;
227 }
228
229 changed |= first_update_;
230 first_update_ = false;
231 return changed;
232}
233
234bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
235 const {
236#if WEBRTC_INTELLIGIBILITY_ENHANCER
237 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700238 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700239#else
peah52775842017-05-16 06:14:09 -0700240 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700241#endif
242}
243
244bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
245 const {
peah8271d042016-11-22 07:24:52 -0800246 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700247 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800248 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200249 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700250}
251
peah23ac8b42017-05-23 05:33:56 -0700252bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
253 const {
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100254 return gain_controller2_enabled_ || capture_post_processor_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700255}
256
peah2ace3f92016-09-10 04:42:27 -0700257bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
258 const {
259 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800260 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200261 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700262}
263
Alex Loiko5825aa62017-12-18 16:02:40 +0100264bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
265 const {
266 return render_pre_processor_enabled_;
267}
268
peah2ace3f92016-09-10 04:42:27 -0700269bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
270 const {
271#if WEBRTC_INTELLIGIBILITY_ENHANCER
272 return intelligibility_enhancer_enabled_;
273#else
274 return false;
275#endif
276}
277
solenberg5e465c32015-12-08 13:22:33 -0800278struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800279 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800280 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800281 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800282 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800283 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800284 std::unique_ptr<LevelEstimatorImpl> level_estimator;
285 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
286 std::unique_ptr<VoiceDetectionImpl> voice_detection;
287 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800288 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800289
290 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800291 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700292#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800293 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700294#endif
solenberg5e465c32015-12-08 13:22:33 -0800295};
296
297struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200298 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100299 std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100300 std::unique_ptr<CustomProcessing> render_pre_processor,
301 std::unique_ptr<EchoDetector> echo_detector)
Sam Zackrisson0beac582017-09-25 12:04:02 +0200302 : beamformer(beamformer),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100303 echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100304 capture_post_processor(std::move(capture_post_processor)),
305 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800306 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700307 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800308 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700309 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800310 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100311 std::unique_ptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200312 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100313 std::unique_ptr<CustomProcessing> capture_post_processor;
314 std::unique_ptr<CustomProcessing> render_pre_processor;
solenberg5e465c32015-12-08 13:22:33 -0800315};
316
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100317AudioProcessingBuilder::AudioProcessingBuilder() = default;
318AudioProcessingBuilder::~AudioProcessingBuilder() = default;
319
320AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
321 std::unique_ptr<CustomProcessing> capture_post_processing) {
322 capture_post_processing_ = std::move(capture_post_processing);
323 return *this;
324}
325
326AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
327 std::unique_ptr<CustomProcessing> render_pre_processing) {
328 render_pre_processing_ = std::move(render_pre_processing);
329 return *this;
330}
331
332AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
333 std::unique_ptr<EchoControlFactory> echo_control_factory) {
334 echo_control_factory_ = std::move(echo_control_factory);
335 return *this;
336}
337
338AudioProcessingBuilder& AudioProcessingBuilder::SetNonlinearBeamformer(
339 std::unique_ptr<NonlinearBeamformer> nonlinear_beamformer) {
340 nonlinear_beamformer_ = std::move(nonlinear_beamformer);
341 return *this;
342}
343
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100344AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
345 std::unique_ptr<EchoDetector> echo_detector) {
346 echo_detector_ = std::move(echo_detector);
347 return *this;
348}
349
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100350AudioProcessing* AudioProcessingBuilder::Create() {
351 webrtc::Config config;
352 return Create(config);
353}
354
355AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100356 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
357 config, std::move(capture_post_processing_),
358 std::move(render_pre_processing_), std::move(echo_control_factory_),
359 std::move(echo_detector_), nonlinear_beamformer_.release());
360 if (apm->Initialize() != AudioProcessing::kNoError) {
361 delete apm;
362 apm = nullptr;
363 }
364 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100365}
366
peah88ac8532016-09-12 16:47:25 -0700367AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100368 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
369}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000370
Per Åhgren13735822018-02-12 21:42:56 +0100371int AudioProcessingImpl::instance_count_ = 0;
372
Sam Zackrisson0beac582017-09-25 12:04:02 +0200373AudioProcessingImpl::AudioProcessingImpl(
374 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100375 std::unique_ptr<CustomProcessing> capture_post_processor,
376 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200377 std::unique_ptr<EchoControlFactory> echo_control_factory,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100378 std::unique_ptr<EchoDetector> echo_detector,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200379 NonlinearBeamformer* beamformer)
Per Åhgren13735822018-02-12 21:42:56 +0100380 : data_dumper_(
381 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alessio Bazzicac054e782018-04-16 12:10:09 +0200382 runtime_settings_(new SwapQueue<RuntimeSetting>(100)),
383 runtime_settings_enqueuer_(runtime_settings_.get()),
Per Åhgren13735822018-02-12 21:42:56 +0100384 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200385 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100386 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800387 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200388 private_submodules_(
389 new ApmPrivateSubmodules(beamformer,
Alex Loiko5825aa62017-12-18 16:02:40 +0100390 std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100391 std::move(render_pre_processor),
392 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800393 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800394 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000395#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700396 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000397#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700398 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000399#endif
andrew1c7075f2015-06-24 18:14:14 -0700400#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800401 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700402#else
aluebs2a346882016-01-11 18:04:30 -0800403 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700404#endif
aluebs2a346882016-01-11 18:04:30 -0800405 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800406 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700407 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700408 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800409 {
410 rtc::CritScope cs_render(&crit_render_);
411 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000412
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200413 // Mark Echo Controller enabled if a factory is injected.
414 capture_nonlocked_.echo_controller_enabled =
415 static_cast<bool>(echo_control_factory_);
416
peahb624d8c2016-03-05 03:01:14 -0800417 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700418 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800419 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700420 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800421 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700422 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800423 public_submodules_->level_estimator.reset(
424 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800425 public_submodules_->noise_suppression.reset(
426 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800427 public_submodules_->voice_detection.reset(
428 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800429 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800430 new GainControlForExperimentalAgc(
431 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100432
433 // If no echo detector is injected, use the ResidualEchoDetector.
434 if (!private_submodules_->echo_detector) {
435 private_submodules_->echo_detector.reset(new ResidualEchoDetector());
436 }
peahca4cac72016-06-29 15:26:12 -0700437
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200438 // TODO(alessiob): Move the injected gain controller once injection is
439 // implemented.
440 private_submodules_->gain_controller2.reset(new GainController2());
441
Mirko Bonadei675513b2017-11-09 11:09:25 +0100442 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100443 << !!private_submodules_->capture_post_processor
444 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100445 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800446 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000447
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000448 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000449}
450
451AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800452 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800453 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800454 private_submodules_->agc_manager.reset();
455 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800456 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000457}
458
niklase@google.com470e71d2011-07-07 08:21:25 +0000459int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800460 // Run in a single-threaded manner during initialization.
461 rtc::CritScope cs_render(&crit_render_);
462 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000463 return InitializeLocked();
464}
465
peahde65ddc2016-09-16 15:02:15 -0700466int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
467 int capture_output_sample_rate_hz,
468 int render_input_sample_rate_hz,
469 ChannelLayout capture_input_layout,
470 ChannelLayout capture_output_layout,
471 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700472 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700473 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
474 LayoutHasKeyboard(capture_input_layout)},
475 {capture_output_sample_rate_hz,
476 ChannelsFromLayout(capture_output_layout),
477 LayoutHasKeyboard(capture_output_layout)},
478 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
479 LayoutHasKeyboard(render_input_layout)},
480 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
481 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700482
483 return Initialize(processing_config);
484}
485
486int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800487 // Run in a single-threaded manner during initialization.
488 rtc::CritScope cs_render(&crit_render_);
489 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700490 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000491}
492
peahdf3efa82015-11-28 12:35:15 -0800493int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800494 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700495 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800496}
497
peahdf3efa82015-11-28 12:35:15 -0800498int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700499 const ProcessingConfig& processing_config,
500 bool force_initialization) {
501 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800502}
503
peah192164e2015-11-17 02:16:45 -0800504// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800505// their current values (needs to be called while holding the crit_render_lock).
506int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700507 const ProcessingConfig& processing_config,
508 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800509 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700510 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800511 return kNoError;
512 }
peahdf3efa82015-11-28 12:35:15 -0800513
514 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800515 return InitializeLocked(processing_config);
516}
517
niklase@google.com470e71d2011-07-07 08:21:25 +0000518int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200519 UpdateActiveSubmoduleStates();
520
peah522d71b2017-02-23 05:16:26 -0800521 const int capture_audiobuffer_num_channels =
522 capture_nonlocked_.beamformer_enabled
523 ? formats_.api_format.input_stream().num_channels()
524 : formats_.api_format.output_stream().num_channels();
525
peahde65ddc2016-09-16 15:02:15 -0700526 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800527 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700528 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800529 : formats_.api_format.reverse_output_stream().num_frames();
530 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
531 render_.render_audio.reset(new AudioBuffer(
532 formats_.api_format.reverse_input_stream().num_frames(),
533 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700534 formats_.render_processing_format.num_frames(),
535 formats_.render_processing_format.num_channels(),
536 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700537 if (formats_.api_format.reverse_input_stream() !=
538 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800539 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800540 formats_.api_format.reverse_input_stream().num_channels(),
541 formats_.api_format.reverse_input_stream().num_frames(),
542 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800543 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700544 } else {
peahdf3efa82015-11-28 12:35:15 -0800545 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700546 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700547 } else {
peahdf3efa82015-11-28 12:35:15 -0800548 render_.render_audio.reset(nullptr);
549 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700550 }
peahce4d9152017-05-19 01:28:05 -0700551
peahdf3efa82015-11-28 12:35:15 -0800552 capture_.capture_audio.reset(
553 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
554 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700555 capture_nonlocked_.capture_processing_format.num_frames(),
556 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800557 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000558
peahde65ddc2016-09-16 15:02:15 -0700559 public_submodules_->echo_cancellation->Initialize(
560 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
561 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700562 AllocateRenderQueue();
563
ivoc3e9a5372016-10-28 07:55:33 -0700564 int success = public_submodules_->echo_cancellation->enable_metrics(true);
565 RTC_DCHECK_EQ(0, success);
566 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
567 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700568 public_submodules_->echo_control_mobile->Initialize(
569 proc_split_sample_rate_hz(), num_reverse_channels(),
570 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700571
572 public_submodules_->gain_control->Initialize(num_proc_channels(),
573 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700574 if (constants_.use_experimental_agc) {
575 if (!private_submodules_->agc_manager.get()) {
576 private_submodules_->agc_manager.reset(new AgcManagerDirect(
577 public_submodules_->gain_control.get(),
578 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800579 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700580 }
581 private_submodules_->agc_manager->Initialize();
582 private_submodules_->agc_manager->SetCaptureMuted(
583 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700584 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700585 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200586 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000587 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700588#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700589 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700590#endif
peah8271d042016-11-22 07:24:52 -0800591 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700592 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
593 proc_sample_rate_hz());
594 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
595 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700596 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200597 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700598 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200599 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100600 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800601
aleloi868f32f2017-05-23 07:20:05 -0700602 if (aec_dump_) {
603 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
604 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000605 return kNoError;
606}
607
Michael Graczyk86c6d332015-07-23 11:41:39 -0700608int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200609 UpdateActiveSubmoduleStates();
610
Michael Graczyk86c6d332015-07-23 11:41:39 -0700611 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700612 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
613 return kBadSampleRateError;
614 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000615 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700616
Peter Kasting69558702016-01-12 16:26:35 -0800617 const size_t num_in_channels = config.input_stream().num_channels();
618 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700619
620 // Need at least one input channel.
621 // Need either one output channel or as many outputs as there are inputs.
622 if (num_in_channels == 0 ||
623 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700624 return kBadNumberChannelsError;
625 }
626
aluebsb2328d12016-01-11 20:32:29 -0800627 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800628 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700629 return kBadNumberChannelsError;
630 }
631
peahdf3efa82015-11-28 12:35:15 -0800632 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000633
peahde65ddc2016-09-16 15:02:15 -0700634 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700635 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700636 formats_.api_format.output_stream().sample_rate_hz()),
637 submodule_states_.CaptureMultiBandSubModulesActive() ||
638 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000639
peahde65ddc2016-09-16 15:02:15 -0700640 capture_nonlocked_.capture_processing_format =
641 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700642
peah2ce640f2017-04-07 03:57:48 -0700643 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200644 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700645 render_processing_rate = FindNativeProcessRateToUse(
646 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
647 formats_.api_format.reverse_output_stream().sample_rate_hz()),
648 submodule_states_.CaptureMultiBandSubModulesActive() ||
649 submodule_states_.RenderMultiBandSubModulesActive());
650 } else {
651 render_processing_rate = capture_processing_rate;
652 }
653
aluebseb3603b2016-04-20 15:27:58 -0700654 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
655 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700656 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200657 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700658 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
659 ? kSampleRate32kHz
660 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700661 }
peah2ce640f2017-04-07 03:57:48 -0700662
peahde65ddc2016-09-16 15:02:15 -0700663 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700664 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700665 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
666 kSampleRate8kHz) {
667 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000668 } else {
peahde65ddc2016-09-16 15:02:15 -0700669 render_processing_rate =
670 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000671 }
672
peahde65ddc2016-09-16 15:02:15 -0700673 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000674 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700675 if (submodule_states_.RenderMultiBandSubModulesActive()) {
676 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
677 } else {
678 formats_.render_processing_format = StreamConfig(
679 formats_.api_format.reverse_input_stream().sample_rate_hz(),
680 formats_.api_format.reverse_input_stream().num_channels());
681 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000682
peahde65ddc2016-09-16 15:02:15 -0700683 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
684 kSampleRate32kHz ||
685 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
686 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800687 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000688 } else {
peahdf3efa82015-11-28 12:35:15 -0800689 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700690 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000691 }
692
693 return InitializeLocked();
694}
695
peah88ac8532016-09-12 16:47:25 -0700696void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700697 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700698
peah88ac8532016-09-12 16:47:25 -0700699 // Run in a single-threaded manner when applying the settings.
700 rtc::CritScope cs_render(&crit_render_);
701 rtc::CritScope cs_capture(&crit_capture_);
702
peah8271d042016-11-22 07:24:52 -0800703 InitializeLowCutFilter();
704
Mirko Bonadei675513b2017-11-09 11:09:25 +0100705 RTC_LOG(LS_INFO) << "Highpass filter activated: "
706 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800707
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100708 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700709 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100710 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
711 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100712 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100713 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700714 config_.gain_controller2 = AudioProcessing::Config::GainController2();
715 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200716 InitializeGainController2();
717 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100718 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
719 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200720 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
721 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700722}
723
724void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800725 // Run in a single-threaded manner when setting the extra options.
726 rtc::CritScope cs_render(&crit_render_);
727 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000728
peahb624d8c2016-03-05 03:01:14 -0800729 public_submodules_->echo_cancellation->SetExtraOptions(config);
730
peahdf3efa82015-11-28 12:35:15 -0800731 if (capture_.transient_suppressor_enabled !=
732 config.Get<ExperimentalNs>().enabled) {
733 capture_.transient_suppressor_enabled =
734 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000735 InitializeTransient();
736 }
aluebs2a346882016-01-11 18:04:30 -0800737
peah1bcfce52016-08-26 07:16:04 -0700738#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700739 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700740 config.Get<Intelligibility>().enabled) {
741 capture_nonlocked_.intelligibility_enabled =
742 config.Get<Intelligibility>().enabled;
743 InitializeIntelligibility();
744 }
peah1bcfce52016-08-26 07:16:04 -0700745#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700746
aluebs2a346882016-01-11 18:04:30 -0800747#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800748 if (capture_nonlocked_.beamformer_enabled !=
749 config.Get<Beamforming>().enabled) {
750 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800751 if (config.Get<Beamforming>().array_geometry.size() > 1) {
752 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
753 }
754 capture_.target_direction = config.Get<Beamforming>().target_direction;
755 InitializeBeamformer();
756 }
757#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000758}
759
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000760int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800761 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700762 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000763}
764
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000765int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800766 // Used as callback from submodules, hence locking is not allowed.
767 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000768}
769
Peter Kasting69558702016-01-12 16:26:35 -0800770size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800771 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700772 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000773}
774
Peter Kasting69558702016-01-12 16:26:35 -0800775size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800776 // Used as callback from submodules, hence locking is not allowed.
777 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000778}
779
Peter Kasting69558702016-01-12 16:26:35 -0800780size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800781 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700782 return (capture_nonlocked_.beamformer_enabled ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200783 capture_nonlocked_.echo_controller_enabled)
peahedddac52017-05-16 01:08:58 -0700784 ? 1
785 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800786}
787
Peter Kasting69558702016-01-12 16:26:35 -0800788size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800789 // Used as callback from submodules, hence locking is not allowed.
790 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000791}
792
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000793void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800794 rtc::CritScope cs(&crit_capture_);
795 capture_.output_will_be_muted = muted;
796 if (private_submodules_->agc_manager.get()) {
797 private_submodules_->agc_manager->SetCaptureMuted(
798 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000799 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000800}
801
Alessio Bazzicac054e782018-04-16 12:10:09 +0200802void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
803 RTC_DCHECK(setting.type() != RuntimeSetting::Type::kNotSpecified);
804 runtime_settings_enqueuer_.Enqueue(setting);
805}
806
807AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
808 SwapQueue<RuntimeSetting>* runtime_settings)
809 : runtime_settings_(runtime_settings) {
810 RTC_DCHECK(runtime_settings_);
811}
812
813AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
814 default;
815
816void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
817 RuntimeSetting setting) {
818 size_t remaining_attempts = 10;
819 while (!runtime_settings_->Insert(&setting) && remaining_attempts-- > 0) {
820 RuntimeSetting setting_to_discard;
821 if (runtime_settings_->Remove(&setting_to_discard))
822 RTC_LOG(LS_ERROR)
823 << "The runtime settings queue is full. Oldest setting discarded.";
824 }
825 if (remaining_attempts == 0)
826 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
827}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000828
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000829int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700830 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000831 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000832 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000833 int output_sample_rate_hz,
834 ChannelLayout output_layout,
835 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800836 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800837 StreamConfig input_stream;
838 StreamConfig output_stream;
839 {
840 // Access the formats_.api_format.input_stream beneath the capture lock.
841 // The lock must be released as it is later required in the call
842 // to ProcessStream(,,,);
843 rtc::CritScope cs(&crit_capture_);
844 input_stream = formats_.api_format.input_stream();
845 output_stream = formats_.api_format.output_stream();
846 }
847
Michael Graczyk86c6d332015-07-23 11:41:39 -0700848 input_stream.set_sample_rate_hz(input_sample_rate_hz);
849 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
850 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700851 output_stream.set_sample_rate_hz(output_sample_rate_hz);
852 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
853 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
854
855 if (samples_per_channel != input_stream.num_frames()) {
856 return kBadDataLengthError;
857 }
858 return ProcessStream(src, input_stream, output_stream, dest);
859}
860
861int AudioProcessingImpl::ProcessStream(const float* const* src,
862 const StreamConfig& input_config,
863 const StreamConfig& output_config,
864 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800865 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800866 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700867 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800868 {
869 // Acquire the capture lock in order to safely call the function
870 // that retrieves the render side data. This function accesses apm
871 // getters that need the capture lock held when being called.
872 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700873 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800874
875 if (!src || !dest) {
876 return kNullPointerError;
877 }
878
879 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700880 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000881 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000882
Michael Graczyk86c6d332015-07-23 11:41:39 -0700883 processing_config.input_stream() = input_config;
884 processing_config.output_stream() = output_config;
885
peahdf3efa82015-11-28 12:35:15 -0800886 {
887 // Do conditional reinitialization.
888 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700889 RETURN_ON_ERR(
890 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800891 }
892 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700893 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
894 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000895
aleloi868f32f2017-05-23 07:20:05 -0700896 if (aec_dump_) {
897 RecordUnprocessedCaptureStream(src);
898 }
899
peahdf3efa82015-11-28 12:35:15 -0800900 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700901 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800902 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000903
aleloi868f32f2017-05-23 07:20:05 -0700904 if (aec_dump_) {
905 RecordProcessedCaptureStream(dest);
906 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000907 return kNoError;
908}
909
Alessio Bazzicac054e782018-04-16 12:10:09 +0200910void AudioProcessingImpl::HandleRuntimeSettings() {
911 RuntimeSetting setting;
912 while (runtime_settings_->Remove(&setting)) {
913 RTC_DCHECK(setting.type() != RuntimeSetting::Type::kNotSpecified);
914 switch (setting.type()) {
915 case RuntimeSetting::Type::kCapturePreGain:
916 // TODO(bugs.chromium.org/9138): Notify
917 // pre-gain when the sub-module is implemented.
918 break;
919 default:
920 RTC_NOTREACHED();
921 break;
922 }
923 }
924}
925
peah9e6a2902017-05-15 07:19:21 -0700926void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700927 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
928 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700929 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700930
kwibergaf476c72016-11-28 15:21:39 -0800931 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700932
933 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700934 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700935 // The data queue is full and needs to be emptied.
936 EmptyQueuedRenderAudio();
937
938 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700939 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700940 RTC_DCHECK(result);
941 }
942
943 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
944 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700945 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700946
947 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700948 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700949 // The data queue is full and needs to be emptied.
950 EmptyQueuedRenderAudio();
951
952 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700953 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700954 RTC_DCHECK(result);
955 }
peah701d6282016-10-25 05:42:20 -0700956
957 if (!constants_.use_experimental_agc) {
958 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
959 // Insert the samples into the queue.
960 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
961 // The data queue is full and needs to be emptied.
962 EmptyQueuedRenderAudio();
963
964 // Retry the insert (should always work).
965 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
966 RTC_DCHECK(result);
967 }
968 }
peah9e6a2902017-05-15 07:19:21 -0700969}
ivoc9f4a4a02016-10-28 05:39:16 -0700970
peah9e6a2902017-05-15 07:19:21 -0700971void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700972 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
973
974 // Insert the samples into the queue.
975 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
976 // The data queue is full and needs to be emptied.
977 EmptyQueuedRenderAudio();
978
979 // Retry the insert (should always work).
980 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
981 RTC_DCHECK(result);
982 }
peah764e3642016-10-22 05:04:30 -0700983}
984
985void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700986 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700987 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700988 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700989 EchoCancellationImpl::NumCancellersRequired(
990 num_output_channels(), num_reverse_channels()));
991
peah701d6282016-10-25 05:42:20 -0700992 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700993 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700994 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700995 EchoControlMobileImpl::NumCancellersRequired(
996 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700997
peah701d6282016-10-25 05:42:20 -0700998 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700999 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001000
ivoc9f4a4a02016-10-28 05:39:16 -07001001 const size_t new_red_render_queue_element_max_size =
1002 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1003
peaha0624602016-10-25 04:45:24 -07001004 // Reallocate the queues if the queue item sizes are too small to fit the
1005 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001006 if (aec_render_queue_element_max_size_ <
1007 new_aec_render_queue_element_max_size) {
1008 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001009
peaha0624602016-10-25 04:45:24 -07001010 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001011 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001012
peah701d6282016-10-25 05:42:20 -07001013 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001014 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1015 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001016 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001017 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001018
peah701d6282016-10-25 05:42:20 -07001019 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1020 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001021 } else {
peah701d6282016-10-25 05:42:20 -07001022 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001023 }
1024
peah701d6282016-10-25 05:42:20 -07001025 if (aecm_render_queue_element_max_size_ <
1026 new_aecm_render_queue_element_max_size) {
1027 aecm_render_queue_element_max_size_ =
1028 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001029
1030 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001031 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001032
peah701d6282016-10-25 05:42:20 -07001033 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001034 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1035 kMaxNumFramesToBuffer, template_queue_element,
1036 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001037 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001038
peah701d6282016-10-25 05:42:20 -07001039 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1040 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001041 } else {
peah701d6282016-10-25 05:42:20 -07001042 aecm_render_signal_queue_->Clear();
1043 }
1044
1045 if (agc_render_queue_element_max_size_ <
1046 new_agc_render_queue_element_max_size) {
1047 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1048
1049 std::vector<int16_t> template_queue_element(
1050 agc_render_queue_element_max_size_);
1051
1052 agc_render_signal_queue_.reset(
1053 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1054 kMaxNumFramesToBuffer, template_queue_element,
1055 RenderQueueItemVerifier<int16_t>(
1056 agc_render_queue_element_max_size_)));
1057
1058 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1059 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1060 } else {
1061 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001062 }
ivoc9f4a4a02016-10-28 05:39:16 -07001063
1064 if (red_render_queue_element_max_size_ <
1065 new_red_render_queue_element_max_size) {
1066 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1067
1068 std::vector<float> template_queue_element(
1069 red_render_queue_element_max_size_);
1070
1071 red_render_signal_queue_.reset(
1072 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1073 kMaxNumFramesToBuffer, template_queue_element,
1074 RenderQueueItemVerifier<float>(
1075 red_render_queue_element_max_size_)));
1076
1077 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1078 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1079 } else {
1080 red_render_signal_queue_->Clear();
1081 }
peah764e3642016-10-22 05:04:30 -07001082}
1083
1084void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1085 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001086 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001087 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001088 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001089 }
1090
peah701d6282016-10-25 05:42:20 -07001091 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001092 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001093 aecm_capture_queue_buffer_);
1094 }
1095
1096 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1097 public_submodules_->gain_control->ProcessRenderAudio(
1098 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001099 }
ivoc9f4a4a02016-10-28 05:39:16 -07001100
1101 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001102 RTC_DCHECK(private_submodules_->echo_detector);
1103 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001104 red_capture_queue_buffer_);
1105 }
peah764e3642016-10-22 05:04:30 -07001106}
1107
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001108int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001109 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001110 {
1111 // Acquire the capture lock in order to safely call the function
1112 // that retrieves the render side data. This function accesses apm
1113 // getters that need the capture lock held when being called.
1114 // The lock needs to be released as
1115 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1116 // as well.
1117 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001118 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001119 }
peahfa6228e2015-11-16 16:27:42 -08001120
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001121 if (!frame) {
1122 return kNullPointerError;
1123 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001124 // Must be a native rate.
1125 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1126 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001127 frame->sample_rate_hz_ != kSampleRate32kHz &&
1128 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001129 return kBadSampleRateError;
1130 }
peah192164e2015-11-17 02:16:45 -08001131
peahdf3efa82015-11-28 12:35:15 -08001132 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001133 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001134 {
1135 // Aquire lock for the access of api_format.
1136 // The lock is released immediately due to the conditional
1137 // reinitialization.
1138 rtc::CritScope cs_capture(&crit_capture_);
1139 // TODO(ajm): The input and output rates and channels are currently
1140 // constrained to be identical in the int16 interface.
1141 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001142
1143 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001144 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001145 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1146 processing_config.input_stream().set_num_channels(frame->num_channels_);
1147 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1148 processing_config.output_stream().set_num_channels(frame->num_channels_);
1149
peahdf3efa82015-11-28 12:35:15 -08001150 {
1151 // Do conditional reinitialization.
1152 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001153 RETURN_ON_ERR(
1154 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001155 }
1156 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001157 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001158 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001159 return kBadDataLengthError;
1160 }
1161
aleloi868f32f2017-05-23 07:20:05 -07001162 if (aec_dump_) {
1163 RecordUnprocessedCaptureStream(*frame);
1164 }
1165
peahdf3efa82015-11-28 12:35:15 -08001166 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001167 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001168 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001169 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1170 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001171
aleloi868f32f2017-05-23 07:20:05 -07001172 if (aec_dump_) {
1173 RecordProcessedCaptureStream(*frame);
1174 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001175
1176 return kNoError;
1177}
1178
peahde65ddc2016-09-16 15:02:15 -07001179int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001180 HandleRuntimeSettings();
1181
peahb58a1582016-03-15 09:34:24 -07001182 // Ensure that not both the AEC and AECM are active at the same time.
1183 // TODO(peah): Simplify once the public API Enable functions for these
1184 // are moved to APM.
1185 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1186 public_submodules_->echo_control_mobile->is_enabled()));
1187
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001188 MaybeUpdateHistograms();
1189
peahde65ddc2016-09-16 15:02:15 -07001190 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001191
peah1b08dc32016-12-20 13:45:58 -08001192 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001193 capture_buffer->channels_const()[0],
1194 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001195 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1196 if (log_rms) {
1197 capture_rms_interval_counter_ = 0;
1198 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001199 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1200 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1201 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1202 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001203 }
1204
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001205 if (private_submodules_->echo_controller) {
Per Åhgren9aed31c2017-06-29 20:23:27 +02001206 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1207 // issues have been addressed.
1208 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001209 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001210 }
1211
peahbe615622016-02-13 16:40:47 -08001212 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001213 public_submodules_->gain_control->is_enabled()) {
1214 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001215 capture_buffer->channels()[0], capture_buffer->num_channels(),
1216 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001217 }
1218
peah2ace3f92016-09-10 04:42:27 -07001219 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1220 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001221 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1222 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001223 }
1224
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001225 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001226 // Force down-mixing of the number of channels after the detection of
1227 // capture signal saturation.
1228 // TODO(peah): Look into ensuring that this kind of tampering with the
1229 // AudioBuffer functionality should not be needed.
1230 capture_buffer->set_num_channels(1);
1231 }
1232
aluebsb2328d12016-01-11 20:32:29 -08001233 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001234 private_submodules_->beamformer->AnalyzeChunk(
1235 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001236 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001237 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001238 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001239
peahe0eae3c2016-12-14 01:16:23 -08001240 // TODO(peah): Move the AEC3 low-cut filter to this place.
1241 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001242 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001243 private_submodules_->low_cut_filter->Process(capture_buffer);
1244 }
peahde65ddc2016-09-16 15:02:15 -07001245 RETURN_ON_ERR(
1246 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1247 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001248
1249 // Ensure that the stream delay was set before the call to the
1250 // AEC ProcessCaptureAudio function.
1251 if (public_submodules_->echo_cancellation->is_enabled() &&
1252 !was_stream_delay_set()) {
1253 return AudioProcessing::kStreamParameterNotSetError;
1254 }
1255
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001256 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001257 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1258
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001259 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001260 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001261 } else {
1262 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1263 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001264 }
1265
peahdf3efa82015-11-28 12:35:15 -08001266 if (public_submodules_->echo_control_mobile->is_enabled() &&
1267 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001268 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001269 }
peahde65ddc2016-09-16 15:02:15 -07001270 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001271#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001272 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001273 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001274 const int gain_db =
1275 public_submodules_->gain_control->is_enabled()
1276 ? public_submodules_->gain_control->compression_gain_db()
1277 : 0;
1278 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001279 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001280 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001281 }
peah1bcfce52016-08-26 07:16:04 -07001282#endif
peah253534d2016-03-15 04:32:28 -07001283
1284 // Ensure that the stream delay was set before the call to the
1285 // AECM ProcessCaptureAudio function.
1286 if (public_submodules_->echo_control_mobile->is_enabled() &&
1287 !was_stream_delay_set()) {
1288 return AudioProcessing::kStreamParameterNotSetError;
1289 }
1290
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001291 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001292 public_submodules_->echo_cancellation->is_enabled())) {
1293 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1294 capture_buffer, stream_delay_ms()));
1295 }
ivoc9f4a4a02016-10-28 05:39:16 -07001296
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001297 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001298 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001299 }
1300
peahde65ddc2016-09-16 15:02:15 -07001301 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001302
peahbe615622016-02-13 16:40:47 -08001303 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001304 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001305 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001306 private_submodules_->beamformer->is_target_present())) {
1307 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001308 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1309 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001310 }
peahb8fbb542016-03-15 02:28:08 -07001311 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001312 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001313
peah2ace3f92016-09-10 04:42:27 -07001314 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1315 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001316 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1317 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001318 }
1319
peah9e6a2902017-05-15 07:19:21 -07001320 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001321 RTC_DCHECK(private_submodules_->echo_detector);
1322 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001323 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1324 capture_buffer->num_frames()));
1325 }
1326
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001327 // TODO(aluebs): Investigate if the transient suppression placement should be
1328 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001329 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001330 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001331 private_submodules_->agc_manager.get()
1332 ? private_submodules_->agc_manager->voice_probability()
1333 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001334
peahdf3efa82015-11-28 12:35:15 -08001335 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001336 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1337 capture_buffer->num_channels(),
1338 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1339 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1340 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001341 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001342 }
1343
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001344 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001345 private_submodules_->gain_controller2->Process(capture_buffer);
1346 }
1347
Sam Zackrisson0beac582017-09-25 12:04:02 +02001348 if (private_submodules_->capture_post_processor) {
1349 private_submodules_->capture_post_processor->Process(capture_buffer);
1350 }
1351
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001352 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001353 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001354
peah1b08dc32016-12-20 13:45:58 -08001355 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1356 capture_buffer->channels_const()[0],
1357 capture_nonlocked_.capture_processing_format.num_frames()));
1358 if (log_rms) {
1359 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1360 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1361 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1362 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1363 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1364 }
1365
peahdf3efa82015-11-28 12:35:15 -08001366 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001367 return kNoError;
1368}
1369
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001370int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001371 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001372 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001373 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001374 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001375 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001376 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001377 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001378 };
1379 if (samples_per_channel != reverse_config.num_frames()) {
1380 return kBadDataLengthError;
1381 }
peahdf3efa82015-11-28 12:35:15 -08001382 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001383}
1384
peahde65ddc2016-09-16 15:02:15 -07001385int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1386 const StreamConfig& input_config,
1387 const StreamConfig& output_config,
1388 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001389 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001390 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001391 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001392 if (submodule_states_.RenderMultiBandProcessingActive() ||
1393 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001394 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1395 dest);
peah2ace3f92016-09-10 04:42:27 -07001396 } else if (formats_.api_format.reverse_input_stream() !=
1397 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001398 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1399 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001400 } else {
peahde65ddc2016-09-16 15:02:15 -07001401 CopyAudioIfNeeded(src, input_config.num_frames(),
1402 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001403 }
1404
1405 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001406}
1407
peahdf3efa82015-11-28 12:35:15 -08001408int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001409 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001410 const StreamConfig& input_config,
1411 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001412 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001413 return kNullPointerError;
1414 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001415
peahde65ddc2016-09-16 15:02:15 -07001416 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001417 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001418 }
1419
peahdf3efa82015-11-28 12:35:15 -08001420 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001421 processing_config.reverse_input_stream() = input_config;
1422 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001423
peahdf3efa82015-11-28 12:35:15 -08001424 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001425 RTC_DCHECK_EQ(input_config.num_frames(),
1426 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001427
aleloi868f32f2017-05-23 07:20:05 -07001428 if (aec_dump_) {
1429 const size_t channel_size =
1430 formats_.api_format.reverse_input_stream().num_frames();
1431 const size_t num_channels =
1432 formats_.api_format.reverse_input_stream().num_channels();
1433 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001434 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001435 }
peahdf3efa82015-11-28 12:35:15 -08001436 render_.render_audio->CopyFrom(src,
1437 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001438 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001439}
1440
1441int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001442 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001443 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001444 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001445 return kNullPointerError;
1446 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001447 // Must be a native rate.
1448 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1449 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001450 frame->sample_rate_hz_ != kSampleRate32kHz &&
1451 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001452 return kBadSampleRateError;
1453 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001454
Michael Graczyk86c6d332015-07-23 11:41:39 -07001455 if (frame->num_channels_ <= 0) {
1456 return kBadNumberChannelsError;
1457 }
1458
peahdf3efa82015-11-28 12:35:15 -08001459 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001460 processing_config.reverse_input_stream().set_sample_rate_hz(
1461 frame->sample_rate_hz_);
1462 processing_config.reverse_input_stream().set_num_channels(
1463 frame->num_channels_);
1464 processing_config.reverse_output_stream().set_sample_rate_hz(
1465 frame->sample_rate_hz_);
1466 processing_config.reverse_output_stream().set_num_channels(
1467 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001468
peahdf3efa82015-11-28 12:35:15 -08001469 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001470 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001471 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001472 return kBadDataLengthError;
1473 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001474
aleloi868f32f2017-05-23 07:20:05 -07001475 if (aec_dump_) {
1476 aec_dump_->WriteRenderStreamMessage(*frame);
1477 }
1478
peahdf3efa82015-11-28 12:35:15 -08001479 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001480 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001481 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001482 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1483 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001484 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001485}
niklase@google.com470e71d2011-07-07 08:21:25 +00001486
peahde65ddc2016-09-16 15:02:15 -07001487int AudioProcessingImpl::ProcessRenderStreamLocked() {
1488 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001489
1490 QueueNonbandedRenderAudio(render_buffer);
1491
Alex Loiko5825aa62017-12-18 16:02:40 +01001492 if (private_submodules_->render_pre_processor) {
1493 private_submodules_->render_pre_processor->Process(render_buffer);
1494 }
1495
peah2ace3f92016-09-10 04:42:27 -07001496 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001497 SampleRateSupportsMultiBand(
1498 formats_.render_processing_format.sample_rate_hz())) {
1499 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001500 }
1501
peah1bcfce52016-08-26 07:16:04 -07001502#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001503 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001504 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001505 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001506 }
peah1bcfce52016-08-26 07:16:04 -07001507#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001508
peahce4d9152017-05-19 01:28:05 -07001509 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1510 QueueBandedRenderAudio(render_buffer);
1511 }
1512
peahe0eae3c2016-12-14 01:16:23 -08001513 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001514 if (private_submodules_->echo_controller) {
1515 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001516 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001517
peah2ace3f92016-09-10 04:42:27 -07001518 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001519 SampleRateSupportsMultiBand(
1520 formats_.render_processing_format.sample_rate_hz())) {
1521 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001522 }
1523
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001524 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001525}
1526
1527int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001528 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001529 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001530 capture_.was_stream_delay_set = true;
1531 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001532
niklase@google.com470e71d2011-07-07 08:21:25 +00001533 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001534 delay = 0;
1535 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001536 }
1537
1538 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1539 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001540 delay = 500;
1541 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001542 }
1543
peahdf3efa82015-11-28 12:35:15 -08001544 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001545 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001546}
1547
1548int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001549 // Used as callback from submodules, hence locking is not allowed.
1550 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001551}
1552
1553bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001554 // Used as callback from submodules, hence locking is not allowed.
1555 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001556}
1557
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001558void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001559 rtc::CritScope cs(&crit_capture_);
1560 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001561}
1562
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001563void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001564 rtc::CritScope cs(&crit_capture_);
1565 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001566}
1567
1568int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001569 rtc::CritScope cs(&crit_capture_);
1570 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001571}
1572
aleloi868f32f2017-05-23 07:20:05 -07001573void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1574 RTC_DCHECK(aec_dump);
1575 rtc::CritScope cs_render(&crit_render_);
1576 rtc::CritScope cs_capture(&crit_capture_);
1577
1578 // The previously attached AecDump will be destroyed with the
1579 // 'aec_dump' parameter, which is after locks are released.
1580 aec_dump_.swap(aec_dump);
1581 WriteAecDumpConfigMessage(true);
1582 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1583}
1584
1585void AudioProcessingImpl::DetachAecDump() {
1586 // The d-tor of a task-queue based AecDump blocks until all pending
1587 // tasks are done. This construction avoids blocking while holding
1588 // the render and capture locks.
1589 std::unique_ptr<AecDump> aec_dump = nullptr;
1590 {
1591 rtc::CritScope cs_render(&crit_render_);
1592 rtc::CritScope cs_capture(&crit_capture_);
1593 aec_dump = std::move(aec_dump_);
1594 }
1595}
1596
Sam Zackrisson4d364492018-03-02 16:03:21 +01001597void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1598 std::unique_ptr<AudioGenerator> audio_generator) {
1599 // TODO(bugs.webrtc.org/8882) Stub.
1600 // Reset internal audio generator with audio_generator.
1601}
1602
1603void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1604 // TODO(bugs.webrtc.org/8882) Stub.
1605 // Delete audio generator, if one is attached.
1606}
1607
ivoc4e477a12017-01-15 08:29:46 -08001608AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1609 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1610 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1611 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1612 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1613}
1614
1615AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1616 const AudioProcessingStatistics& other) = default;
1617
1618AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1619 default;
1620
ivoc3e9a5372016-10-28 07:55:33 -07001621// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1622AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1623 const {
1624 return AudioProcessingStatistics();
1625}
1626
Ivo Creusenae026092017-11-20 13:07:16 +01001627// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001628AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001629 bool has_remote_tracks) const {
1630 return AudioProcessingStats();
1631}
1632
ivoc3e9a5372016-10-28 07:55:33 -07001633AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1634 const {
1635 AudioProcessingStatistics stats;
1636 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001637 if (private_submodules_->echo_controller) {
1638 rtc::CritScope cs_capture(&crit_capture_);
1639 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1640 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1641 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1642 // Instant value will also be used for min, max and average.
1643 stats.echo_return_loss.Set(erl, erl, erl, erl);
1644 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1645 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1646 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001647 stats.a_nlp.Set(metrics.a_nlp);
1648 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1649 stats.echo_return_loss.Set(metrics.echo_return_loss);
1650 stats.echo_return_loss_enhancement.Set(
1651 metrics.echo_return_loss_enhancement);
1652 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1653 }
ivoc9c192b22017-03-16 04:22:14 -07001654 {
1655 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001656 RTC_DCHECK(private_submodules_->echo_detector);
1657 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1658 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001659 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001660 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001661 }
ivoc3e9a5372016-10-28 07:55:33 -07001662 public_submodules_->echo_cancellation->GetDelayMetrics(
1663 &stats.delay_median, &stats.delay_standard_deviation,
1664 &stats.fraction_poor_delays);
1665 return stats;
1666}
1667
Ivo Creusen56d46092017-11-24 17:29:59 +01001668AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001669 bool has_remote_tracks) const {
1670 AudioProcessingStats stats;
1671 if (has_remote_tracks) {
1672 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001673 if (private_submodules_->echo_controller) {
1674 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001675 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1676 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001677 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001678 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001679 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001680 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1681 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001682 if (metrics.divergent_filter_fraction != -1.0f) {
1683 stats.divergent_filter_fraction =
1684 rtc::Optional<double>(metrics.divergent_filter_fraction);
1685 }
1686 if (metrics.echo_return_loss.instant != -100) {
1687 stats.echo_return_loss =
1688 rtc::Optional<double>(metrics.echo_return_loss.instant);
1689 }
1690 if (metrics.echo_return_loss_enhancement.instant != -100) {
1691 stats.echo_return_loss_enhancement =
1692 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1693 }
1694 }
1695 if (config_.residual_echo_detector.enabled) {
1696 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001697 RTC_DCHECK(private_submodules_->echo_detector);
1698 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1699 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001700 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001701 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001702 }
1703 int delay_median, delay_std;
1704 float fraction_poor_delays;
1705 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1706 &delay_median, &delay_std, &fraction_poor_delays) ==
1707 Error::kNoError) {
1708 if (delay_median >= 0) {
1709 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1710 }
1711 if (delay_std >= 0) {
1712 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1713 }
1714 }
1715 }
1716 return stats;
1717}
1718
niklase@google.com470e71d2011-07-07 08:21:25 +00001719EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001720 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001721}
1722
1723EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001724 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001725}
1726
1727GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001728 if (constants_.use_experimental_agc) {
1729 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001730 }
peahbfa97112016-03-10 21:09:04 -08001731 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001732}
1733
1734HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001735 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001736}
1737
1738LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001739 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001740}
1741
1742NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001743 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001744}
1745
1746VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001747 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001748}
1749
peah8271d042016-11-22 07:24:52 -08001750void AudioProcessingImpl::MutateConfig(
1751 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1752 rtc::CritScope cs_render(&crit_render_);
1753 rtc::CritScope cs_capture(&crit_capture_);
1754 mutator(&config_);
1755 ApplyConfig(config_);
1756}
1757
1758AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1759 rtc::CritScope cs_render(&crit_render_);
1760 rtc::CritScope cs_capture(&crit_capture_);
1761 return config_;
1762}
1763
peah2ace3f92016-09-10 04:42:27 -07001764bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1765 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001766 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001767 public_submodules_->echo_cancellation->is_enabled(),
1768 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001769 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001770 public_submodules_->noise_suppression->is_enabled(),
1771 capture_nonlocked_.intelligibility_enabled,
1772 capture_nonlocked_.beamformer_enabled,
1773 public_submodules_->gain_control->is_enabled(),
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001774 config_.gain_controller2.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001775 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001776 public_submodules_->voice_detection->is_enabled(),
1777 public_submodules_->level_estimator->is_enabled(),
1778 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001779}
1780
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001781
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001782void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001783 if (capture_.transient_suppressor_enabled) {
1784 if (!public_submodules_->transient_suppressor.get()) {
1785 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001786 }
peahdf3efa82015-11-28 12:35:15 -08001787 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001788 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1789 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001790 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001791}
1792
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001793void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001794 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001795 if (!private_submodules_->beamformer) {
1796 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001797 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001798 }
peahdf3efa82015-11-28 12:35:15 -08001799 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1800 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001801 }
1802}
1803
ekmeyerson60d9b332015-08-14 10:35:55 -07001804void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001805#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001806 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001807 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001808 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001809 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001810 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001811 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001812 }
peah1bcfce52016-08-26 07:16:04 -07001813#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001814}
1815
peah8271d042016-11-22 07:24:52 -08001816void AudioProcessingImpl::InitializeLowCutFilter() {
1817 if (config_.high_pass_filter.enabled) {
1818 private_submodules_->low_cut_filter.reset(
1819 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1820 } else {
1821 private_submodules_->low_cut_filter.reset();
1822 }
1823}
alessiob3ec96df2017-05-22 06:57:06 -07001824
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001825void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001826 if (echo_control_factory_) {
1827 private_submodules_->echo_controller =
1828 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001829 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001830 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001831 }
1832}
peah8271d042016-11-22 07:24:52 -08001833
alessiob3ec96df2017-05-22 06:57:06 -07001834void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001835 if (config_.gain_controller2.enabled) {
1836 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001837 }
1838}
1839
ivoc9f4a4a02016-10-28 05:39:16 -07001840void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001841 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001842 private_submodules_->echo_detector->Initialize(
1843 proc_sample_rate_hz(), num_proc_channels(),
1844 formats_.render_processing_format.sample_rate_hz(),
1845 formats_.render_processing_format.num_channels());
ivoc9f4a4a02016-10-28 05:39:16 -07001846}
1847
Sam Zackrisson0beac582017-09-25 12:04:02 +02001848void AudioProcessingImpl::InitializePostProcessor() {
1849 if (private_submodules_->capture_post_processor) {
1850 private_submodules_->capture_post_processor->Initialize(
1851 proc_sample_rate_hz(), num_proc_channels());
1852 }
1853}
1854
Alex Loiko5825aa62017-12-18 16:02:40 +01001855void AudioProcessingImpl::InitializePreProcessor() {
1856 if (private_submodules_->render_pre_processor) {
1857 private_submodules_->render_pre_processor->Initialize(
1858 formats_.render_processing_format.sample_rate_hz(),
1859 formats_.render_processing_format.num_channels());
1860 }
1861}
1862
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001863void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001864 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001865
1866 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001867 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001868 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001869 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001870 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001871 capture_.stream_delay_jumps = 0;
1872 }
1873 if (capture_.aec_system_delay_jumps == -1 &&
1874 echo_cancellation()->stream_has_echo()) {
1875 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001876 }
1877
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001878 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001879 const int diff_stream_delay_ms =
1880 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1881 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1882 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001883 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1884 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001885 if (capture_.stream_delay_jumps == -1) {
1886 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001887 }
peahdf3efa82015-11-28 12:35:15 -08001888 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001889 }
peahdf3efa82015-11-28 12:35:15 -08001890 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001891
1892 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001893 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001894 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001895 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001896 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001897 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1898 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001899 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001900 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001901 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001902 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001903 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1904 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1905 100);
peahdf3efa82015-11-28 12:35:15 -08001906 if (capture_.aec_system_delay_jumps == -1) {
1907 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001908 }
peahdf3efa82015-11-28 12:35:15 -08001909 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001910 }
peahdf3efa82015-11-28 12:35:15 -08001911 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001912 }
1913}
1914
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001915void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001916 // Run in a single-threaded manner.
1917 rtc::CritScope cs_render(&crit_render_);
1918 rtc::CritScope cs_capture(&crit_capture_);
1919
1920 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001921 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001922 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001923 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001924 }
peahdf3efa82015-11-28 12:35:15 -08001925 capture_.stream_delay_jumps = -1;
1926 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001927
peahdf3efa82015-11-28 12:35:15 -08001928 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001929 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1930 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001931 }
peahdf3efa82015-11-28 12:35:15 -08001932 capture_.aec_system_delay_jumps = -1;
1933 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001934}
1935
aleloi868f32f2017-05-23 07:20:05 -07001936void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1937 if (!aec_dump_) {
1938 return;
1939 }
1940 std::string experiments_description =
1941 public_submodules_->echo_cancellation->GetExperimentsDescription();
1942 // TODO(peah): Add semicolon-separated concatenations of experiment
1943 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001944 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1945 experiments_description += "AgcClippingLevelExperiment;";
1946 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001947 if (capture_nonlocked_.echo_controller_enabled) {
1948 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001949 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001950 if (config_.gain_controller2.enabled) {
1951 experiments_description += "GainController2;";
1952 }
aleloi868f32f2017-05-23 07:20:05 -07001953
1954 InternalAPMConfig apm_config;
1955
1956 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1957 apm_config.aec_delay_agnostic_enabled =
1958 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1959 apm_config.aec_drift_compensation_enabled =
1960 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1961 apm_config.aec_extended_filter_enabled =
1962 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1963 apm_config.aec_suppression_level = static_cast<int>(
1964 public_submodules_->echo_cancellation->suppression_level());
1965
1966 apm_config.aecm_enabled =
1967 public_submodules_->echo_control_mobile->is_enabled();
1968 apm_config.aecm_comfort_noise_enabled =
1969 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1970 apm_config.aecm_routing_mode =
1971 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1972
1973 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1974 apm_config.agc_mode =
1975 static_cast<int>(public_submodules_->gain_control->mode());
1976 apm_config.agc_limiter_enabled =
1977 public_submodules_->gain_control->is_limiter_enabled();
1978 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1979
1980 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1981
1982 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1983 apm_config.ns_level =
1984 static_cast<int>(public_submodules_->noise_suppression->level());
1985
1986 apm_config.transient_suppression_enabled =
1987 capture_.transient_suppressor_enabled;
1988 apm_config.intelligibility_enhancer_enabled =
1989 capture_nonlocked_.intelligibility_enabled;
1990 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001991 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1992 apm_config.pre_amplifier_fixed_gain_factor =
1993 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001994
1995 if (!forced && apm_config == apm_config_for_aec_dump_) {
1996 return;
1997 }
1998 aec_dump_->WriteConfig(apm_config);
1999 apm_config_for_aec_dump_ = apm_config;
2000}
2001
2002void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2003 const float* const* src) {
2004 RTC_DCHECK(aec_dump_);
2005 WriteAecDumpConfigMessage(false);
2006
2007 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2008 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2009 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002010 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002011 RecordAudioProcessingState();
2012}
2013
2014void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2015 const AudioFrame& capture_frame) {
2016 RTC_DCHECK(aec_dump_);
2017 WriteAecDumpConfigMessage(false);
2018
2019 aec_dump_->AddCaptureStreamInput(capture_frame);
2020 RecordAudioProcessingState();
2021}
2022
2023void AudioProcessingImpl::RecordProcessedCaptureStream(
2024 const float* const* processed_capture_stream) {
2025 RTC_DCHECK(aec_dump_);
2026
2027 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2028 const size_t num_channels =
2029 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002030 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2031 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002032 aec_dump_->WriteCaptureStreamMessage();
2033}
2034
2035void AudioProcessingImpl::RecordProcessedCaptureStream(
2036 const AudioFrame& processed_capture_frame) {
2037 RTC_DCHECK(aec_dump_);
2038
2039 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2040 aec_dump_->WriteCaptureStreamMessage();
2041}
2042
2043void AudioProcessingImpl::RecordAudioProcessingState() {
2044 RTC_DCHECK(aec_dump_);
2045 AecDump::AudioProcessingState audio_proc_state;
2046 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2047 audio_proc_state.drift =
2048 public_submodules_->echo_cancellation->stream_drift_samples();
2049 audio_proc_state.level = gain_control()->stream_analog_level();
2050 audio_proc_state.keypress = capture_.key_pressed;
2051 aec_dump_->AddAudioProcessingState(audio_proc_state);
2052}
2053
kwiberg83ffe452016-08-29 14:46:07 -07002054AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2055 bool transient_suppressor_enabled,
2056 const std::vector<Point>& array_geometry,
2057 SphericalPointf target_direction)
2058 : aec_system_delay_jumps(-1),
2059 delay_offset_ms(0),
2060 was_stream_delay_set(false),
2061 last_stream_delay_ms(0),
2062 last_aec_system_delay_ms(0),
2063 stream_delay_jumps(-1),
2064 output_will_be_muted(false),
2065 key_pressed(false),
2066 transient_suppressor_enabled(transient_suppressor_enabled),
2067 array_geometry(array_geometry),
2068 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002069 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002070 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002071 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002072
2073AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2074
2075AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2076
2077AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2078
niklase@google.com470e71d2011-07-07 08:21:25 +00002079} // namespace webrtc