blob: 3711375cab63dc5947dc93801585a251af0a0305 [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"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#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"
Niels Möllera12c42a2018-07-25 16:05:48 +020036#include "rtc_base/system/arch.h"
Minyue Li656d6092018-08-10 15:38:52 +020037#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070039#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070041#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "modules/audio_processing/level_estimator_impl.h"
43#include "modules/audio_processing/low_cut_filter.h"
44#include "modules/audio_processing/noise_suppression_impl.h"
45#include "modules/audio_processing/residual_echo_detector.h"
46#include "modules/audio_processing/transient/transient_suppressor.h"
47#include "modules/audio_processing/voice_detection_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010048#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000050
peah1bcfce52016-08-26 07:16:04 -070051// Check to verify that the define for the intelligibility enhancer is properly
52// set.
53#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
54 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
55 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
56#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
57#endif
58
Michael Graczyk86c6d332015-07-23 11:41:39 -070059#define RETURN_ON_ERR(expr) \
60 do { \
61 int err = (expr); \
62 if (err != kNoError) { \
63 return err; \
64 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000065 } while (0)
66
niklase@google.com470e71d2011-07-07 08:21:25 +000067namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070068
kwibergd59d3bb2016-09-13 07:49:33 -070069constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020070constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070071
Michael Graczyk86c6d332015-07-23 11:41:39 -070072namespace {
73
74static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
75 switch (layout) {
76 case AudioProcessing::kMono:
77 case AudioProcessing::kStereo:
78 return false;
79 case AudioProcessing::kMonoAndKeyboard:
80 case AudioProcessing::kStereoAndKeyboard:
81 return true;
82 }
83
kwiberg9e2be5f2016-09-14 05:23:22 -070084 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070085 return false;
86}
aluebsdf6416a2016-03-16 18:26:35 -070087
peah2ace3f92016-09-10 04:42:27 -070088bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070089 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
90 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
91}
92
peah2ace3f92016-09-10 04:42:27 -070093int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
94#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070095 constexpr int kMaxSplittingNativeProcessRate =
96 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070097#else
kwibergd59d3bb2016-09-13 07:49:33 -070098 constexpr int kMaxSplittingNativeProcessRate =
99 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700100#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700101 static_assert(
102 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
103 "");
peah2ace3f92016-09-10 04:42:27 -0700104 const int uppermost_native_rate = band_splitting_required
105 ? kMaxSplittingNativeProcessRate
106 : AudioProcessing::kSampleRate48kHz;
107
108 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
109 if (rate >= uppermost_native_rate) {
110 return uppermost_native_rate;
111 }
112 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700113 return rate;
114 }
115 }
peah2ace3f92016-09-10 04:42:27 -0700116 RTC_NOTREACHED();
117 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700118}
119
peah9e6a2902017-05-15 07:19:21 -0700120// Maximum lengths that frame of samples being passed from the render side to
121// the capture side can have (does not apply to AEC3).
122static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
123static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
124
peah764e3642016-10-22 05:04:30 -0700125// Maximum number of frames to buffer in the render queue.
126// TODO(peah): Decrease this once we properly handle hugely unbalanced
127// reverse and forward call numbers.
128static const size_t kMaxNumFramesToBuffer = 100;
129
peah8271d042016-11-22 07:24:52 -0800130class HighPassFilterImpl : public HighPassFilter {
131 public:
132 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
133 ~HighPassFilterImpl() override = default;
134
135 // HighPassFilter implementation.
136 int Enable(bool enable) override {
137 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
138 config->high_pass_filter.enabled = enable;
139 });
140
141 return AudioProcessing::kNoError;
142 }
143
144 bool is_enabled() const override {
145 return apm_->GetConfig().high_pass_filter.enabled;
146 }
147
148 private:
149 AudioProcessingImpl* apm_;
150 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
151};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700152} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000153
154// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000155static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000156
Sam Zackrisson0beac582017-09-25 12:04:02 +0200157AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100158 bool capture_post_processor_enabled,
159 bool render_pre_processor_enabled)
160 : capture_post_processor_enabled_(capture_post_processor_enabled),
161 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700162
163bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800164 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700165 bool echo_canceller_enabled,
166 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700167 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700168 bool noise_suppressor_enabled,
169 bool intelligibility_enhancer_enabled,
peah2ace3f92016-09-10 04:42:27 -0700170 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700171 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200172 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200173 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700174 bool voice_activity_detector_enabled,
175 bool level_estimator_enabled,
176 bool transient_suppressor_enabled) {
177 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800178 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700179 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
180 changed |=
181 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700182 changed |=
183 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700184 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
185 changed |=
186 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700187 changed |=
188 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700189 changed |=
190 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200191 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200192 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700193 changed |= (level_estimator_enabled != level_estimator_enabled_);
194 changed |=
195 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
196 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
197 if (changed) {
peah8271d042016-11-22 07:24:52 -0800198 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700199 echo_canceller_enabled_ = echo_canceller_enabled;
200 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700201 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700202 noise_suppressor_enabled_ = noise_suppressor_enabled;
203 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
peah2ace3f92016-09-10 04:42:27 -0700204 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700205 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200206 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200207 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700208 level_estimator_enabled_ = level_estimator_enabled;
209 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
210 transient_suppressor_enabled_ = transient_suppressor_enabled;
211 }
212
213 changed |= first_update_;
214 first_update_ = false;
215 return changed;
216}
217
218bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
219 const {
220#if WEBRTC_INTELLIGIBILITY_ENHANCER
221 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700222 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700223#else
peah52775842017-05-16 06:14:09 -0700224 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700225#endif
226}
227
228bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
229 const {
peah8271d042016-11-22 07:24:52 -0800230 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700231 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200232 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700233}
234
peah23ac8b42017-05-23 05:33:56 -0700235bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
236 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200237 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
238 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700239}
240
peah2ace3f92016-09-10 04:42:27 -0700241bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
242 const {
243 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800244 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200245 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700246}
247
Alex Loiko5825aa62017-12-18 16:02:40 +0100248bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
249 const {
250 return render_pre_processor_enabled_;
251}
252
peah2ace3f92016-09-10 04:42:27 -0700253bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
254 const {
255#if WEBRTC_INTELLIGIBILITY_ENHANCER
256 return intelligibility_enhancer_enabled_;
257#else
258 return false;
259#endif
260}
261
solenberg5e465c32015-12-08 13:22:33 -0800262struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800263 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800264 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800265 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800266 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800267 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800268 std::unique_ptr<LevelEstimatorImpl> level_estimator;
269 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
270 std::unique_ptr<VoiceDetectionImpl> voice_detection;
271 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800272 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800273
274 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800275 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700276#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800277 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700278#endif
solenberg5e465c32015-12-08 13:22:33 -0800279};
280
281struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200282 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100283 std::unique_ptr<CustomProcessing> render_pre_processor,
Ivo Creusend1f970d2018-06-14 11:02:03 +0200284 rtc::scoped_refptr<EchoDetector> echo_detector)
Sam Zackrissondb389722018-06-21 10:12:24 +0200285 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100286 capture_post_processor(std::move(capture_post_processor)),
287 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800288 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800289 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700290 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800291 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200292 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200293 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100294 std::unique_ptr<CustomProcessing> capture_post_processor;
295 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200296 std::unique_ptr<GainApplier> pre_amplifier;
solenberg5e465c32015-12-08 13:22:33 -0800297};
298
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100299AudioProcessingBuilder::AudioProcessingBuilder() = default;
300AudioProcessingBuilder::~AudioProcessingBuilder() = default;
301
302AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
303 std::unique_ptr<CustomProcessing> capture_post_processing) {
304 capture_post_processing_ = std::move(capture_post_processing);
305 return *this;
306}
307
308AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
309 std::unique_ptr<CustomProcessing> render_pre_processing) {
310 render_pre_processing_ = std::move(render_pre_processing);
311 return *this;
312}
313
314AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
315 std::unique_ptr<EchoControlFactory> echo_control_factory) {
316 echo_control_factory_ = std::move(echo_control_factory);
317 return *this;
318}
319
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100320AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200321 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100322 echo_detector_ = std::move(echo_detector);
323 return *this;
324}
325
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100326AudioProcessing* AudioProcessingBuilder::Create() {
327 webrtc::Config config;
328 return Create(config);
329}
330
331AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100332 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
333 config, std::move(capture_post_processing_),
334 std::move(render_pre_processing_), std::move(echo_control_factory_),
Sam Zackrissondb389722018-06-21 10:12:24 +0200335 std::move(echo_detector_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100336 if (apm->Initialize() != AudioProcessing::kNoError) {
337 delete apm;
338 apm = nullptr;
339 }
340 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100341}
342
peah88ac8532016-09-12 16:47:25 -0700343AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissondb389722018-06-21 10:12:24 +0200344 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000345
Per Åhgren13735822018-02-12 21:42:56 +0100346int AudioProcessingImpl::instance_count_ = 0;
347
Sam Zackrisson0beac582017-09-25 12:04:02 +0200348AudioProcessingImpl::AudioProcessingImpl(
349 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100350 std::unique_ptr<CustomProcessing> capture_post_processor,
351 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200352 std::unique_ptr<EchoControlFactory> echo_control_factory,
Sam Zackrissondb389722018-06-21 10:12:24 +0200353 rtc::scoped_refptr<EchoDetector> echo_detector)
Per Åhgren13735822018-02-12 21:42:56 +0100354 : data_dumper_(
355 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200356 capture_runtime_settings_(kRuntimeSettingQueueSize),
357 render_runtime_settings_(kRuntimeSettingQueueSize),
358 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
359 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100360 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200361 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100362 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800363 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200364 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200365 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100366 std::move(render_pre_processor),
367 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800368 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800369 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000370#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loiko64cb83b2018-07-02 13:38:19 +0200371 false,
372 false,
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700373 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000374#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200375 config.Get<ExperimentalAgc>().enabled,
376 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loiko9489c3a2018-08-09 15:04:24 +0200377 config.Get<ExperimentalAgc>().digital_adaptive_disabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000378#endif
andrew1c7075f2015-06-24 18:14:14 -0700379#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200380 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700381#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200382 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700383#endif
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200384 capture_nonlocked_(config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800385 {
386 rtc::CritScope cs_render(&crit_render_);
387 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000388
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200389 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000390 capture_nonlocked_.echo_controller_enabled =
391 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200392
peahb624d8c2016-03-05 03:01:14 -0800393 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700394 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800395 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700396 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800397 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200398 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800399 public_submodules_->level_estimator.reset(
400 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800401 public_submodules_->noise_suppression.reset(
402 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800403 public_submodules_->voice_detection.reset(
404 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800405 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800406 new GainControlForExperimentalAgc(
407 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100408
409 // If no echo detector is injected, use the ResidualEchoDetector.
410 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200411 private_submodules_->echo_detector =
412 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100413 }
peahca4cac72016-06-29 15:26:12 -0700414
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200415 // TODO(alessiob): Move the injected gain controller once injection is
416 // implemented.
417 private_submodules_->gain_controller2.reset(new GainController2());
418
Mirko Bonadei675513b2017-11-09 11:09:25 +0100419 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100420 << !!private_submodules_->capture_post_processor
421 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100422 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800423 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000424
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000425 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000426}
427
428AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800429 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800430 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800431 private_submodules_->agc_manager.reset();
432 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800433 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000434}
435
niklase@google.com470e71d2011-07-07 08:21:25 +0000436int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800437 // Run in a single-threaded manner during initialization.
438 rtc::CritScope cs_render(&crit_render_);
439 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000440 return InitializeLocked();
441}
442
peahde65ddc2016-09-16 15:02:15 -0700443int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
444 int capture_output_sample_rate_hz,
445 int render_input_sample_rate_hz,
446 ChannelLayout capture_input_layout,
447 ChannelLayout capture_output_layout,
448 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700449 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700450 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
451 LayoutHasKeyboard(capture_input_layout)},
452 {capture_output_sample_rate_hz,
453 ChannelsFromLayout(capture_output_layout),
454 LayoutHasKeyboard(capture_output_layout)},
455 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
456 LayoutHasKeyboard(render_input_layout)},
457 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
458 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700459
460 return Initialize(processing_config);
461}
462
463int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800464 // Run in a single-threaded manner during initialization.
465 rtc::CritScope cs_render(&crit_render_);
466 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700467 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000468}
469
peahdf3efa82015-11-28 12:35:15 -0800470int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800471 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700472 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800473}
474
peahdf3efa82015-11-28 12:35:15 -0800475int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700476 const ProcessingConfig& processing_config,
477 bool force_initialization) {
478 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800479}
480
peah192164e2015-11-17 02:16:45 -0800481// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800482// their current values (needs to be called while holding the crit_render_lock).
483int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700484 const ProcessingConfig& processing_config,
485 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800486 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700487 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800488 return kNoError;
489 }
peahdf3efa82015-11-28 12:35:15 -0800490
491 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800492 return InitializeLocked(processing_config);
493}
494
niklase@google.com470e71d2011-07-07 08:21:25 +0000495int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200496 UpdateActiveSubmoduleStates();
497
peahde65ddc2016-09-16 15:02:15 -0700498 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800499 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700500 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800501 : formats_.api_format.reverse_output_stream().num_frames();
502 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
503 render_.render_audio.reset(new AudioBuffer(
504 formats_.api_format.reverse_input_stream().num_frames(),
505 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700506 formats_.render_processing_format.num_frames(),
507 formats_.render_processing_format.num_channels(),
508 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700509 if (formats_.api_format.reverse_input_stream() !=
510 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800511 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800512 formats_.api_format.reverse_input_stream().num_channels(),
513 formats_.api_format.reverse_input_stream().num_frames(),
514 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800515 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700516 } else {
peahdf3efa82015-11-28 12:35:15 -0800517 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700518 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700519 } else {
peahdf3efa82015-11-28 12:35:15 -0800520 render_.render_audio.reset(nullptr);
521 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700522 }
peahce4d9152017-05-19 01:28:05 -0700523
peahdf3efa82015-11-28 12:35:15 -0800524 capture_.capture_audio.reset(
525 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
526 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700527 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200528 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800529 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000530
peahde65ddc2016-09-16 15:02:15 -0700531 public_submodules_->echo_cancellation->Initialize(
532 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
533 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700534 AllocateRenderQueue();
535
ivoc3e9a5372016-10-28 07:55:33 -0700536 int success = public_submodules_->echo_cancellation->enable_metrics(true);
537 RTC_DCHECK_EQ(0, success);
538 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
539 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700540 public_submodules_->echo_control_mobile->Initialize(
541 proc_split_sample_rate_hz(), num_reverse_channels(),
542 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700543
544 public_submodules_->gain_control->Initialize(num_proc_channels(),
545 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700546 if (constants_.use_experimental_agc) {
547 if (!private_submodules_->agc_manager.get()) {
548 private_submodules_->agc_manager.reset(new AgcManagerDirect(
549 public_submodules_->gain_control.get(),
550 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200551 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
552 constants_.use_experimental_agc_agc2_level_estimation,
553 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700554 }
555 private_submodules_->agc_manager->Initialize();
556 private_submodules_->agc_manager->SetCaptureMuted(
557 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700558 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700559 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200560 InitializeTransient();
peah1bcfce52016-08-26 07:16:04 -0700561#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700562 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700563#endif
peah8271d042016-11-22 07:24:52 -0800564 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700565 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
566 proc_sample_rate_hz());
567 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
568 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700569 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200570 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700571 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200572 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100573 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800574
aleloi868f32f2017-05-23 07:20:05 -0700575 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200576 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700577 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000578 return kNoError;
579}
580
Michael Graczyk86c6d332015-07-23 11:41:39 -0700581int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200582 UpdateActiveSubmoduleStates();
583
Michael Graczyk86c6d332015-07-23 11:41:39 -0700584 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700585 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
586 return kBadSampleRateError;
587 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000588 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700589
Peter Kasting69558702016-01-12 16:26:35 -0800590 const size_t num_in_channels = config.input_stream().num_channels();
591 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700592
593 // Need at least one input channel.
594 // Need either one output channel or as many outputs as there are inputs.
595 if (num_in_channels == 0 ||
596 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700597 return kBadNumberChannelsError;
598 }
599
peahdf3efa82015-11-28 12:35:15 -0800600 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000601
peahde65ddc2016-09-16 15:02:15 -0700602 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700603 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700604 formats_.api_format.output_stream().sample_rate_hz()),
605 submodule_states_.CaptureMultiBandSubModulesActive() ||
606 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000607
peahde65ddc2016-09-16 15:02:15 -0700608 capture_nonlocked_.capture_processing_format =
609 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700610
peah2ce640f2017-04-07 03:57:48 -0700611 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200612 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700613 render_processing_rate = FindNativeProcessRateToUse(
614 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
615 formats_.api_format.reverse_output_stream().sample_rate_hz()),
616 submodule_states_.CaptureMultiBandSubModulesActive() ||
617 submodule_states_.RenderMultiBandSubModulesActive());
618 } else {
619 render_processing_rate = capture_processing_rate;
620 }
621
aluebseb3603b2016-04-20 15:27:58 -0700622 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
623 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700624 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200625 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700626 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
627 ? kSampleRate32kHz
628 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700629 }
peah2ce640f2017-04-07 03:57:48 -0700630
peahde65ddc2016-09-16 15:02:15 -0700631 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700632 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700633 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
634 kSampleRate8kHz) {
635 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000636 } else {
peahde65ddc2016-09-16 15:02:15 -0700637 render_processing_rate =
638 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000639 }
640
peahde65ddc2016-09-16 15:02:15 -0700641 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000642 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700643 if (submodule_states_.RenderMultiBandSubModulesActive()) {
644 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
645 } else {
646 formats_.render_processing_format = StreamConfig(
647 formats_.api_format.reverse_input_stream().sample_rate_hz(),
648 formats_.api_format.reverse_input_stream().num_channels());
649 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000650
peahde65ddc2016-09-16 15:02:15 -0700651 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
652 kSampleRate32kHz ||
653 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
654 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800655 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000656 } else {
peahdf3efa82015-11-28 12:35:15 -0800657 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700658 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000659 }
660
661 return InitializeLocked();
662}
663
peah88ac8532016-09-12 16:47:25 -0700664void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700665 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700666
peah88ac8532016-09-12 16:47:25 -0700667 // Run in a single-threaded manner when applying the settings.
668 rtc::CritScope cs_render(&crit_render_);
669 rtc::CritScope cs_capture(&crit_capture_);
670
peah8271d042016-11-22 07:24:52 -0800671 InitializeLowCutFilter();
672
Mirko Bonadei675513b2017-11-09 11:09:25 +0100673 RTC_LOG(LS_INFO) << "Highpass filter activated: "
674 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800675
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100676 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700677 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100678 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
679 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100680 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100681 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700682 config_.gain_controller2 = AudioProcessing::Config::GainController2();
683 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200684 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200685 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200686 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100687 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
688 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200689 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
690 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700691}
692
693void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800694 // Run in a single-threaded manner when setting the extra options.
695 rtc::CritScope cs_render(&crit_render_);
696 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000697
peahb624d8c2016-03-05 03:01:14 -0800698 public_submodules_->echo_cancellation->SetExtraOptions(config);
699
peahdf3efa82015-11-28 12:35:15 -0800700 if (capture_.transient_suppressor_enabled !=
701 config.Get<ExperimentalNs>().enabled) {
702 capture_.transient_suppressor_enabled =
703 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000704 InitializeTransient();
705 }
aluebs2a346882016-01-11 18:04:30 -0800706
peah1bcfce52016-08-26 07:16:04 -0700707#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700708 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700709 config.Get<Intelligibility>().enabled) {
710 capture_nonlocked_.intelligibility_enabled =
711 config.Get<Intelligibility>().enabled;
712 InitializeIntelligibility();
713 }
peah1bcfce52016-08-26 07:16:04 -0700714#endif
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000715}
716
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000717int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800718 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700719 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000720}
721
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000722int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800723 // Used as callback from submodules, hence locking is not allowed.
724 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
Peter Kasting69558702016-01-12 16:26:35 -0800727size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800728 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700729 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000730}
731
Peter Kasting69558702016-01-12 16:26:35 -0800732size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800733 // Used as callback from submodules, hence locking is not allowed.
734 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000735}
736
Peter Kasting69558702016-01-12 16:26:35 -0800737size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800738 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200739 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800740}
741
Peter Kasting69558702016-01-12 16:26:35 -0800742size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800743 // Used as callback from submodules, hence locking is not allowed.
744 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000745}
746
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000747void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800748 rtc::CritScope cs(&crit_capture_);
749 capture_.output_will_be_muted = muted;
750 if (private_submodules_->agc_manager.get()) {
751 private_submodules_->agc_manager->SetCaptureMuted(
752 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000753 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000754}
755
Alessio Bazzicac054e782018-04-16 12:10:09 +0200756void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200757 switch (setting.type()) {
758 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
759 render_runtime_settings_enqueuer_.Enqueue(setting);
760 return;
761 case RuntimeSetting::Type::kNotSpecified:
762 RTC_NOTREACHED();
763 return;
764 case RuntimeSetting::Type::kCapturePreGain:
765 capture_runtime_settings_enqueuer_.Enqueue(setting);
766 return;
767 }
768 // The language allows the enum to have a non-enumerator
769 // value. Check that this doesn't happen.
770 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200771}
772
773AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
774 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200775 : runtime_settings_(*runtime_settings) {
776 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200777}
778
779AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
780 default;
781
782void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
783 RuntimeSetting setting) {
784 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200785 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200786 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200787 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200788 RTC_LOG(LS_ERROR)
789 << "The runtime settings queue is full. Oldest setting discarded.";
790 }
791 if (remaining_attempts == 0)
792 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
793}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000794
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000795int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700796 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000797 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000798 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000799 int output_sample_rate_hz,
800 ChannelLayout output_layout,
801 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800802 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800803 StreamConfig input_stream;
804 StreamConfig output_stream;
805 {
806 // Access the formats_.api_format.input_stream beneath the capture lock.
807 // The lock must be released as it is later required in the call
808 // to ProcessStream(,,,);
809 rtc::CritScope cs(&crit_capture_);
810 input_stream = formats_.api_format.input_stream();
811 output_stream = formats_.api_format.output_stream();
812 }
813
Michael Graczyk86c6d332015-07-23 11:41:39 -0700814 input_stream.set_sample_rate_hz(input_sample_rate_hz);
815 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
816 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700817 output_stream.set_sample_rate_hz(output_sample_rate_hz);
818 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
819 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
820
821 if (samples_per_channel != input_stream.num_frames()) {
822 return kBadDataLengthError;
823 }
824 return ProcessStream(src, input_stream, output_stream, dest);
825}
826
827int AudioProcessingImpl::ProcessStream(const float* const* src,
828 const StreamConfig& input_config,
829 const StreamConfig& output_config,
830 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800831 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800832 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700833 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800834 {
835 // Acquire the capture lock in order to safely call the function
836 // that retrieves the render side data. This function accesses apm
837 // getters that need the capture lock held when being called.
838 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700839 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800840
841 if (!src || !dest) {
842 return kNullPointerError;
843 }
844
845 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700846 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000847 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000848
Michael Graczyk86c6d332015-07-23 11:41:39 -0700849 processing_config.input_stream() = input_config;
850 processing_config.output_stream() = output_config;
851
peahdf3efa82015-11-28 12:35:15 -0800852 {
853 // Do conditional reinitialization.
854 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700855 RETURN_ON_ERR(
856 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800857 }
858 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700859 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
860 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000861
aleloi868f32f2017-05-23 07:20:05 -0700862 if (aec_dump_) {
863 RecordUnprocessedCaptureStream(src);
864 }
865
peahdf3efa82015-11-28 12:35:15 -0800866 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700867 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800868 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000869
aleloi868f32f2017-05-23 07:20:05 -0700870 if (aec_dump_) {
871 RecordProcessedCaptureStream(dest);
872 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000873 return kNoError;
874}
875
Alex Loiko73ec0192018-05-15 10:52:28 +0200876void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200877 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200878 while (capture_runtime_settings_.Remove(&setting)) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200879 switch (setting.type()) {
880 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200881 if (config_.pre_amplifier.enabled) {
882 float value;
883 setting.GetFloat(&value);
884 private_submodules_->pre_amplifier->SetGainFactor(value);
885 }
886 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200887 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200888 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
889 RTC_NOTREACHED();
890 break;
891 case RuntimeSetting::Type::kNotSpecified:
892 RTC_NOTREACHED();
893 break;
894 }
895 }
896}
897
898void AudioProcessingImpl::HandleRenderRuntimeSettings() {
899 RuntimeSetting setting;
900 while (render_runtime_settings_.Remove(&setting)) {
901 switch (setting.type()) {
902 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
903 if (private_submodules_->render_pre_processor) {
904 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
905 }
906 break;
907 case RuntimeSetting::Type::kCapturePreGain:
908 RTC_NOTREACHED();
909 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200910 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200911 RTC_NOTREACHED();
912 break;
913 }
914 }
915}
916
peah9e6a2902017-05-15 07:19:21 -0700917void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700918 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
919 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700920 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700921
kwibergaf476c72016-11-28 15:21:39 -0800922 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700923
924 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700925 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700926 // The data queue is full and needs to be emptied.
927 EmptyQueuedRenderAudio();
928
929 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700930 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700931 RTC_DCHECK(result);
932 }
933
934 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
935 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700936 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700937
938 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700939 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700940 // The data queue is full and needs to be emptied.
941 EmptyQueuedRenderAudio();
942
943 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700944 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700945 RTC_DCHECK(result);
946 }
peah701d6282016-10-25 05:42:20 -0700947
948 if (!constants_.use_experimental_agc) {
949 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
950 // Insert the samples into the queue.
951 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
952 // The data queue is full and needs to be emptied.
953 EmptyQueuedRenderAudio();
954
955 // Retry the insert (should always work).
956 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
957 RTC_DCHECK(result);
958 }
959 }
peah9e6a2902017-05-15 07:19:21 -0700960}
ivoc9f4a4a02016-10-28 05:39:16 -0700961
peah9e6a2902017-05-15 07:19:21 -0700962void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700963 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
964
965 // Insert the samples into the queue.
966 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
967 // The data queue is full and needs to be emptied.
968 EmptyQueuedRenderAudio();
969
970 // Retry the insert (should always work).
971 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
972 RTC_DCHECK(result);
973 }
peah764e3642016-10-22 05:04:30 -0700974}
975
976void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700977 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700978 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700979 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700980 EchoCancellationImpl::NumCancellersRequired(
981 num_output_channels(), num_reverse_channels()));
982
peah701d6282016-10-25 05:42:20 -0700983 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700984 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700985 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700986 EchoControlMobileImpl::NumCancellersRequired(
987 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700988
peah701d6282016-10-25 05:42:20 -0700989 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700990 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700991
ivoc9f4a4a02016-10-28 05:39:16 -0700992 const size_t new_red_render_queue_element_max_size =
993 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
994
peaha0624602016-10-25 04:45:24 -0700995 // Reallocate the queues if the queue item sizes are too small to fit the
996 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700997 if (aec_render_queue_element_max_size_ <
998 new_aec_render_queue_element_max_size) {
999 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001000
peaha0624602016-10-25 04:45:24 -07001001 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001002 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001003
peah701d6282016-10-25 05:42:20 -07001004 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001005 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1006 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001007 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001008 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001009
peah701d6282016-10-25 05:42:20 -07001010 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1011 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001012 } else {
peah701d6282016-10-25 05:42:20 -07001013 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001014 }
1015
peah701d6282016-10-25 05:42:20 -07001016 if (aecm_render_queue_element_max_size_ <
1017 new_aecm_render_queue_element_max_size) {
1018 aecm_render_queue_element_max_size_ =
1019 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001020
1021 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001022 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001023
peah701d6282016-10-25 05:42:20 -07001024 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001025 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1026 kMaxNumFramesToBuffer, template_queue_element,
1027 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001028 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001029
peah701d6282016-10-25 05:42:20 -07001030 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1031 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001032 } else {
peah701d6282016-10-25 05:42:20 -07001033 aecm_render_signal_queue_->Clear();
1034 }
1035
1036 if (agc_render_queue_element_max_size_ <
1037 new_agc_render_queue_element_max_size) {
1038 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1039
1040 std::vector<int16_t> template_queue_element(
1041 agc_render_queue_element_max_size_);
1042
1043 agc_render_signal_queue_.reset(
1044 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1045 kMaxNumFramesToBuffer, template_queue_element,
1046 RenderQueueItemVerifier<int16_t>(
1047 agc_render_queue_element_max_size_)));
1048
1049 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1050 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1051 } else {
1052 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001053 }
ivoc9f4a4a02016-10-28 05:39:16 -07001054
1055 if (red_render_queue_element_max_size_ <
1056 new_red_render_queue_element_max_size) {
1057 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1058
1059 std::vector<float> template_queue_element(
1060 red_render_queue_element_max_size_);
1061
1062 red_render_signal_queue_.reset(
1063 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1064 kMaxNumFramesToBuffer, template_queue_element,
1065 RenderQueueItemVerifier<float>(
1066 red_render_queue_element_max_size_)));
1067
1068 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1069 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1070 } else {
1071 red_render_signal_queue_->Clear();
1072 }
peah764e3642016-10-22 05:04:30 -07001073}
1074
1075void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1076 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001077 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001078 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001079 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001080 }
1081
peah701d6282016-10-25 05:42:20 -07001082 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001083 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001084 aecm_capture_queue_buffer_);
1085 }
1086
1087 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1088 public_submodules_->gain_control->ProcessRenderAudio(
1089 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001090 }
ivoc9f4a4a02016-10-28 05:39:16 -07001091
1092 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001093 RTC_DCHECK(private_submodules_->echo_detector);
1094 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001095 red_capture_queue_buffer_);
1096 }
peah764e3642016-10-22 05:04:30 -07001097}
1098
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001099int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001100 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001101 {
1102 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001103 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001104 // getters that need the capture lock held when being called.
1105 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001106 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001107 // as well.
1108 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001109 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001110 }
peahfa6228e2015-11-16 16:27:42 -08001111
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001112 if (!frame) {
1113 return kNullPointerError;
1114 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001115 // Must be a native rate.
1116 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1117 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001118 frame->sample_rate_hz_ != kSampleRate32kHz &&
1119 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001120 return kBadSampleRateError;
1121 }
peah192164e2015-11-17 02:16:45 -08001122
peahdf3efa82015-11-28 12:35:15 -08001123 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001124 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001125 {
1126 // Aquire lock for the access of api_format.
1127 // The lock is released immediately due to the conditional
1128 // reinitialization.
1129 rtc::CritScope cs_capture(&crit_capture_);
1130 // TODO(ajm): The input and output rates and channels are currently
1131 // constrained to be identical in the int16 interface.
1132 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001133
1134 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001135 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001136 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1137 processing_config.input_stream().set_num_channels(frame->num_channels_);
1138 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1139 processing_config.output_stream().set_num_channels(frame->num_channels_);
1140
peahdf3efa82015-11-28 12:35:15 -08001141 {
1142 // Do conditional reinitialization.
1143 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001144 RETURN_ON_ERR(
1145 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001146 }
1147 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001148 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001149 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001150 return kBadDataLengthError;
1151 }
1152
aleloi868f32f2017-05-23 07:20:05 -07001153 if (aec_dump_) {
1154 RecordUnprocessedCaptureStream(*frame);
1155 }
1156
peahdf3efa82015-11-28 12:35:15 -08001157 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001158 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001159 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001160 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1161 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001162
aleloi868f32f2017-05-23 07:20:05 -07001163 if (aec_dump_) {
1164 RecordProcessedCaptureStream(*frame);
1165 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001166
1167 return kNoError;
1168}
1169
peahde65ddc2016-09-16 15:02:15 -07001170int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001171 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001172
peahb58a1582016-03-15 09:34:24 -07001173 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001174 // TODO(peah): Simplify once the public API Enable functions for these
1175 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001176 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1177 public_submodules_->echo_control_mobile->is_enabled()));
1178
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001179 MaybeUpdateHistograms();
1180
peahde65ddc2016-09-16 15:02:15 -07001181 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001182
Alex Loikob5c9a792018-04-16 16:31:22 +02001183 if (private_submodules_->pre_amplifier) {
1184 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1185 capture_buffer->channels_f(), capture_buffer->num_channels(),
1186 capture_buffer->num_frames()));
1187 }
1188
peah1b08dc32016-12-20 13:45:58 -08001189 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001190 capture_buffer->channels_const()[0],
1191 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001192 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1193 if (log_rms) {
1194 capture_rms_interval_counter_ = 0;
1195 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001196 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1197 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1198 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1199 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001200 }
1201
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001202 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001203 // Detect and flag any change in the analog gain.
1204 int analog_mic_level = gain_control()->stream_analog_level();
1205 capture_.echo_path_gain_change =
1206 capture_.prev_analog_mic_level != analog_mic_level &&
1207 capture_.prev_analog_mic_level != -1;
1208 capture_.prev_analog_mic_level = analog_mic_level;
1209
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001210 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001211 }
1212
peahbe615622016-02-13 16:40:47 -08001213 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001214 public_submodules_->gain_control->is_enabled()) {
1215 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001216 capture_buffer->channels()[0], capture_buffer->num_channels(),
1217 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001218 }
1219
peah2ace3f92016-09-10 04:42:27 -07001220 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1221 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001222 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1223 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001224 }
1225
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001226 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001227 // Force down-mixing of the number of channels after the detection of
1228 // capture signal saturation.
1229 // TODO(peah): Look into ensuring that this kind of tampering with the
1230 // AudioBuffer functionality should not be needed.
1231 capture_buffer->set_num_channels(1);
1232 }
1233
peahe0eae3c2016-12-14 01:16:23 -08001234 // TODO(peah): Move the AEC3 low-cut filter to this place.
1235 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001236 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001237 private_submodules_->low_cut_filter->Process(capture_buffer);
1238 }
peahde65ddc2016-09-16 15:02:15 -07001239 RETURN_ON_ERR(
1240 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1241 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001242
1243 // Ensure that the stream delay was set before the call to the
1244 // AEC ProcessCaptureAudio function.
1245 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001246 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001247 return AudioProcessing::kStreamParameterNotSetError;
1248 }
1249
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001250 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001251 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1252
Per Åhgrend0fa8202018-04-18 09:35:13 +02001253 if (was_stream_delay_set()) {
1254 private_submodules_->echo_controller->SetAudioBufferDelay(
1255 stream_delay_ms());
1256 }
1257
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001258 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001259 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001260 } else {
1261 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1262 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001263 }
1264
peahdf3efa82015-11-28 12:35:15 -08001265 if (public_submodules_->echo_control_mobile->is_enabled() &&
1266 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001267 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001268 }
peahde65ddc2016-09-16 15:02:15 -07001269 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001270#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001271 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001272 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001273 const int gain_db =
1274 public_submodules_->gain_control->is_enabled()
1275 ? public_submodules_->gain_control->compression_gain_db()
1276 : 0;
1277 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001278 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001279 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001280 }
peah1bcfce52016-08-26 07:16:04 -07001281#endif
peah253534d2016-03-15 04:32:28 -07001282
1283 // Ensure that the stream delay was set before the call to the
1284 // AECM ProcessCaptureAudio function.
1285 if (public_submodules_->echo_control_mobile->is_enabled() &&
1286 !was_stream_delay_set()) {
1287 return AudioProcessing::kStreamParameterNotSetError;
1288 }
1289
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001290 if (!(private_submodules_->echo_controller ||
1291 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001292 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1293 capture_buffer, stream_delay_ms()));
1294 }
ivoc9f4a4a02016-10-28 05:39:16 -07001295
peahde65ddc2016-09-16 15:02:15 -07001296 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001297
peahbe615622016-02-13 16:40:47 -08001298 if (constants_.use_experimental_agc &&
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001299 public_submodules_->gain_control->is_enabled()) {
peahdf3efa82015-11-28 12:35:15 -08001300 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001301 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1302 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001303 }
peahb8fbb542016-03-15 02:28:08 -07001304 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001305 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001306
peah2ace3f92016-09-10 04:42:27 -07001307 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1308 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001309 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1310 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001311 }
1312
peah9e6a2902017-05-15 07:19:21 -07001313 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001314 RTC_DCHECK(private_submodules_->echo_detector);
1315 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001316 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1317 capture_buffer->num_frames()));
1318 }
1319
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001320 // TODO(aluebs): Investigate if the transient suppression placement should be
1321 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001322 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001323 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001324 private_submodules_->agc_manager.get()
1325 ? private_submodules_->agc_manager->voice_probability()
1326 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001327
peahdf3efa82015-11-28 12:35:15 -08001328 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001329 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1330 capture_buffer->num_channels(),
1331 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1332 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1333 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001334 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001335 }
1336
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001337 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001338 private_submodules_->gain_controller2->NotifyAnalogLevel(
1339 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001340 private_submodules_->gain_controller2->Process(capture_buffer);
1341 }
1342
Sam Zackrisson0beac582017-09-25 12:04:02 +02001343 if (private_submodules_->capture_post_processor) {
1344 private_submodules_->capture_post_processor->Process(capture_buffer);
1345 }
1346
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001347 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001348 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001349
peah1b08dc32016-12-20 13:45:58 -08001350 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1351 capture_buffer->channels_const()[0],
1352 capture_nonlocked_.capture_processing_format.num_frames()));
1353 if (log_rms) {
1354 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1355 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1356 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1357 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1358 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1359 }
1360
peahdf3efa82015-11-28 12:35:15 -08001361 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001362 return kNoError;
1363}
1364
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001365int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001366 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001367 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001368 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001369 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001370 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001371 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001372 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001373 };
1374 if (samples_per_channel != reverse_config.num_frames()) {
1375 return kBadDataLengthError;
1376 }
peahdf3efa82015-11-28 12:35:15 -08001377 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001378}
1379
peahde65ddc2016-09-16 15:02:15 -07001380int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1381 const StreamConfig& input_config,
1382 const StreamConfig& output_config,
1383 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001384 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001385 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001386 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001387 if (submodule_states_.RenderMultiBandProcessingActive() ||
1388 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001389 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1390 dest);
peah2ace3f92016-09-10 04:42:27 -07001391 } else if (formats_.api_format.reverse_input_stream() !=
1392 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001393 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1394 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001395 } else {
peahde65ddc2016-09-16 15:02:15 -07001396 CopyAudioIfNeeded(src, input_config.num_frames(),
1397 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001398 }
1399
1400 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001401}
1402
peahdf3efa82015-11-28 12:35:15 -08001403int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001404 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001405 const StreamConfig& input_config,
1406 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001407 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001408 return kNullPointerError;
1409 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001410
peahde65ddc2016-09-16 15:02:15 -07001411 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001412 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001413 }
1414
peahdf3efa82015-11-28 12:35:15 -08001415 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001416 processing_config.reverse_input_stream() = input_config;
1417 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001418
peahdf3efa82015-11-28 12:35:15 -08001419 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001420 RTC_DCHECK_EQ(input_config.num_frames(),
1421 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001422
aleloi868f32f2017-05-23 07:20:05 -07001423 if (aec_dump_) {
1424 const size_t channel_size =
1425 formats_.api_format.reverse_input_stream().num_frames();
1426 const size_t num_channels =
1427 formats_.api_format.reverse_input_stream().num_channels();
1428 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001429 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001430 }
peahdf3efa82015-11-28 12:35:15 -08001431 render_.render_audio->CopyFrom(src,
1432 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001433 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001434}
1435
1436int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001437 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001438 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001439 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001440 return kNullPointerError;
1441 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001442 // Must be a native rate.
1443 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1444 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001445 frame->sample_rate_hz_ != kSampleRate32kHz &&
1446 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001447 return kBadSampleRateError;
1448 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001449
Michael Graczyk86c6d332015-07-23 11:41:39 -07001450 if (frame->num_channels_ <= 0) {
1451 return kBadNumberChannelsError;
1452 }
1453
peahdf3efa82015-11-28 12:35:15 -08001454 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001455 processing_config.reverse_input_stream().set_sample_rate_hz(
1456 frame->sample_rate_hz_);
1457 processing_config.reverse_input_stream().set_num_channels(
1458 frame->num_channels_);
1459 processing_config.reverse_output_stream().set_sample_rate_hz(
1460 frame->sample_rate_hz_);
1461 processing_config.reverse_output_stream().set_num_channels(
1462 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001463
peahdf3efa82015-11-28 12:35:15 -08001464 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001465 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001466 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001467 return kBadDataLengthError;
1468 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001469
aleloi868f32f2017-05-23 07:20:05 -07001470 if (aec_dump_) {
1471 aec_dump_->WriteRenderStreamMessage(*frame);
1472 }
1473
peahdf3efa82015-11-28 12:35:15 -08001474 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001475 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001476 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001477 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1478 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001479 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001480}
niklase@google.com470e71d2011-07-07 08:21:25 +00001481
peahde65ddc2016-09-16 15:02:15 -07001482int AudioProcessingImpl::ProcessRenderStreamLocked() {
1483 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001484
Alex Loiko73ec0192018-05-15 10:52:28 +02001485 HandleRenderRuntimeSettings();
1486
Alex Loiko5825aa62017-12-18 16:02:40 +01001487 if (private_submodules_->render_pre_processor) {
1488 private_submodules_->render_pre_processor->Process(render_buffer);
1489 }
1490
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001491 QueueNonbandedRenderAudio(render_buffer);
1492
peah2ace3f92016-09-10 04:42:27 -07001493 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001494 SampleRateSupportsMultiBand(
1495 formats_.render_processing_format.sample_rate_hz())) {
1496 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001497 }
1498
peah1bcfce52016-08-26 07:16:04 -07001499#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001500 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001501 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001502 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001503 }
peah1bcfce52016-08-26 07:16:04 -07001504#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001505
peahce4d9152017-05-19 01:28:05 -07001506 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1507 QueueBandedRenderAudio(render_buffer);
1508 }
1509
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001510 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001511 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001512 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001513 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001514
peah2ace3f92016-09-10 04:42:27 -07001515 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001516 SampleRateSupportsMultiBand(
1517 formats_.render_processing_format.sample_rate_hz())) {
1518 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001519 }
1520
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001521 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001522}
1523
1524int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001525 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001526 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001527 capture_.was_stream_delay_set = true;
1528 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001529
niklase@google.com470e71d2011-07-07 08:21:25 +00001530 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001531 delay = 0;
1532 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001533 }
1534
1535 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1536 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001537 delay = 500;
1538 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001539 }
1540
peahdf3efa82015-11-28 12:35:15 -08001541 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001542 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001543}
1544
1545int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001546 // Used as callback from submodules, hence locking is not allowed.
1547 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001548}
1549
1550bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001551 // Used as callback from submodules, hence locking is not allowed.
1552 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001553}
1554
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001555void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001556 rtc::CritScope cs(&crit_capture_);
1557 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001558}
1559
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001560void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001561 rtc::CritScope cs(&crit_capture_);
1562 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001563}
1564
1565int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001566 rtc::CritScope cs(&crit_capture_);
1567 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001568}
1569
aleloi868f32f2017-05-23 07:20:05 -07001570void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1571 RTC_DCHECK(aec_dump);
1572 rtc::CritScope cs_render(&crit_render_);
1573 rtc::CritScope cs_capture(&crit_capture_);
1574
1575 // The previously attached AecDump will be destroyed with the
1576 // 'aec_dump' parameter, which is after locks are released.
1577 aec_dump_.swap(aec_dump);
1578 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001579 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001580}
1581
1582void AudioProcessingImpl::DetachAecDump() {
1583 // The d-tor of a task-queue based AecDump blocks until all pending
1584 // tasks are done. This construction avoids blocking while holding
1585 // the render and capture locks.
1586 std::unique_ptr<AecDump> aec_dump = nullptr;
1587 {
1588 rtc::CritScope cs_render(&crit_render_);
1589 rtc::CritScope cs_capture(&crit_capture_);
1590 aec_dump = std::move(aec_dump_);
1591 }
1592}
1593
Sam Zackrisson4d364492018-03-02 16:03:21 +01001594void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1595 std::unique_ptr<AudioGenerator> audio_generator) {
1596 // TODO(bugs.webrtc.org/8882) Stub.
1597 // Reset internal audio generator with audio_generator.
1598}
1599
1600void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1601 // TODO(bugs.webrtc.org/8882) Stub.
1602 // Delete audio generator, if one is attached.
1603}
1604
ivoc4e477a12017-01-15 08:29:46 -08001605AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1606 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1607 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1608 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1609 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1610}
1611
1612AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1613 const AudioProcessingStatistics& other) = default;
1614
1615AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1616 default;
1617
ivoc3e9a5372016-10-28 07:55:33 -07001618// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1619AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1620 const {
1621 return AudioProcessingStatistics();
1622}
1623
Ivo Creusenae026092017-11-20 13:07:16 +01001624// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001625AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001626 bool has_remote_tracks) const {
1627 return AudioProcessingStats();
1628}
1629
ivoc3e9a5372016-10-28 07:55:33 -07001630AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1631 const {
1632 AudioProcessingStatistics stats;
1633 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001634 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001635 rtc::CritScope cs_capture(&crit_capture_);
1636 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1637 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1638 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1639 // Instant value will also be used for min, max and average.
1640 stats.echo_return_loss.Set(erl, erl, erl, erl);
1641 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1642 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1643 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001644 stats.a_nlp.Set(metrics.a_nlp);
1645 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1646 stats.echo_return_loss.Set(metrics.echo_return_loss);
1647 stats.echo_return_loss_enhancement.Set(
1648 metrics.echo_return_loss_enhancement);
1649 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1650 }
ivoc9c192b22017-03-16 04:22:14 -07001651 {
1652 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001653 RTC_DCHECK(private_submodules_->echo_detector);
1654 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1655 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001656 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001657 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001658 }
ivoc3e9a5372016-10-28 07:55:33 -07001659 public_submodules_->echo_cancellation->GetDelayMetrics(
1660 &stats.delay_median, &stats.delay_standard_deviation,
1661 &stats.fraction_poor_delays);
1662 return stats;
1663}
1664
Ivo Creusen56d46092017-11-24 17:29:59 +01001665AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001666 bool has_remote_tracks) const {
1667 AudioProcessingStats stats;
1668 if (has_remote_tracks) {
1669 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001670 if (private_submodules_->echo_controller) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001671 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001672 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1673 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001674 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001675 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001676 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001677 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1678 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001679 if (metrics.divergent_filter_fraction != -1.0f) {
1680 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001681 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001682 }
1683 if (metrics.echo_return_loss.instant != -100) {
1684 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001685 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001686 }
1687 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001688 stats.echo_return_loss_enhancement = absl::optional<double>(
1689 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001690 }
1691 }
1692 if (config_.residual_echo_detector.enabled) {
1693 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001694 RTC_DCHECK(private_submodules_->echo_detector);
1695 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1696 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001697 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001698 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001699 }
1700 int delay_median, delay_std;
1701 float fraction_poor_delays;
1702 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1703 &delay_median, &delay_std, &fraction_poor_delays) ==
1704 Error::kNoError) {
1705 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001706 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001707 }
1708 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001709 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001710 }
1711 }
1712 }
1713 return stats;
1714}
1715
niklase@google.com470e71d2011-07-07 08:21:25 +00001716EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001717 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001718}
1719
1720EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001721 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001722}
1723
1724GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001725 if (constants_.use_experimental_agc) {
1726 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001727 }
peahbfa97112016-03-10 21:09:04 -08001728 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001729}
1730
1731HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001732 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001733}
1734
1735LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001736 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001737}
1738
1739NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001740 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001741}
1742
1743VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001744 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001745}
1746
peah8271d042016-11-22 07:24:52 -08001747void AudioProcessingImpl::MutateConfig(
1748 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1749 rtc::CritScope cs_render(&crit_render_);
1750 rtc::CritScope cs_capture(&crit_capture_);
1751 mutator(&config_);
1752 ApplyConfig(config_);
1753}
1754
1755AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1756 rtc::CritScope cs_render(&crit_render_);
1757 rtc::CritScope cs_capture(&crit_capture_);
1758 return config_;
1759}
1760
peah2ace3f92016-09-10 04:42:27 -07001761bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1762 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001763 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001764 public_submodules_->echo_cancellation->is_enabled(),
1765 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001766 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001767 public_submodules_->noise_suppression->is_enabled(),
1768 capture_nonlocked_.intelligibility_enabled,
peah2ace3f92016-09-10 04:42:27 -07001769 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001770 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001771 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001772 public_submodules_->voice_detection->is_enabled(),
1773 public_submodules_->level_estimator->is_enabled(),
1774 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001775}
1776
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001777
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001778void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001779 if (capture_.transient_suppressor_enabled) {
1780 if (!public_submodules_->transient_suppressor.get()) {
1781 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001782 }
peahdf3efa82015-11-28 12:35:15 -08001783 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001784 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1785 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001786 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001787}
1788
ekmeyerson60d9b332015-08-14 10:35:55 -07001789void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001790#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001791 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001792 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001793 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001794 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001795 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001796 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001797 }
peah1bcfce52016-08-26 07:16:04 -07001798#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001799}
1800
peah8271d042016-11-22 07:24:52 -08001801void AudioProcessingImpl::InitializeLowCutFilter() {
1802 if (config_.high_pass_filter.enabled) {
1803 private_submodules_->low_cut_filter.reset(
1804 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1805 } else {
1806 private_submodules_->low_cut_filter.reset();
1807 }
1808}
alessiob3ec96df2017-05-22 06:57:06 -07001809
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001810void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001811 if (echo_control_factory_) {
1812 private_submodules_->echo_controller =
1813 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001814 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001815 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001816 }
1817}
peah8271d042016-11-22 07:24:52 -08001818
alessiob3ec96df2017-05-22 06:57:06 -07001819void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001820 if (config_.gain_controller2.enabled) {
1821 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001822 }
1823}
1824
Alex Loikob5c9a792018-04-16 16:31:22 +02001825void AudioProcessingImpl::InitializePreAmplifier() {
1826 if (config_.pre_amplifier.enabled) {
1827 private_submodules_->pre_amplifier.reset(
1828 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1829 } else {
1830 private_submodules_->pre_amplifier.reset();
1831 }
1832}
1833
ivoc9f4a4a02016-10-28 05:39:16 -07001834void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001835 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001836 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001837 proc_sample_rate_hz(), 1,
1838 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001839}
1840
Sam Zackrisson0beac582017-09-25 12:04:02 +02001841void AudioProcessingImpl::InitializePostProcessor() {
1842 if (private_submodules_->capture_post_processor) {
1843 private_submodules_->capture_post_processor->Initialize(
1844 proc_sample_rate_hz(), num_proc_channels());
1845 }
1846}
1847
Alex Loiko5825aa62017-12-18 16:02:40 +01001848void AudioProcessingImpl::InitializePreProcessor() {
1849 if (private_submodules_->render_pre_processor) {
1850 private_submodules_->render_pre_processor->Initialize(
1851 formats_.render_processing_format.sample_rate_hz(),
1852 formats_.render_processing_format.num_channels());
1853 }
1854}
1855
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001856void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001857 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001858
1859 if (echo_cancellation()->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001860 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1861 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001862 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001863 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001864 capture_.stream_delay_jumps = 0;
1865 }
1866 if (capture_.aec_system_delay_jumps == -1 &&
1867 echo_cancellation()->stream_has_echo()) {
1868 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001869 }
1870
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001871 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001872 const int diff_stream_delay_ms =
1873 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1874 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1875 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001876 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1877 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001878 if (capture_.stream_delay_jumps == -1) {
1879 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001880 }
peahdf3efa82015-11-28 12:35:15 -08001881 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001882 }
peahdf3efa82015-11-28 12:35:15 -08001883 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001884
1885 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001886 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001887 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001888 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001889 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001890 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1891 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001892 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001893 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001894 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001895 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001896 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1897 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1898 100);
peahdf3efa82015-11-28 12:35:15 -08001899 if (capture_.aec_system_delay_jumps == -1) {
1900 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001901 }
peahdf3efa82015-11-28 12:35:15 -08001902 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001903 }
peahdf3efa82015-11-28 12:35:15 -08001904 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001905 }
1906}
1907
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001908void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001909 // Run in a single-threaded manner.
1910 rtc::CritScope cs_render(&crit_render_);
1911 rtc::CritScope cs_capture(&crit_capture_);
1912
1913 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001914 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001915 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001916 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001917 }
peahdf3efa82015-11-28 12:35:15 -08001918 capture_.stream_delay_jumps = -1;
1919 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001920
peahdf3efa82015-11-28 12:35:15 -08001921 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001922 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1923 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001924 }
peahdf3efa82015-11-28 12:35:15 -08001925 capture_.aec_system_delay_jumps = -1;
1926 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001927}
1928
aleloi868f32f2017-05-23 07:20:05 -07001929void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1930 if (!aec_dump_) {
1931 return;
1932 }
1933 std::string experiments_description =
1934 public_submodules_->echo_cancellation->GetExperimentsDescription();
1935 // TODO(peah): Add semicolon-separated concatenations of experiment
1936 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001937 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1938 experiments_description += "AgcClippingLevelExperiment;";
1939 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001940 if (capture_nonlocked_.echo_controller_enabled) {
1941 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001942 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001943 if (config_.gain_controller2.enabled) {
1944 experiments_description += "GainController2;";
1945 }
aleloi868f32f2017-05-23 07:20:05 -07001946
1947 InternalAPMConfig apm_config;
1948
1949 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1950 apm_config.aec_delay_agnostic_enabled =
1951 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1952 apm_config.aec_drift_compensation_enabled =
1953 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1954 apm_config.aec_extended_filter_enabled =
1955 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1956 apm_config.aec_suppression_level = static_cast<int>(
1957 public_submodules_->echo_cancellation->suppression_level());
1958
1959 apm_config.aecm_enabled =
1960 public_submodules_->echo_control_mobile->is_enabled();
1961 apm_config.aecm_comfort_noise_enabled =
1962 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1963 apm_config.aecm_routing_mode =
1964 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1965
1966 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1967 apm_config.agc_mode =
1968 static_cast<int>(public_submodules_->gain_control->mode());
1969 apm_config.agc_limiter_enabled =
1970 public_submodules_->gain_control->is_limiter_enabled();
1971 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1972
1973 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1974
1975 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1976 apm_config.ns_level =
1977 static_cast<int>(public_submodules_->noise_suppression->level());
1978
1979 apm_config.transient_suppression_enabled =
1980 capture_.transient_suppressor_enabled;
1981 apm_config.intelligibility_enhancer_enabled =
1982 capture_nonlocked_.intelligibility_enabled;
1983 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001984 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1985 apm_config.pre_amplifier_fixed_gain_factor =
1986 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001987
1988 if (!forced && apm_config == apm_config_for_aec_dump_) {
1989 return;
1990 }
1991 aec_dump_->WriteConfig(apm_config);
1992 apm_config_for_aec_dump_ = apm_config;
1993}
1994
1995void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1996 const float* const* src) {
1997 RTC_DCHECK(aec_dump_);
1998 WriteAecDumpConfigMessage(false);
1999
2000 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2001 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2002 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002003 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002004 RecordAudioProcessingState();
2005}
2006
2007void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2008 const AudioFrame& capture_frame) {
2009 RTC_DCHECK(aec_dump_);
2010 WriteAecDumpConfigMessage(false);
2011
2012 aec_dump_->AddCaptureStreamInput(capture_frame);
2013 RecordAudioProcessingState();
2014}
2015
2016void AudioProcessingImpl::RecordProcessedCaptureStream(
2017 const float* const* processed_capture_stream) {
2018 RTC_DCHECK(aec_dump_);
2019
2020 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2021 const size_t num_channels =
2022 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002023 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2024 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002025 aec_dump_->WriteCaptureStreamMessage();
2026}
2027
2028void AudioProcessingImpl::RecordProcessedCaptureStream(
2029 const AudioFrame& processed_capture_frame) {
2030 RTC_DCHECK(aec_dump_);
2031
2032 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2033 aec_dump_->WriteCaptureStreamMessage();
2034}
2035
2036void AudioProcessingImpl::RecordAudioProcessingState() {
2037 RTC_DCHECK(aec_dump_);
2038 AecDump::AudioProcessingState audio_proc_state;
2039 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2040 audio_proc_state.drift =
2041 public_submodules_->echo_cancellation->stream_drift_samples();
2042 audio_proc_state.level = gain_control()->stream_analog_level();
2043 audio_proc_state.keypress = capture_.key_pressed;
2044 aec_dump_->AddAudioProcessingState(audio_proc_state);
2045}
2046
kwiberg83ffe452016-08-29 14:46:07 -07002047AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002048 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002049 : aec_system_delay_jumps(-1),
2050 delay_offset_ms(0),
2051 was_stream_delay_set(false),
2052 last_stream_delay_ms(0),
2053 last_aec_system_delay_ms(0),
2054 stream_delay_jumps(-1),
2055 output_will_be_muted(false),
2056 key_pressed(false),
2057 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002058 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002059 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002060 echo_path_gain_change(false),
2061 prev_analog_mic_level(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002062
2063AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2064
2065AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2066
2067AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2068
niklase@google.com470e71d2011-07-07 08:21:25 +00002069} // namespace webrtc