blob: f25c430c6a9a35a16413b9297ea565dc78abd76a [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;
peah88ac8532016-09-12 16:47:25 -0700720}
721
722void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800723 // Run in a single-threaded manner when setting the extra options.
724 rtc::CritScope cs_render(&crit_render_);
725 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000726
peahb624d8c2016-03-05 03:01:14 -0800727 public_submodules_->echo_cancellation->SetExtraOptions(config);
728
peahdf3efa82015-11-28 12:35:15 -0800729 if (capture_.transient_suppressor_enabled !=
730 config.Get<ExperimentalNs>().enabled) {
731 capture_.transient_suppressor_enabled =
732 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000733 InitializeTransient();
734 }
aluebs2a346882016-01-11 18:04:30 -0800735
peah1bcfce52016-08-26 07:16:04 -0700736#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700737 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700738 config.Get<Intelligibility>().enabled) {
739 capture_nonlocked_.intelligibility_enabled =
740 config.Get<Intelligibility>().enabled;
741 InitializeIntelligibility();
742 }
peah1bcfce52016-08-26 07:16:04 -0700743#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700744
aluebs2a346882016-01-11 18:04:30 -0800745#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800746 if (capture_nonlocked_.beamformer_enabled !=
747 config.Get<Beamforming>().enabled) {
748 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800749 if (config.Get<Beamforming>().array_geometry.size() > 1) {
750 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
751 }
752 capture_.target_direction = config.Get<Beamforming>().target_direction;
753 InitializeBeamformer();
754 }
755#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000756}
757
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000758int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800759 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700760 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000761}
762
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000763int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800764 // Used as callback from submodules, hence locking is not allowed.
765 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000766}
767
Peter Kasting69558702016-01-12 16:26:35 -0800768size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800769 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700770 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000771}
772
Peter Kasting69558702016-01-12 16:26:35 -0800773size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800774 // Used as callback from submodules, hence locking is not allowed.
775 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000776}
777
Peter Kasting69558702016-01-12 16:26:35 -0800778size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800779 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700780 return (capture_nonlocked_.beamformer_enabled ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200781 capture_nonlocked_.echo_controller_enabled)
peahedddac52017-05-16 01:08:58 -0700782 ? 1
783 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800784}
785
Peter Kasting69558702016-01-12 16:26:35 -0800786size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800787 // Used as callback from submodules, hence locking is not allowed.
788 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000789}
790
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000791void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800792 rtc::CritScope cs(&crit_capture_);
793 capture_.output_will_be_muted = muted;
794 if (private_submodules_->agc_manager.get()) {
795 private_submodules_->agc_manager->SetCaptureMuted(
796 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000797 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000798}
799
Alessio Bazzicac054e782018-04-16 12:10:09 +0200800void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
801 RTC_DCHECK(setting.type() != RuntimeSetting::Type::kNotSpecified);
802 runtime_settings_enqueuer_.Enqueue(setting);
803}
804
805AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
806 SwapQueue<RuntimeSetting>* runtime_settings)
807 : runtime_settings_(runtime_settings) {
808 RTC_DCHECK(runtime_settings_);
809}
810
811AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
812 default;
813
814void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
815 RuntimeSetting setting) {
816 size_t remaining_attempts = 10;
817 while (!runtime_settings_->Insert(&setting) && remaining_attempts-- > 0) {
818 RuntimeSetting setting_to_discard;
819 if (runtime_settings_->Remove(&setting_to_discard))
820 RTC_LOG(LS_ERROR)
821 << "The runtime settings queue is full. Oldest setting discarded.";
822 }
823 if (remaining_attempts == 0)
824 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
825}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000826
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000827int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700828 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000829 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000830 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000831 int output_sample_rate_hz,
832 ChannelLayout output_layout,
833 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800834 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800835 StreamConfig input_stream;
836 StreamConfig output_stream;
837 {
838 // Access the formats_.api_format.input_stream beneath the capture lock.
839 // The lock must be released as it is later required in the call
840 // to ProcessStream(,,,);
841 rtc::CritScope cs(&crit_capture_);
842 input_stream = formats_.api_format.input_stream();
843 output_stream = formats_.api_format.output_stream();
844 }
845
Michael Graczyk86c6d332015-07-23 11:41:39 -0700846 input_stream.set_sample_rate_hz(input_sample_rate_hz);
847 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
848 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700849 output_stream.set_sample_rate_hz(output_sample_rate_hz);
850 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
851 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
852
853 if (samples_per_channel != input_stream.num_frames()) {
854 return kBadDataLengthError;
855 }
856 return ProcessStream(src, input_stream, output_stream, dest);
857}
858
859int AudioProcessingImpl::ProcessStream(const float* const* src,
860 const StreamConfig& input_config,
861 const StreamConfig& output_config,
862 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800863 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800864 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700865 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800866 {
867 // Acquire the capture lock in order to safely call the function
868 // that retrieves the render side data. This function accesses apm
869 // getters that need the capture lock held when being called.
870 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700871 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800872
873 if (!src || !dest) {
874 return kNullPointerError;
875 }
876
877 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700878 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000879 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000880
Michael Graczyk86c6d332015-07-23 11:41:39 -0700881 processing_config.input_stream() = input_config;
882 processing_config.output_stream() = output_config;
883
peahdf3efa82015-11-28 12:35:15 -0800884 {
885 // Do conditional reinitialization.
886 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700887 RETURN_ON_ERR(
888 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800889 }
890 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700891 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
892 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000893
aleloi868f32f2017-05-23 07:20:05 -0700894 if (aec_dump_) {
895 RecordUnprocessedCaptureStream(src);
896 }
897
peahdf3efa82015-11-28 12:35:15 -0800898 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700899 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800900 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000901
aleloi868f32f2017-05-23 07:20:05 -0700902 if (aec_dump_) {
903 RecordProcessedCaptureStream(dest);
904 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000905 return kNoError;
906}
907
Alessio Bazzicac054e782018-04-16 12:10:09 +0200908void AudioProcessingImpl::HandleRuntimeSettings() {
909 RuntimeSetting setting;
910 while (runtime_settings_->Remove(&setting)) {
911 RTC_DCHECK(setting.type() != RuntimeSetting::Type::kNotSpecified);
912 switch (setting.type()) {
913 case RuntimeSetting::Type::kCapturePreGain:
914 // TODO(bugs.chromium.org/9138): Notify
915 // pre-gain when the sub-module is implemented.
916 break;
917 default:
918 RTC_NOTREACHED();
919 break;
920 }
921 }
922}
923
peah9e6a2902017-05-15 07:19:21 -0700924void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700925 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
926 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700927 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700928
kwibergaf476c72016-11-28 15:21:39 -0800929 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700930
931 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700932 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700933 // The data queue is full and needs to be emptied.
934 EmptyQueuedRenderAudio();
935
936 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700937 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700938 RTC_DCHECK(result);
939 }
940
941 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
942 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700943 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700944
945 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700946 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700947 // The data queue is full and needs to be emptied.
948 EmptyQueuedRenderAudio();
949
950 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700951 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700952 RTC_DCHECK(result);
953 }
peah701d6282016-10-25 05:42:20 -0700954
955 if (!constants_.use_experimental_agc) {
956 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
957 // Insert the samples into the queue.
958 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
959 // The data queue is full and needs to be emptied.
960 EmptyQueuedRenderAudio();
961
962 // Retry the insert (should always work).
963 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
964 RTC_DCHECK(result);
965 }
966 }
peah9e6a2902017-05-15 07:19:21 -0700967}
ivoc9f4a4a02016-10-28 05:39:16 -0700968
peah9e6a2902017-05-15 07:19:21 -0700969void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700970 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
971
972 // Insert the samples into the queue.
973 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
974 // The data queue is full and needs to be emptied.
975 EmptyQueuedRenderAudio();
976
977 // Retry the insert (should always work).
978 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
979 RTC_DCHECK(result);
980 }
peah764e3642016-10-22 05:04:30 -0700981}
982
983void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700984 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700985 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700986 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700987 EchoCancellationImpl::NumCancellersRequired(
988 num_output_channels(), num_reverse_channels()));
989
peah701d6282016-10-25 05:42:20 -0700990 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700991 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700992 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700993 EchoControlMobileImpl::NumCancellersRequired(
994 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700995
peah701d6282016-10-25 05:42:20 -0700996 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700997 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700998
ivoc9f4a4a02016-10-28 05:39:16 -0700999 const size_t new_red_render_queue_element_max_size =
1000 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1001
peaha0624602016-10-25 04:45:24 -07001002 // Reallocate the queues if the queue item sizes are too small to fit the
1003 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001004 if (aec_render_queue_element_max_size_ <
1005 new_aec_render_queue_element_max_size) {
1006 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001007
peaha0624602016-10-25 04:45:24 -07001008 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001009 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001010
peah701d6282016-10-25 05:42:20 -07001011 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001012 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1013 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001014 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001015 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001016
peah701d6282016-10-25 05:42:20 -07001017 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1018 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001019 } else {
peah701d6282016-10-25 05:42:20 -07001020 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001021 }
1022
peah701d6282016-10-25 05:42:20 -07001023 if (aecm_render_queue_element_max_size_ <
1024 new_aecm_render_queue_element_max_size) {
1025 aecm_render_queue_element_max_size_ =
1026 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001027
1028 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001029 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001030
peah701d6282016-10-25 05:42:20 -07001031 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001032 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1033 kMaxNumFramesToBuffer, template_queue_element,
1034 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001035 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001036
peah701d6282016-10-25 05:42:20 -07001037 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1038 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001039 } else {
peah701d6282016-10-25 05:42:20 -07001040 aecm_render_signal_queue_->Clear();
1041 }
1042
1043 if (agc_render_queue_element_max_size_ <
1044 new_agc_render_queue_element_max_size) {
1045 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1046
1047 std::vector<int16_t> template_queue_element(
1048 agc_render_queue_element_max_size_);
1049
1050 agc_render_signal_queue_.reset(
1051 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1052 kMaxNumFramesToBuffer, template_queue_element,
1053 RenderQueueItemVerifier<int16_t>(
1054 agc_render_queue_element_max_size_)));
1055
1056 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1057 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1058 } else {
1059 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001060 }
ivoc9f4a4a02016-10-28 05:39:16 -07001061
1062 if (red_render_queue_element_max_size_ <
1063 new_red_render_queue_element_max_size) {
1064 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1065
1066 std::vector<float> template_queue_element(
1067 red_render_queue_element_max_size_);
1068
1069 red_render_signal_queue_.reset(
1070 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1071 kMaxNumFramesToBuffer, template_queue_element,
1072 RenderQueueItemVerifier<float>(
1073 red_render_queue_element_max_size_)));
1074
1075 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1076 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1077 } else {
1078 red_render_signal_queue_->Clear();
1079 }
peah764e3642016-10-22 05:04:30 -07001080}
1081
1082void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1083 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001084 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001085 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001086 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001087 }
1088
peah701d6282016-10-25 05:42:20 -07001089 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001090 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001091 aecm_capture_queue_buffer_);
1092 }
1093
1094 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1095 public_submodules_->gain_control->ProcessRenderAudio(
1096 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001097 }
ivoc9f4a4a02016-10-28 05:39:16 -07001098
1099 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001100 RTC_DCHECK(private_submodules_->echo_detector);
1101 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001102 red_capture_queue_buffer_);
1103 }
peah764e3642016-10-22 05:04:30 -07001104}
1105
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001106int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001107 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001108 {
1109 // Acquire the capture lock in order to safely call the function
1110 // that retrieves the render side data. This function accesses apm
1111 // getters that need the capture lock held when being called.
1112 // The lock needs to be released as
1113 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1114 // as well.
1115 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001116 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001117 }
peahfa6228e2015-11-16 16:27:42 -08001118
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001119 if (!frame) {
1120 return kNullPointerError;
1121 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001122 // Must be a native rate.
1123 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1124 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001125 frame->sample_rate_hz_ != kSampleRate32kHz &&
1126 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001127 return kBadSampleRateError;
1128 }
peah192164e2015-11-17 02:16:45 -08001129
peahdf3efa82015-11-28 12:35:15 -08001130 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001131 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001132 {
1133 // Aquire lock for the access of api_format.
1134 // The lock is released immediately due to the conditional
1135 // reinitialization.
1136 rtc::CritScope cs_capture(&crit_capture_);
1137 // TODO(ajm): The input and output rates and channels are currently
1138 // constrained to be identical in the int16 interface.
1139 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001140
1141 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001142 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001143 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1144 processing_config.input_stream().set_num_channels(frame->num_channels_);
1145 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1146 processing_config.output_stream().set_num_channels(frame->num_channels_);
1147
peahdf3efa82015-11-28 12:35:15 -08001148 {
1149 // Do conditional reinitialization.
1150 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001151 RETURN_ON_ERR(
1152 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001153 }
1154 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001155 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001156 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001157 return kBadDataLengthError;
1158 }
1159
aleloi868f32f2017-05-23 07:20:05 -07001160 if (aec_dump_) {
1161 RecordUnprocessedCaptureStream(*frame);
1162 }
1163
peahdf3efa82015-11-28 12:35:15 -08001164 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001165 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001166 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001167 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1168 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001169
aleloi868f32f2017-05-23 07:20:05 -07001170 if (aec_dump_) {
1171 RecordProcessedCaptureStream(*frame);
1172 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001173
1174 return kNoError;
1175}
1176
peahde65ddc2016-09-16 15:02:15 -07001177int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001178 HandleRuntimeSettings();
1179
peahb58a1582016-03-15 09:34:24 -07001180 // Ensure that not both the AEC and AECM are active at the same time.
1181 // TODO(peah): Simplify once the public API Enable functions for these
1182 // are moved to APM.
1183 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1184 public_submodules_->echo_control_mobile->is_enabled()));
1185
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001186 MaybeUpdateHistograms();
1187
peahde65ddc2016-09-16 15:02:15 -07001188 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001189
peah1b08dc32016-12-20 13:45:58 -08001190 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001191 capture_buffer->channels_const()[0],
1192 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001193 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1194 if (log_rms) {
1195 capture_rms_interval_counter_ = 0;
1196 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001197 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1198 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1199 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1200 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001201 }
1202
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001203 if (private_submodules_->echo_controller) {
Per Åhgren9aed31c2017-06-29 20:23:27 +02001204 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1205 // issues have been addressed.
1206 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001207 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001208 }
1209
peahbe615622016-02-13 16:40:47 -08001210 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001211 public_submodules_->gain_control->is_enabled()) {
1212 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001213 capture_buffer->channels()[0], capture_buffer->num_channels(),
1214 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001215 }
1216
peah2ace3f92016-09-10 04:42:27 -07001217 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1218 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001219 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1220 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001221 }
1222
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001223 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001224 // Force down-mixing of the number of channels after the detection of
1225 // capture signal saturation.
1226 // TODO(peah): Look into ensuring that this kind of tampering with the
1227 // AudioBuffer functionality should not be needed.
1228 capture_buffer->set_num_channels(1);
1229 }
1230
aluebsb2328d12016-01-11 20:32:29 -08001231 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001232 private_submodules_->beamformer->AnalyzeChunk(
1233 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001234 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001235 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001236 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001237
peahe0eae3c2016-12-14 01:16:23 -08001238 // TODO(peah): Move the AEC3 low-cut filter to this place.
1239 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001240 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001241 private_submodules_->low_cut_filter->Process(capture_buffer);
1242 }
peahde65ddc2016-09-16 15:02:15 -07001243 RETURN_ON_ERR(
1244 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1245 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001246
1247 // Ensure that the stream delay was set before the call to the
1248 // AEC ProcessCaptureAudio function.
1249 if (public_submodules_->echo_cancellation->is_enabled() &&
1250 !was_stream_delay_set()) {
1251 return AudioProcessing::kStreamParameterNotSetError;
1252 }
1253
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001254 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001255 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1256
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001257 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001258 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001259 } else {
1260 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1261 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001262 }
1263
peahdf3efa82015-11-28 12:35:15 -08001264 if (public_submodules_->echo_control_mobile->is_enabled() &&
1265 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001266 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001267 }
peahde65ddc2016-09-16 15:02:15 -07001268 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001269#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001270 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001271 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001272 const int gain_db =
1273 public_submodules_->gain_control->is_enabled()
1274 ? public_submodules_->gain_control->compression_gain_db()
1275 : 0;
1276 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001277 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001278 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001279 }
peah1bcfce52016-08-26 07:16:04 -07001280#endif
peah253534d2016-03-15 04:32:28 -07001281
1282 // Ensure that the stream delay was set before the call to the
1283 // AECM ProcessCaptureAudio function.
1284 if (public_submodules_->echo_control_mobile->is_enabled() &&
1285 !was_stream_delay_set()) {
1286 return AudioProcessing::kStreamParameterNotSetError;
1287 }
1288
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001289 if (!(private_submodules_->echo_controller ||
Per Åhgren46537a32017-06-07 10:08:10 +02001290 public_submodules_->echo_cancellation->is_enabled())) {
1291 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1292 capture_buffer, stream_delay_ms()));
1293 }
ivoc9f4a4a02016-10-28 05:39:16 -07001294
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001295 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001296 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001297 }
1298
peahde65ddc2016-09-16 15:02:15 -07001299 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001300
peahbe615622016-02-13 16:40:47 -08001301 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001302 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001303 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001304 private_submodules_->beamformer->is_target_present())) {
1305 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001306 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1307 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001308 }
peahb8fbb542016-03-15 02:28:08 -07001309 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001310 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001311
peah2ace3f92016-09-10 04:42:27 -07001312 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1313 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001314 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1315 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001316 }
1317
peah9e6a2902017-05-15 07:19:21 -07001318 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001319 RTC_DCHECK(private_submodules_->echo_detector);
1320 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001321 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1322 capture_buffer->num_frames()));
1323 }
1324
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001325 // TODO(aluebs): Investigate if the transient suppression placement should be
1326 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001327 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001328 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001329 private_submodules_->agc_manager.get()
1330 ? private_submodules_->agc_manager->voice_probability()
1331 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001332
peahdf3efa82015-11-28 12:35:15 -08001333 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001334 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1335 capture_buffer->num_channels(),
1336 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1337 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1338 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001339 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001340 }
1341
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001342 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001343 private_submodules_->gain_controller2->Process(capture_buffer);
1344 }
1345
Sam Zackrisson0beac582017-09-25 12:04:02 +02001346 if (private_submodules_->capture_post_processor) {
1347 private_submodules_->capture_post_processor->Process(capture_buffer);
1348 }
1349
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001350 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001351 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001352
peah1b08dc32016-12-20 13:45:58 -08001353 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1354 capture_buffer->channels_const()[0],
1355 capture_nonlocked_.capture_processing_format.num_frames()));
1356 if (log_rms) {
1357 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1358 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1359 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1360 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1361 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1362 }
1363
peahdf3efa82015-11-28 12:35:15 -08001364 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001365 return kNoError;
1366}
1367
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001368int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001369 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001370 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001371 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001372 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001373 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001374 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001375 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001376 };
1377 if (samples_per_channel != reverse_config.num_frames()) {
1378 return kBadDataLengthError;
1379 }
peahdf3efa82015-11-28 12:35:15 -08001380 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001381}
1382
peahde65ddc2016-09-16 15:02:15 -07001383int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1384 const StreamConfig& input_config,
1385 const StreamConfig& output_config,
1386 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001387 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001388 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001389 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001390 if (submodule_states_.RenderMultiBandProcessingActive() ||
1391 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001392 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1393 dest);
peah2ace3f92016-09-10 04:42:27 -07001394 } else if (formats_.api_format.reverse_input_stream() !=
1395 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001396 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1397 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001398 } else {
peahde65ddc2016-09-16 15:02:15 -07001399 CopyAudioIfNeeded(src, input_config.num_frames(),
1400 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001401 }
1402
1403 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001404}
1405
peahdf3efa82015-11-28 12:35:15 -08001406int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001407 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001408 const StreamConfig& input_config,
1409 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001410 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001411 return kNullPointerError;
1412 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001413
peahde65ddc2016-09-16 15:02:15 -07001414 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001415 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001416 }
1417
peahdf3efa82015-11-28 12:35:15 -08001418 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001419 processing_config.reverse_input_stream() = input_config;
1420 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001421
peahdf3efa82015-11-28 12:35:15 -08001422 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001423 RTC_DCHECK_EQ(input_config.num_frames(),
1424 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001425
aleloi868f32f2017-05-23 07:20:05 -07001426 if (aec_dump_) {
1427 const size_t channel_size =
1428 formats_.api_format.reverse_input_stream().num_frames();
1429 const size_t num_channels =
1430 formats_.api_format.reverse_input_stream().num_channels();
1431 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001432 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001433 }
peahdf3efa82015-11-28 12:35:15 -08001434 render_.render_audio->CopyFrom(src,
1435 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001436 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001437}
1438
1439int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001440 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001441 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001442 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001443 return kNullPointerError;
1444 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001445 // Must be a native rate.
1446 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1447 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001448 frame->sample_rate_hz_ != kSampleRate32kHz &&
1449 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001450 return kBadSampleRateError;
1451 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001452
Michael Graczyk86c6d332015-07-23 11:41:39 -07001453 if (frame->num_channels_ <= 0) {
1454 return kBadNumberChannelsError;
1455 }
1456
peahdf3efa82015-11-28 12:35:15 -08001457 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001458 processing_config.reverse_input_stream().set_sample_rate_hz(
1459 frame->sample_rate_hz_);
1460 processing_config.reverse_input_stream().set_num_channels(
1461 frame->num_channels_);
1462 processing_config.reverse_output_stream().set_sample_rate_hz(
1463 frame->sample_rate_hz_);
1464 processing_config.reverse_output_stream().set_num_channels(
1465 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001466
peahdf3efa82015-11-28 12:35:15 -08001467 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001468 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001469 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001470 return kBadDataLengthError;
1471 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001472
aleloi868f32f2017-05-23 07:20:05 -07001473 if (aec_dump_) {
1474 aec_dump_->WriteRenderStreamMessage(*frame);
1475 }
1476
peahdf3efa82015-11-28 12:35:15 -08001477 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001478 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001479 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001480 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1481 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001482 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001483}
niklase@google.com470e71d2011-07-07 08:21:25 +00001484
peahde65ddc2016-09-16 15:02:15 -07001485int AudioProcessingImpl::ProcessRenderStreamLocked() {
1486 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001487
1488 QueueNonbandedRenderAudio(render_buffer);
1489
Alex Loiko5825aa62017-12-18 16:02:40 +01001490 if (private_submodules_->render_pre_processor) {
1491 private_submodules_->render_pre_processor->Process(render_buffer);
1492 }
1493
peah2ace3f92016-09-10 04:42:27 -07001494 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001495 SampleRateSupportsMultiBand(
1496 formats_.render_processing_format.sample_rate_hz())) {
1497 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001498 }
1499
peah1bcfce52016-08-26 07:16:04 -07001500#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001501 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001502 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001503 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001504 }
peah1bcfce52016-08-26 07:16:04 -07001505#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001506
peahce4d9152017-05-19 01:28:05 -07001507 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1508 QueueBandedRenderAudio(render_buffer);
1509 }
1510
peahe0eae3c2016-12-14 01:16:23 -08001511 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001512 if (private_submodules_->echo_controller) {
1513 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001514 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001515
peah2ace3f92016-09-10 04:42:27 -07001516 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001517 SampleRateSupportsMultiBand(
1518 formats_.render_processing_format.sample_rate_hz())) {
1519 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001520 }
1521
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001522 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001523}
1524
1525int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001526 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001527 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001528 capture_.was_stream_delay_set = true;
1529 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001530
niklase@google.com470e71d2011-07-07 08:21:25 +00001531 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001532 delay = 0;
1533 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001534 }
1535
1536 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1537 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001538 delay = 500;
1539 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001540 }
1541
peahdf3efa82015-11-28 12:35:15 -08001542 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001543 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001544}
1545
1546int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001547 // Used as callback from submodules, hence locking is not allowed.
1548 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001549}
1550
1551bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001552 // Used as callback from submodules, hence locking is not allowed.
1553 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001554}
1555
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001556void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001557 rtc::CritScope cs(&crit_capture_);
1558 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001559}
1560
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001561void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001562 rtc::CritScope cs(&crit_capture_);
1563 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001564}
1565
1566int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001567 rtc::CritScope cs(&crit_capture_);
1568 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001569}
1570
aleloi868f32f2017-05-23 07:20:05 -07001571void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1572 RTC_DCHECK(aec_dump);
1573 rtc::CritScope cs_render(&crit_render_);
1574 rtc::CritScope cs_capture(&crit_capture_);
1575
1576 // The previously attached AecDump will be destroyed with the
1577 // 'aec_dump' parameter, which is after locks are released.
1578 aec_dump_.swap(aec_dump);
1579 WriteAecDumpConfigMessage(true);
1580 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1581}
1582
1583void AudioProcessingImpl::DetachAecDump() {
1584 // The d-tor of a task-queue based AecDump blocks until all pending
1585 // tasks are done. This construction avoids blocking while holding
1586 // the render and capture locks.
1587 std::unique_ptr<AecDump> aec_dump = nullptr;
1588 {
1589 rtc::CritScope cs_render(&crit_render_);
1590 rtc::CritScope cs_capture(&crit_capture_);
1591 aec_dump = std::move(aec_dump_);
1592 }
1593}
1594
Sam Zackrisson4d364492018-03-02 16:03:21 +01001595void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1596 std::unique_ptr<AudioGenerator> audio_generator) {
1597 // TODO(bugs.webrtc.org/8882) Stub.
1598 // Reset internal audio generator with audio_generator.
1599}
1600
1601void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1602 // TODO(bugs.webrtc.org/8882) Stub.
1603 // Delete audio generator, if one is attached.
1604}
1605
ivoc4e477a12017-01-15 08:29:46 -08001606AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1607 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1608 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1609 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1610 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1611}
1612
1613AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1614 const AudioProcessingStatistics& other) = default;
1615
1616AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1617 default;
1618
ivoc3e9a5372016-10-28 07:55:33 -07001619// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1620AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1621 const {
1622 return AudioProcessingStatistics();
1623}
1624
Ivo Creusenae026092017-11-20 13:07:16 +01001625// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001626AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001627 bool has_remote_tracks) const {
1628 return AudioProcessingStats();
1629}
1630
ivoc3e9a5372016-10-28 07:55:33 -07001631AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1632 const {
1633 AudioProcessingStatistics stats;
1634 EchoCancellation::Metrics metrics;
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001635 if (private_submodules_->echo_controller) {
1636 rtc::CritScope cs_capture(&crit_capture_);
1637 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1638 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1639 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1640 // Instant value will also be used for min, max and average.
1641 stats.echo_return_loss.Set(erl, erl, erl, erl);
1642 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1643 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1644 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001645 stats.a_nlp.Set(metrics.a_nlp);
1646 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1647 stats.echo_return_loss.Set(metrics.echo_return_loss);
1648 stats.echo_return_loss_enhancement.Set(
1649 metrics.echo_return_loss_enhancement);
1650 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1651 }
ivoc9c192b22017-03-16 04:22:14 -07001652 {
1653 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001654 RTC_DCHECK(private_submodules_->echo_detector);
1655 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1656 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001657 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001658 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001659 }
ivoc3e9a5372016-10-28 07:55:33 -07001660 public_submodules_->echo_cancellation->GetDelayMetrics(
1661 &stats.delay_median, &stats.delay_standard_deviation,
1662 &stats.fraction_poor_delays);
1663 return stats;
1664}
1665
Ivo Creusen56d46092017-11-24 17:29:59 +01001666AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001667 bool has_remote_tracks) const {
1668 AudioProcessingStats stats;
1669 if (has_remote_tracks) {
1670 EchoCancellation::Metrics metrics;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001671 if (private_submodules_->echo_controller) {
1672 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001673 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1674 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001675 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001676 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001677 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001678 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1679 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001680 if (metrics.divergent_filter_fraction != -1.0f) {
1681 stats.divergent_filter_fraction =
1682 rtc::Optional<double>(metrics.divergent_filter_fraction);
1683 }
1684 if (metrics.echo_return_loss.instant != -100) {
1685 stats.echo_return_loss =
1686 rtc::Optional<double>(metrics.echo_return_loss.instant);
1687 }
1688 if (metrics.echo_return_loss_enhancement.instant != -100) {
1689 stats.echo_return_loss_enhancement =
1690 rtc::Optional<double>(metrics.echo_return_loss_enhancement.instant);
1691 }
1692 }
1693 if (config_.residual_echo_detector.enabled) {
1694 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001695 RTC_DCHECK(private_submodules_->echo_detector);
1696 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1697 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001698 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001699 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001700 }
1701 int delay_median, delay_std;
1702 float fraction_poor_delays;
1703 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1704 &delay_median, &delay_std, &fraction_poor_delays) ==
1705 Error::kNoError) {
1706 if (delay_median >= 0) {
1707 stats.delay_median_ms = rtc::Optional<int32_t>(delay_median);
1708 }
1709 if (delay_std >= 0) {
1710 stats.delay_standard_deviation_ms = rtc::Optional<int32_t>(delay_std);
1711 }
1712 }
1713 }
1714 return stats;
1715}
1716
niklase@google.com470e71d2011-07-07 08:21:25 +00001717EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001718 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001719}
1720
1721EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001722 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001723}
1724
1725GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001726 if (constants_.use_experimental_agc) {
1727 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001728 }
peahbfa97112016-03-10 21:09:04 -08001729 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001730}
1731
1732HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001733 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001734}
1735
1736LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001737 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001738}
1739
1740NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001741 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
1744VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001745 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001746}
1747
peah8271d042016-11-22 07:24:52 -08001748void AudioProcessingImpl::MutateConfig(
1749 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1750 rtc::CritScope cs_render(&crit_render_);
1751 rtc::CritScope cs_capture(&crit_capture_);
1752 mutator(&config_);
1753 ApplyConfig(config_);
1754}
1755
1756AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1757 rtc::CritScope cs_render(&crit_render_);
1758 rtc::CritScope cs_capture(&crit_capture_);
1759 return config_;
1760}
1761
peah2ace3f92016-09-10 04:42:27 -07001762bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1763 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001764 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001765 public_submodules_->echo_cancellation->is_enabled(),
1766 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001767 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001768 public_submodules_->noise_suppression->is_enabled(),
1769 capture_nonlocked_.intelligibility_enabled,
1770 capture_nonlocked_.beamformer_enabled,
1771 public_submodules_->gain_control->is_enabled(),
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001772 config_.gain_controller2.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001773 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001774 public_submodules_->voice_detection->is_enabled(),
1775 public_submodules_->level_estimator->is_enabled(),
1776 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001777}
1778
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001779
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001780void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001781 if (capture_.transient_suppressor_enabled) {
1782 if (!public_submodules_->transient_suppressor.get()) {
1783 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001784 }
peahdf3efa82015-11-28 12:35:15 -08001785 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001786 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1787 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001788 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001789}
1790
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001791void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001792 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001793 if (!private_submodules_->beamformer) {
1794 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001795 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001796 }
peahdf3efa82015-11-28 12:35:15 -08001797 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1798 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001799 }
1800}
1801
ekmeyerson60d9b332015-08-14 10:35:55 -07001802void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001803#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001804 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001805 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001806 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001807 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001808 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001809 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001810 }
peah1bcfce52016-08-26 07:16:04 -07001811#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001812}
1813
peah8271d042016-11-22 07:24:52 -08001814void AudioProcessingImpl::InitializeLowCutFilter() {
1815 if (config_.high_pass_filter.enabled) {
1816 private_submodules_->low_cut_filter.reset(
1817 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1818 } else {
1819 private_submodules_->low_cut_filter.reset();
1820 }
1821}
alessiob3ec96df2017-05-22 06:57:06 -07001822
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001823void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001824 if (echo_control_factory_) {
1825 private_submodules_->echo_controller =
1826 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001827 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001828 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001829 }
1830}
peah8271d042016-11-22 07:24:52 -08001831
alessiob3ec96df2017-05-22 06:57:06 -07001832void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001833 if (config_.gain_controller2.enabled) {
1834 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001835 }
1836}
1837
ivoc9f4a4a02016-10-28 05:39:16 -07001838void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001839 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001840 private_submodules_->echo_detector->Initialize(
1841 proc_sample_rate_hz(), num_proc_channels(),
1842 formats_.render_processing_format.sample_rate_hz(),
1843 formats_.render_processing_format.num_channels());
ivoc9f4a4a02016-10-28 05:39:16 -07001844}
1845
Sam Zackrisson0beac582017-09-25 12:04:02 +02001846void AudioProcessingImpl::InitializePostProcessor() {
1847 if (private_submodules_->capture_post_processor) {
1848 private_submodules_->capture_post_processor->Initialize(
1849 proc_sample_rate_hz(), num_proc_channels());
1850 }
1851}
1852
Alex Loiko5825aa62017-12-18 16:02:40 +01001853void AudioProcessingImpl::InitializePreProcessor() {
1854 if (private_submodules_->render_pre_processor) {
1855 private_submodules_->render_pre_processor->Initialize(
1856 formats_.render_processing_format.sample_rate_hz(),
1857 formats_.render_processing_format.num_channels());
1858 }
1859}
1860
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001861void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001862 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001863
1864 if (echo_cancellation()->is_enabled()) {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001865 // Activate delay_jumps_ counters if we know echo_cancellation is running.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001866 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001867 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001868 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001869 capture_.stream_delay_jumps = 0;
1870 }
1871 if (capture_.aec_system_delay_jumps == -1 &&
1872 echo_cancellation()->stream_has_echo()) {
1873 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001874 }
1875
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001876 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001877 const int diff_stream_delay_ms =
1878 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1879 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1880 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001881 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1882 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001883 if (capture_.stream_delay_jumps == -1) {
1884 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001885 }
peahdf3efa82015-11-28 12:35:15 -08001886 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001887 }
peahdf3efa82015-11-28 12:35:15 -08001888 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001889
1890 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001891 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001892 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001893 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001894 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001895 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1896 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001897 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001898 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001899 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001900 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001901 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1902 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1903 100);
peahdf3efa82015-11-28 12:35:15 -08001904 if (capture_.aec_system_delay_jumps == -1) {
1905 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001906 }
peahdf3efa82015-11-28 12:35:15 -08001907 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001908 }
peahdf3efa82015-11-28 12:35:15 -08001909 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001910 }
1911}
1912
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001913void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001914 // Run in a single-threaded manner.
1915 rtc::CritScope cs_render(&crit_render_);
1916 rtc::CritScope cs_capture(&crit_capture_);
1917
1918 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001919 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001920 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001921 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001922 }
peahdf3efa82015-11-28 12:35:15 -08001923 capture_.stream_delay_jumps = -1;
1924 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001925
peahdf3efa82015-11-28 12:35:15 -08001926 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001927 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1928 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001929 }
peahdf3efa82015-11-28 12:35:15 -08001930 capture_.aec_system_delay_jumps = -1;
1931 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001932}
1933
aleloi868f32f2017-05-23 07:20:05 -07001934void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1935 if (!aec_dump_) {
1936 return;
1937 }
1938 std::string experiments_description =
1939 public_submodules_->echo_cancellation->GetExperimentsDescription();
1940 // TODO(peah): Add semicolon-separated concatenations of experiment
1941 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001942 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1943 experiments_description += "AgcClippingLevelExperiment;";
1944 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001945 if (capture_nonlocked_.echo_controller_enabled) {
1946 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001947 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001948 if (config_.gain_controller2.enabled) {
1949 experiments_description += "GainController2;";
1950 }
aleloi868f32f2017-05-23 07:20:05 -07001951
1952 InternalAPMConfig apm_config;
1953
1954 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1955 apm_config.aec_delay_agnostic_enabled =
1956 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1957 apm_config.aec_drift_compensation_enabled =
1958 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1959 apm_config.aec_extended_filter_enabled =
1960 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1961 apm_config.aec_suppression_level = static_cast<int>(
1962 public_submodules_->echo_cancellation->suppression_level());
1963
1964 apm_config.aecm_enabled =
1965 public_submodules_->echo_control_mobile->is_enabled();
1966 apm_config.aecm_comfort_noise_enabled =
1967 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1968 apm_config.aecm_routing_mode =
1969 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1970
1971 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1972 apm_config.agc_mode =
1973 static_cast<int>(public_submodules_->gain_control->mode());
1974 apm_config.agc_limiter_enabled =
1975 public_submodules_->gain_control->is_limiter_enabled();
1976 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1977
1978 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1979
1980 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1981 apm_config.ns_level =
1982 static_cast<int>(public_submodules_->noise_suppression->level());
1983
1984 apm_config.transient_suppression_enabled =
1985 capture_.transient_suppressor_enabled;
1986 apm_config.intelligibility_enhancer_enabled =
1987 capture_nonlocked_.intelligibility_enabled;
1988 apm_config.experiments_description = experiments_description;
1989
1990 if (!forced && apm_config == apm_config_for_aec_dump_) {
1991 return;
1992 }
1993 aec_dump_->WriteConfig(apm_config);
1994 apm_config_for_aec_dump_ = apm_config;
1995}
1996
1997void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1998 const float* const* src) {
1999 RTC_DCHECK(aec_dump_);
2000 WriteAecDumpConfigMessage(false);
2001
2002 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2003 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2004 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002005 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002006 RecordAudioProcessingState();
2007}
2008
2009void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2010 const AudioFrame& capture_frame) {
2011 RTC_DCHECK(aec_dump_);
2012 WriteAecDumpConfigMessage(false);
2013
2014 aec_dump_->AddCaptureStreamInput(capture_frame);
2015 RecordAudioProcessingState();
2016}
2017
2018void AudioProcessingImpl::RecordProcessedCaptureStream(
2019 const float* const* processed_capture_stream) {
2020 RTC_DCHECK(aec_dump_);
2021
2022 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2023 const size_t num_channels =
2024 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002025 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2026 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002027 aec_dump_->WriteCaptureStreamMessage();
2028}
2029
2030void AudioProcessingImpl::RecordProcessedCaptureStream(
2031 const AudioFrame& processed_capture_frame) {
2032 RTC_DCHECK(aec_dump_);
2033
2034 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2035 aec_dump_->WriteCaptureStreamMessage();
2036}
2037
2038void AudioProcessingImpl::RecordAudioProcessingState() {
2039 RTC_DCHECK(aec_dump_);
2040 AecDump::AudioProcessingState audio_proc_state;
2041 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2042 audio_proc_state.drift =
2043 public_submodules_->echo_cancellation->stream_drift_samples();
2044 audio_proc_state.level = gain_control()->stream_analog_level();
2045 audio_proc_state.keypress = capture_.key_pressed;
2046 aec_dump_->AddAudioProcessingState(audio_proc_state);
2047}
2048
kwiberg83ffe452016-08-29 14:46:07 -07002049AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2050 bool transient_suppressor_enabled,
2051 const std::vector<Point>& array_geometry,
2052 SphericalPointf target_direction)
2053 : aec_system_delay_jumps(-1),
2054 delay_offset_ms(0),
2055 was_stream_delay_set(false),
2056 last_stream_delay_ms(0),
2057 last_aec_system_delay_ms(0),
2058 stream_delay_jumps(-1),
2059 output_will_be_muted(false),
2060 key_pressed(false),
2061 transient_suppressor_enabled(transient_suppressor_enabled),
2062 array_geometry(array_geometry),
2063 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002064 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002065 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002066 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002067
2068AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2069
2070AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2071
2072AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2073
niklase@google.com470e71d2011-07-07 08:21:25 +00002074} // namespace webrtc