blob: 52693859aeb345238ab7ffaaae1ba3f3fc3765e7 [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"
Sam Zackrisson74ed7342018-08-16 10:54:07 +020027#include "modules/audio_processing/echo_cancellation_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/echo_control_mobile_impl.h"
Sam Zackrisson74ed7342018-08-16 10:54:07 +020029#include "modules/audio_processing/echo_control_mobile_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "modules/audio_processing/gain_control_for_experimental_agc.h"
31#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010032#include "modules/audio_processing/gain_controller2.h"
Per Åhgren13735822018-02-12 21:42:56 +010033#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/checks.h"
35#include "rtc_base/logging.h"
36#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020037#include "rtc_base/refcountedobject.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020038#include "rtc_base/system/arch.h"
Minyue Li656d6092018-08-10 15:38:52 +020039#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070041#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070043#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "modules/audio_processing/level_estimator_impl.h"
45#include "modules/audio_processing/low_cut_filter.h"
46#include "modules/audio_processing/noise_suppression_impl.h"
47#include "modules/audio_processing/residual_echo_detector.h"
48#include "modules/audio_processing/transient/transient_suppressor.h"
49#include "modules/audio_processing/voice_detection_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010050#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000052
peah1bcfce52016-08-26 07:16:04 -070053// Check to verify that the define for the intelligibility enhancer is properly
54// set.
55#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
56 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
57 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
58#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
59#endif
60
Michael Graczyk86c6d332015-07-23 11:41:39 -070061#define RETURN_ON_ERR(expr) \
62 do { \
63 int err = (expr); \
64 if (err != kNoError) { \
65 return err; \
66 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000067 } while (0)
68
niklase@google.com470e71d2011-07-07 08:21:25 +000069namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070070
kwibergd59d3bb2016-09-13 07:49:33 -070071constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020072constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070073
Michael Graczyk86c6d332015-07-23 11:41:39 -070074namespace {
75
76static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
77 switch (layout) {
78 case AudioProcessing::kMono:
79 case AudioProcessing::kStereo:
80 return false;
81 case AudioProcessing::kMonoAndKeyboard:
82 case AudioProcessing::kStereoAndKeyboard:
83 return true;
84 }
85
kwiberg9e2be5f2016-09-14 05:23:22 -070086 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070087 return false;
88}
aluebsdf6416a2016-03-16 18:26:35 -070089
peah2ace3f92016-09-10 04:42:27 -070090bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070091 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
92 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
93}
94
peah2ace3f92016-09-10 04:42:27 -070095int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
96#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070097 constexpr int kMaxSplittingNativeProcessRate =
98 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070099#else
kwibergd59d3bb2016-09-13 07:49:33 -0700100 constexpr int kMaxSplittingNativeProcessRate =
101 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700102#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700103 static_assert(
104 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
105 "");
peah2ace3f92016-09-10 04:42:27 -0700106 const int uppermost_native_rate = band_splitting_required
107 ? kMaxSplittingNativeProcessRate
108 : AudioProcessing::kSampleRate48kHz;
109
110 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
111 if (rate >= uppermost_native_rate) {
112 return uppermost_native_rate;
113 }
114 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700115 return rate;
116 }
117 }
peah2ace3f92016-09-10 04:42:27 -0700118 RTC_NOTREACHED();
119 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700120}
121
peah9e6a2902017-05-15 07:19:21 -0700122// Maximum lengths that frame of samples being passed from the render side to
123// the capture side can have (does not apply to AEC3).
124static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
125static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
126
peah764e3642016-10-22 05:04:30 -0700127// Maximum number of frames to buffer in the render queue.
128// TODO(peah): Decrease this once we properly handle hugely unbalanced
129// reverse and forward call numbers.
130static const size_t kMaxNumFramesToBuffer = 100;
131
peah8271d042016-11-22 07:24:52 -0800132class HighPassFilterImpl : public HighPassFilter {
133 public:
134 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
135 ~HighPassFilterImpl() override = default;
136
137 // HighPassFilter implementation.
138 int Enable(bool enable) override {
139 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
140 config->high_pass_filter.enabled = enable;
141 });
142
143 return AudioProcessing::kNoError;
144 }
145
146 bool is_enabled() const override {
147 return apm_->GetConfig().high_pass_filter.enabled;
148 }
149
150 private:
151 AudioProcessingImpl* apm_;
152 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
153};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700154} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000155
156// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000157static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000158
Sam Zackrisson0beac582017-09-25 12:04:02 +0200159AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100160 bool capture_post_processor_enabled,
161 bool render_pre_processor_enabled)
162 : capture_post_processor_enabled_(capture_post_processor_enabled),
163 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700164
165bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800166 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700167 bool echo_canceller_enabled,
168 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700169 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700170 bool noise_suppressor_enabled,
171 bool intelligibility_enhancer_enabled,
peah2ace3f92016-09-10 04:42:27 -0700172 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700173 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200174 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200175 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700176 bool voice_activity_detector_enabled,
177 bool level_estimator_enabled,
178 bool transient_suppressor_enabled) {
179 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800180 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700181 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
182 changed |=
183 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700184 changed |=
185 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700186 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
187 changed |=
188 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700189 changed |=
190 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700191 changed |=
192 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200193 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200194 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700195 changed |= (level_estimator_enabled != level_estimator_enabled_);
196 changed |=
197 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
198 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
199 if (changed) {
peah8271d042016-11-22 07:24:52 -0800200 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700201 echo_canceller_enabled_ = echo_canceller_enabled;
202 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700203 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700204 noise_suppressor_enabled_ = noise_suppressor_enabled;
205 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
peah2ace3f92016-09-10 04:42:27 -0700206 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700207 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200208 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200209 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700210 level_estimator_enabled_ = level_estimator_enabled;
211 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
212 transient_suppressor_enabled_ = transient_suppressor_enabled;
213 }
214
215 changed |= first_update_;
216 first_update_ = false;
217 return changed;
218}
219
220bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
221 const {
222#if WEBRTC_INTELLIGIBILITY_ENHANCER
223 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700224 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700225#else
peah52775842017-05-16 06:14:09 -0700226 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700227#endif
228}
229
230bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
231 const {
peah8271d042016-11-22 07:24:52 -0800232 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700233 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200234 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700235}
236
peah23ac8b42017-05-23 05:33:56 -0700237bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
238 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200239 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
240 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700241}
242
peah2ace3f92016-09-10 04:42:27 -0700243bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
244 const {
245 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800246 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200247 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700248}
249
Alex Loiko5825aa62017-12-18 16:02:40 +0100250bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
251 const {
252 return render_pre_processor_enabled_;
253}
254
peah2ace3f92016-09-10 04:42:27 -0700255bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
256 const {
257#if WEBRTC_INTELLIGIBILITY_ENHANCER
258 return intelligibility_enhancer_enabled_;
259#else
260 return false;
261#endif
262}
263
solenberg5e465c32015-12-08 13:22:33 -0800264struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800265 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800266 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800267 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800268 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Sam Zackrisson74ed7342018-08-16 10:54:07 +0200269 std::unique_ptr<EchoCancellationProxy> echo_cancellation_proxy;
270 std::unique_ptr<EchoControlMobileProxy> echo_control_mobile_proxy;
peahbfa97112016-03-10 21:09:04 -0800271 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800272 std::unique_ptr<LevelEstimatorImpl> level_estimator;
273 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
274 std::unique_ptr<VoiceDetectionImpl> voice_detection;
275 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800276 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800277
278 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800279 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700280#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800281 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700282#endif
solenberg5e465c32015-12-08 13:22:33 -0800283};
284
285struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200286 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100287 std::unique_ptr<CustomProcessing> render_pre_processor,
Ivo Creusend1f970d2018-06-14 11:02:03 +0200288 rtc::scoped_refptr<EchoDetector> echo_detector)
Sam Zackrissondb389722018-06-21 10:12:24 +0200289 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100290 capture_post_processor(std::move(capture_post_processor)),
291 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800292 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800293 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700294 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800295 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200296 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200297 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100298 std::unique_ptr<CustomProcessing> capture_post_processor;
299 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200300 std::unique_ptr<GainApplier> pre_amplifier;
solenberg5e465c32015-12-08 13:22:33 -0800301};
302
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100303AudioProcessingBuilder::AudioProcessingBuilder() = default;
304AudioProcessingBuilder::~AudioProcessingBuilder() = default;
305
306AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
307 std::unique_ptr<CustomProcessing> capture_post_processing) {
308 capture_post_processing_ = std::move(capture_post_processing);
309 return *this;
310}
311
312AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
313 std::unique_ptr<CustomProcessing> render_pre_processing) {
314 render_pre_processing_ = std::move(render_pre_processing);
315 return *this;
316}
317
318AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
319 std::unique_ptr<EchoControlFactory> echo_control_factory) {
320 echo_control_factory_ = std::move(echo_control_factory);
321 return *this;
322}
323
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100324AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200325 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100326 echo_detector_ = std::move(echo_detector);
327 return *this;
328}
329
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100330AudioProcessing* AudioProcessingBuilder::Create() {
331 webrtc::Config config;
332 return Create(config);
333}
334
335AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100336 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
337 config, std::move(capture_post_processing_),
338 std::move(render_pre_processing_), std::move(echo_control_factory_),
Sam Zackrissondb389722018-06-21 10:12:24 +0200339 std::move(echo_detector_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100340 if (apm->Initialize() != AudioProcessing::kNoError) {
341 delete apm;
342 apm = nullptr;
343 }
344 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100345}
346
peah88ac8532016-09-12 16:47:25 -0700347AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissondb389722018-06-21 10:12:24 +0200348 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000349
Per Åhgren13735822018-02-12 21:42:56 +0100350int AudioProcessingImpl::instance_count_ = 0;
351
Sam Zackrisson0beac582017-09-25 12:04:02 +0200352AudioProcessingImpl::AudioProcessingImpl(
353 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100354 std::unique_ptr<CustomProcessing> capture_post_processor,
355 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200356 std::unique_ptr<EchoControlFactory> echo_control_factory,
Sam Zackrissondb389722018-06-21 10:12:24 +0200357 rtc::scoped_refptr<EchoDetector> echo_detector)
Per Åhgren13735822018-02-12 21:42:56 +0100358 : data_dumper_(
359 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200360 capture_runtime_settings_(kRuntimeSettingQueueSize),
361 render_runtime_settings_(kRuntimeSettingQueueSize),
362 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
363 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100364 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200365 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100366 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800367 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200368 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200369 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100370 std::move(render_pre_processor),
371 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800372 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800373 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000374#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loiko64cb83b2018-07-02 13:38:19 +0200375 false,
376 false,
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700377 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000378#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200379 config.Get<ExperimentalAgc>().enabled,
380 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loiko9489c3a2018-08-09 15:04:24 +0200381 config.Get<ExperimentalAgc>().digital_adaptive_disabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000382#endif
andrew1c7075f2015-06-24 18:14:14 -0700383#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200384 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700385#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200386 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700387#endif
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200388 capture_nonlocked_(config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800389 {
390 rtc::CritScope cs_render(&crit_render_);
391 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000392
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200393 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000394 capture_nonlocked_.echo_controller_enabled =
395 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200396
peahb624d8c2016-03-05 03:01:14 -0800397 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700398 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800399 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700400 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
Sam Zackrisson74ed7342018-08-16 10:54:07 +0200401 public_submodules_->echo_cancellation_proxy.reset(new EchoCancellationProxy(
402 this, public_submodules_->echo_cancellation.get()));
403 public_submodules_->echo_control_mobile_proxy.reset(
404 new EchoControlMobileProxy(
405 this, public_submodules_->echo_control_mobile.get()));
peahbfa97112016-03-10 21:09:04 -0800406 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200407 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800408 public_submodules_->level_estimator.reset(
409 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800410 public_submodules_->noise_suppression.reset(
411 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800412 public_submodules_->voice_detection.reset(
413 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800414 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800415 new GainControlForExperimentalAgc(
416 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100417
418 // If no echo detector is injected, use the ResidualEchoDetector.
419 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200420 private_submodules_->echo_detector =
421 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100422 }
peahca4cac72016-06-29 15:26:12 -0700423
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200424 // TODO(alessiob): Move the injected gain controller once injection is
425 // implemented.
426 private_submodules_->gain_controller2.reset(new GainController2());
427
Mirko Bonadei675513b2017-11-09 11:09:25 +0100428 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100429 << !!private_submodules_->capture_post_processor
430 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100431 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800432 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000433
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000434 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000435}
436
437AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800438 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800439 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800440 private_submodules_->agc_manager.reset();
441 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800442 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000443}
444
niklase@google.com470e71d2011-07-07 08:21:25 +0000445int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800446 // Run in a single-threaded manner during initialization.
447 rtc::CritScope cs_render(&crit_render_);
448 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000449 return InitializeLocked();
450}
451
peahde65ddc2016-09-16 15:02:15 -0700452int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
453 int capture_output_sample_rate_hz,
454 int render_input_sample_rate_hz,
455 ChannelLayout capture_input_layout,
456 ChannelLayout capture_output_layout,
457 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700458 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700459 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
460 LayoutHasKeyboard(capture_input_layout)},
461 {capture_output_sample_rate_hz,
462 ChannelsFromLayout(capture_output_layout),
463 LayoutHasKeyboard(capture_output_layout)},
464 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
465 LayoutHasKeyboard(render_input_layout)},
466 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
467 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700468
469 return Initialize(processing_config);
470}
471
472int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800473 // Run in a single-threaded manner during initialization.
474 rtc::CritScope cs_render(&crit_render_);
475 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700476 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000477}
478
peahdf3efa82015-11-28 12:35:15 -0800479int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800480 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700481 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800482}
483
peahdf3efa82015-11-28 12:35:15 -0800484int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700485 const ProcessingConfig& processing_config,
486 bool force_initialization) {
487 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800488}
489
peah192164e2015-11-17 02:16:45 -0800490// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800491// their current values (needs to be called while holding the crit_render_lock).
492int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700493 const ProcessingConfig& processing_config,
494 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800495 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700496 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800497 return kNoError;
498 }
peahdf3efa82015-11-28 12:35:15 -0800499
500 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800501 return InitializeLocked(processing_config);
502}
503
niklase@google.com470e71d2011-07-07 08:21:25 +0000504int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200505 UpdateActiveSubmoduleStates();
506
peahde65ddc2016-09-16 15:02:15 -0700507 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800508 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700509 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800510 : formats_.api_format.reverse_output_stream().num_frames();
511 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
512 render_.render_audio.reset(new AudioBuffer(
513 formats_.api_format.reverse_input_stream().num_frames(),
514 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700515 formats_.render_processing_format.num_frames(),
516 formats_.render_processing_format.num_channels(),
517 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700518 if (formats_.api_format.reverse_input_stream() !=
519 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800520 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800521 formats_.api_format.reverse_input_stream().num_channels(),
522 formats_.api_format.reverse_input_stream().num_frames(),
523 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800524 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700525 } else {
peahdf3efa82015-11-28 12:35:15 -0800526 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700527 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700528 } else {
peahdf3efa82015-11-28 12:35:15 -0800529 render_.render_audio.reset(nullptr);
530 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700531 }
peahce4d9152017-05-19 01:28:05 -0700532
peahdf3efa82015-11-28 12:35:15 -0800533 capture_.capture_audio.reset(
534 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
535 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700536 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200537 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800538 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000539
peahde65ddc2016-09-16 15:02:15 -0700540 public_submodules_->echo_cancellation->Initialize(
541 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
542 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700543 AllocateRenderQueue();
544
ivoc3e9a5372016-10-28 07:55:33 -0700545 int success = public_submodules_->echo_cancellation->enable_metrics(true);
546 RTC_DCHECK_EQ(0, success);
547 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
548 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700549 public_submodules_->echo_control_mobile->Initialize(
550 proc_split_sample_rate_hz(), num_reverse_channels(),
551 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700552
553 public_submodules_->gain_control->Initialize(num_proc_channels(),
554 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700555 if (constants_.use_experimental_agc) {
556 if (!private_submodules_->agc_manager.get()) {
557 private_submodules_->agc_manager.reset(new AgcManagerDirect(
558 public_submodules_->gain_control.get(),
559 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200560 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
561 constants_.use_experimental_agc_agc2_level_estimation,
562 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700563 }
564 private_submodules_->agc_manager->Initialize();
565 private_submodules_->agc_manager->SetCaptureMuted(
566 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700567 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700568 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200569 InitializeTransient();
peah1bcfce52016-08-26 07:16:04 -0700570#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700571 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700572#endif
peah8271d042016-11-22 07:24:52 -0800573 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700574 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
575 proc_sample_rate_hz());
576 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
577 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700578 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200579 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700580 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200581 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100582 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800583
aleloi868f32f2017-05-23 07:20:05 -0700584 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200585 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700586 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000587 return kNoError;
588}
589
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200591 UpdateActiveSubmoduleStates();
592
Michael Graczyk86c6d332015-07-23 11:41:39 -0700593 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700594 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
595 return kBadSampleRateError;
596 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000597 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700598
Peter Kasting69558702016-01-12 16:26:35 -0800599 const size_t num_in_channels = config.input_stream().num_channels();
600 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700601
602 // Need at least one input channel.
603 // Need either one output channel or as many outputs as there are inputs.
604 if (num_in_channels == 0 ||
605 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700606 return kBadNumberChannelsError;
607 }
608
peahdf3efa82015-11-28 12:35:15 -0800609 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000610
peahde65ddc2016-09-16 15:02:15 -0700611 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700612 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700613 formats_.api_format.output_stream().sample_rate_hz()),
614 submodule_states_.CaptureMultiBandSubModulesActive() ||
615 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000616
peahde65ddc2016-09-16 15:02:15 -0700617 capture_nonlocked_.capture_processing_format =
618 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700619
peah2ce640f2017-04-07 03:57:48 -0700620 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200621 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700622 render_processing_rate = FindNativeProcessRateToUse(
623 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
624 formats_.api_format.reverse_output_stream().sample_rate_hz()),
625 submodule_states_.CaptureMultiBandSubModulesActive() ||
626 submodule_states_.RenderMultiBandSubModulesActive());
627 } else {
628 render_processing_rate = capture_processing_rate;
629 }
630
aluebseb3603b2016-04-20 15:27:58 -0700631 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
632 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700633 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200634 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700635 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
636 ? kSampleRate32kHz
637 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700638 }
peah2ce640f2017-04-07 03:57:48 -0700639
peahde65ddc2016-09-16 15:02:15 -0700640 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700641 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700642 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
643 kSampleRate8kHz) {
644 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000645 } else {
peahde65ddc2016-09-16 15:02:15 -0700646 render_processing_rate =
647 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000648 }
649
peahde65ddc2016-09-16 15:02:15 -0700650 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000651 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700652 if (submodule_states_.RenderMultiBandSubModulesActive()) {
653 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
654 } else {
655 formats_.render_processing_format = StreamConfig(
656 formats_.api_format.reverse_input_stream().sample_rate_hz(),
657 formats_.api_format.reverse_input_stream().num_channels());
658 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000659
peahde65ddc2016-09-16 15:02:15 -0700660 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
661 kSampleRate32kHz ||
662 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
663 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800664 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000665 } else {
peahdf3efa82015-11-28 12:35:15 -0800666 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700667 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000668 }
669
670 return InitializeLocked();
671}
672
peah88ac8532016-09-12 16:47:25 -0700673void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700674 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700675
peah88ac8532016-09-12 16:47:25 -0700676 // Run in a single-threaded manner when applying the settings.
677 rtc::CritScope cs_render(&crit_render_);
678 rtc::CritScope cs_capture(&crit_capture_);
679
peah8271d042016-11-22 07:24:52 -0800680 InitializeLowCutFilter();
681
Mirko Bonadei675513b2017-11-09 11:09:25 +0100682 RTC_LOG(LS_INFO) << "Highpass filter activated: "
683 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800684
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100685 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700686 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100687 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
688 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100689 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100690 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700691 config_.gain_controller2 = AudioProcessing::Config::GainController2();
692 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200693 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200694 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200695 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100696 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
697 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200698 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
699 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700700}
701
702void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800703 // Run in a single-threaded manner when setting the extra options.
704 rtc::CritScope cs_render(&crit_render_);
705 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000706
peahb624d8c2016-03-05 03:01:14 -0800707 public_submodules_->echo_cancellation->SetExtraOptions(config);
708
peahdf3efa82015-11-28 12:35:15 -0800709 if (capture_.transient_suppressor_enabled !=
710 config.Get<ExperimentalNs>().enabled) {
711 capture_.transient_suppressor_enabled =
712 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000713 InitializeTransient();
714 }
aluebs2a346882016-01-11 18:04:30 -0800715
peah1bcfce52016-08-26 07:16:04 -0700716#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700717 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700718 config.Get<Intelligibility>().enabled) {
719 capture_nonlocked_.intelligibility_enabled =
720 config.Get<Intelligibility>().enabled;
721 InitializeIntelligibility();
722 }
peah1bcfce52016-08-26 07:16:04 -0700723#endif
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000724}
725
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000726int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800727 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700728 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000729}
730
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000731int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800732 // Used as callback from submodules, hence locking is not allowed.
733 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000734}
735
Peter Kasting69558702016-01-12 16:26:35 -0800736size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800737 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700738 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000739}
740
Peter Kasting69558702016-01-12 16:26:35 -0800741size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800742 // Used as callback from submodules, hence locking is not allowed.
743 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
Peter Kasting69558702016-01-12 16:26:35 -0800746size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800747 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200748 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800749}
750
Peter Kasting69558702016-01-12 16:26:35 -0800751size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800752 // Used as callback from submodules, hence locking is not allowed.
753 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000754}
755
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000756void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800757 rtc::CritScope cs(&crit_capture_);
758 capture_.output_will_be_muted = muted;
759 if (private_submodules_->agc_manager.get()) {
760 private_submodules_->agc_manager->SetCaptureMuted(
761 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000762 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000763}
764
Alessio Bazzicac054e782018-04-16 12:10:09 +0200765void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200766 switch (setting.type()) {
767 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
768 render_runtime_settings_enqueuer_.Enqueue(setting);
769 return;
770 case RuntimeSetting::Type::kNotSpecified:
771 RTC_NOTREACHED();
772 return;
773 case RuntimeSetting::Type::kCapturePreGain:
774 capture_runtime_settings_enqueuer_.Enqueue(setting);
775 return;
776 }
777 // The language allows the enum to have a non-enumerator
778 // value. Check that this doesn't happen.
779 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200780}
781
782AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
783 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200784 : runtime_settings_(*runtime_settings) {
785 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200786}
787
788AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
789 default;
790
791void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
792 RuntimeSetting setting) {
793 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200794 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200795 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200796 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200797 RTC_LOG(LS_ERROR)
798 << "The runtime settings queue is full. Oldest setting discarded.";
799 }
800 if (remaining_attempts == 0)
801 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
802}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000803
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000804int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700805 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000806 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000807 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000808 int output_sample_rate_hz,
809 ChannelLayout output_layout,
810 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800811 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800812 StreamConfig input_stream;
813 StreamConfig output_stream;
814 {
815 // Access the formats_.api_format.input_stream beneath the capture lock.
816 // The lock must be released as it is later required in the call
817 // to ProcessStream(,,,);
818 rtc::CritScope cs(&crit_capture_);
819 input_stream = formats_.api_format.input_stream();
820 output_stream = formats_.api_format.output_stream();
821 }
822
Michael Graczyk86c6d332015-07-23 11:41:39 -0700823 input_stream.set_sample_rate_hz(input_sample_rate_hz);
824 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
825 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700826 output_stream.set_sample_rate_hz(output_sample_rate_hz);
827 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
828 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
829
830 if (samples_per_channel != input_stream.num_frames()) {
831 return kBadDataLengthError;
832 }
833 return ProcessStream(src, input_stream, output_stream, dest);
834}
835
836int AudioProcessingImpl::ProcessStream(const float* const* src,
837 const StreamConfig& input_config,
838 const StreamConfig& output_config,
839 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800840 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800841 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700842 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800843 {
844 // Acquire the capture lock in order to safely call the function
845 // that retrieves the render side data. This function accesses apm
846 // getters that need the capture lock held when being called.
847 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700848 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800849
850 if (!src || !dest) {
851 return kNullPointerError;
852 }
853
854 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700855 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000856 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000857
Michael Graczyk86c6d332015-07-23 11:41:39 -0700858 processing_config.input_stream() = input_config;
859 processing_config.output_stream() = output_config;
860
peahdf3efa82015-11-28 12:35:15 -0800861 {
862 // Do conditional reinitialization.
863 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700864 RETURN_ON_ERR(
865 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800866 }
867 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700868 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
869 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000870
aleloi868f32f2017-05-23 07:20:05 -0700871 if (aec_dump_) {
872 RecordUnprocessedCaptureStream(src);
873 }
874
peahdf3efa82015-11-28 12:35:15 -0800875 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700876 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800877 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000878
aleloi868f32f2017-05-23 07:20:05 -0700879 if (aec_dump_) {
880 RecordProcessedCaptureStream(dest);
881 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000882 return kNoError;
883}
884
Alex Loiko73ec0192018-05-15 10:52:28 +0200885void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200886 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200887 while (capture_runtime_settings_.Remove(&setting)) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200888 switch (setting.type()) {
889 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200890 if (config_.pre_amplifier.enabled) {
891 float value;
892 setting.GetFloat(&value);
893 private_submodules_->pre_amplifier->SetGainFactor(value);
894 }
895 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200896 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200897 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
898 RTC_NOTREACHED();
899 break;
900 case RuntimeSetting::Type::kNotSpecified:
901 RTC_NOTREACHED();
902 break;
903 }
904 }
905}
906
907void AudioProcessingImpl::HandleRenderRuntimeSettings() {
908 RuntimeSetting setting;
909 while (render_runtime_settings_.Remove(&setting)) {
910 switch (setting.type()) {
911 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
912 if (private_submodules_->render_pre_processor) {
913 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
914 }
915 break;
916 case RuntimeSetting::Type::kCapturePreGain:
917 RTC_NOTREACHED();
918 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200919 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200920 RTC_NOTREACHED();
921 break;
922 }
923 }
924}
925
peah9e6a2902017-05-15 07:19:21 -0700926void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700927 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
928 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700929 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700930
kwibergaf476c72016-11-28 15:21:39 -0800931 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700932
933 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700934 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700935 // The data queue is full and needs to be emptied.
936 EmptyQueuedRenderAudio();
937
938 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700939 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700940 RTC_DCHECK(result);
941 }
942
943 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
944 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700945 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700946
947 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700948 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700949 // The data queue is full and needs to be emptied.
950 EmptyQueuedRenderAudio();
951
952 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700953 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700954 RTC_DCHECK(result);
955 }
peah701d6282016-10-25 05:42:20 -0700956
957 if (!constants_.use_experimental_agc) {
958 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
959 // Insert the samples into the queue.
960 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
961 // The data queue is full and needs to be emptied.
962 EmptyQueuedRenderAudio();
963
964 // Retry the insert (should always work).
965 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
966 RTC_DCHECK(result);
967 }
968 }
peah9e6a2902017-05-15 07:19:21 -0700969}
ivoc9f4a4a02016-10-28 05:39:16 -0700970
peah9e6a2902017-05-15 07:19:21 -0700971void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700972 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
973
974 // Insert the samples into the queue.
975 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
976 // The data queue is full and needs to be emptied.
977 EmptyQueuedRenderAudio();
978
979 // Retry the insert (should always work).
980 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
981 RTC_DCHECK(result);
982 }
peah764e3642016-10-22 05:04:30 -0700983}
984
985void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700986 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700987 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700988 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700989 EchoCancellationImpl::NumCancellersRequired(
990 num_output_channels(), num_reverse_channels()));
991
peah701d6282016-10-25 05:42:20 -0700992 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700993 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700994 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700995 EchoControlMobileImpl::NumCancellersRequired(
996 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700997
peah701d6282016-10-25 05:42:20 -0700998 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700999 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001000
ivoc9f4a4a02016-10-28 05:39:16 -07001001 const size_t new_red_render_queue_element_max_size =
1002 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1003
peaha0624602016-10-25 04:45:24 -07001004 // Reallocate the queues if the queue item sizes are too small to fit the
1005 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001006 if (aec_render_queue_element_max_size_ <
1007 new_aec_render_queue_element_max_size) {
1008 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001009
peaha0624602016-10-25 04:45:24 -07001010 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001011 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001012
peah701d6282016-10-25 05:42:20 -07001013 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001014 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1015 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001016 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001017 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001018
peah701d6282016-10-25 05:42:20 -07001019 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1020 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001021 } else {
peah701d6282016-10-25 05:42:20 -07001022 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001023 }
1024
peah701d6282016-10-25 05:42:20 -07001025 if (aecm_render_queue_element_max_size_ <
1026 new_aecm_render_queue_element_max_size) {
1027 aecm_render_queue_element_max_size_ =
1028 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001029
1030 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001031 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001032
peah701d6282016-10-25 05:42:20 -07001033 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001034 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1035 kMaxNumFramesToBuffer, template_queue_element,
1036 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001037 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001038
peah701d6282016-10-25 05:42:20 -07001039 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1040 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001041 } else {
peah701d6282016-10-25 05:42:20 -07001042 aecm_render_signal_queue_->Clear();
1043 }
1044
1045 if (agc_render_queue_element_max_size_ <
1046 new_agc_render_queue_element_max_size) {
1047 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1048
1049 std::vector<int16_t> template_queue_element(
1050 agc_render_queue_element_max_size_);
1051
1052 agc_render_signal_queue_.reset(
1053 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1054 kMaxNumFramesToBuffer, template_queue_element,
1055 RenderQueueItemVerifier<int16_t>(
1056 agc_render_queue_element_max_size_)));
1057
1058 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1059 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1060 } else {
1061 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001062 }
ivoc9f4a4a02016-10-28 05:39:16 -07001063
1064 if (red_render_queue_element_max_size_ <
1065 new_red_render_queue_element_max_size) {
1066 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1067
1068 std::vector<float> template_queue_element(
1069 red_render_queue_element_max_size_);
1070
1071 red_render_signal_queue_.reset(
1072 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1073 kMaxNumFramesToBuffer, template_queue_element,
1074 RenderQueueItemVerifier<float>(
1075 red_render_queue_element_max_size_)));
1076
1077 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1078 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1079 } else {
1080 red_render_signal_queue_->Clear();
1081 }
peah764e3642016-10-22 05:04:30 -07001082}
1083
1084void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1085 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001086 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001087 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001088 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001089 }
1090
peah701d6282016-10-25 05:42:20 -07001091 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001092 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001093 aecm_capture_queue_buffer_);
1094 }
1095
1096 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1097 public_submodules_->gain_control->ProcessRenderAudio(
1098 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001099 }
ivoc9f4a4a02016-10-28 05:39:16 -07001100
1101 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001102 RTC_DCHECK(private_submodules_->echo_detector);
1103 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001104 red_capture_queue_buffer_);
1105 }
peah764e3642016-10-22 05:04:30 -07001106}
1107
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001108int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001109 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001110 {
1111 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001112 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001113 // getters that need the capture lock held when being called.
1114 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001115 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001116 // as well.
1117 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001118 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001119 }
peahfa6228e2015-11-16 16:27:42 -08001120
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001121 if (!frame) {
1122 return kNullPointerError;
1123 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001124 // Must be a native rate.
1125 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1126 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001127 frame->sample_rate_hz_ != kSampleRate32kHz &&
1128 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001129 return kBadSampleRateError;
1130 }
peah192164e2015-11-17 02:16:45 -08001131
peahdf3efa82015-11-28 12:35:15 -08001132 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001133 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001134 {
1135 // Aquire lock for the access of api_format.
1136 // The lock is released immediately due to the conditional
1137 // reinitialization.
1138 rtc::CritScope cs_capture(&crit_capture_);
1139 // TODO(ajm): The input and output rates and channels are currently
1140 // constrained to be identical in the int16 interface.
1141 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001142
1143 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001144 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001145 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1146 processing_config.input_stream().set_num_channels(frame->num_channels_);
1147 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1148 processing_config.output_stream().set_num_channels(frame->num_channels_);
1149
peahdf3efa82015-11-28 12:35:15 -08001150 {
1151 // Do conditional reinitialization.
1152 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001153 RETURN_ON_ERR(
1154 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001155 }
1156 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001157 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001158 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001159 return kBadDataLengthError;
1160 }
1161
aleloi868f32f2017-05-23 07:20:05 -07001162 if (aec_dump_) {
1163 RecordUnprocessedCaptureStream(*frame);
1164 }
1165
peahdf3efa82015-11-28 12:35:15 -08001166 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001167 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001168 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001169 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1170 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001171
aleloi868f32f2017-05-23 07:20:05 -07001172 if (aec_dump_) {
1173 RecordProcessedCaptureStream(*frame);
1174 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001175
1176 return kNoError;
1177}
1178
peahde65ddc2016-09-16 15:02:15 -07001179int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001180 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001181
peahb58a1582016-03-15 09:34:24 -07001182 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001183 // TODO(peah): Simplify once the public API Enable functions for these
1184 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001185 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1186 public_submodules_->echo_control_mobile->is_enabled()));
1187
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001188 MaybeUpdateHistograms();
1189
peahde65ddc2016-09-16 15:02:15 -07001190 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001191
Alex Loikob5c9a792018-04-16 16:31:22 +02001192 if (private_submodules_->pre_amplifier) {
1193 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1194 capture_buffer->channels_f(), capture_buffer->num_channels(),
1195 capture_buffer->num_frames()));
1196 }
1197
peah1b08dc32016-12-20 13:45:58 -08001198 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001199 capture_buffer->channels_const()[0],
1200 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001201 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1202 if (log_rms) {
1203 capture_rms_interval_counter_ = 0;
1204 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001205 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1206 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1207 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1208 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001209 }
1210
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001211 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001212 // Detect and flag any change in the analog gain.
1213 int analog_mic_level = gain_control()->stream_analog_level();
1214 capture_.echo_path_gain_change =
1215 capture_.prev_analog_mic_level != analog_mic_level &&
1216 capture_.prev_analog_mic_level != -1;
1217 capture_.prev_analog_mic_level = analog_mic_level;
1218
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001219 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001220 }
1221
peahbe615622016-02-13 16:40:47 -08001222 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001223 public_submodules_->gain_control->is_enabled()) {
1224 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001225 capture_buffer->channels()[0], capture_buffer->num_channels(),
1226 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001227 }
1228
peah2ace3f92016-09-10 04:42:27 -07001229 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1230 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001231 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1232 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001233 }
1234
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001235 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001236 // Force down-mixing of the number of channels after the detection of
1237 // capture signal saturation.
1238 // TODO(peah): Look into ensuring that this kind of tampering with the
1239 // AudioBuffer functionality should not be needed.
1240 capture_buffer->set_num_channels(1);
1241 }
1242
peahe0eae3c2016-12-14 01:16:23 -08001243 // TODO(peah): Move the AEC3 low-cut filter to this place.
1244 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001245 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001246 private_submodules_->low_cut_filter->Process(capture_buffer);
1247 }
peahde65ddc2016-09-16 15:02:15 -07001248 RETURN_ON_ERR(
1249 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1250 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001251
1252 // Ensure that the stream delay was set before the call to the
1253 // AEC ProcessCaptureAudio function.
1254 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001255 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001256 return AudioProcessing::kStreamParameterNotSetError;
1257 }
1258
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001259 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001260 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1261
Per Åhgrend0fa8202018-04-18 09:35:13 +02001262 if (was_stream_delay_set()) {
1263 private_submodules_->echo_controller->SetAudioBufferDelay(
1264 stream_delay_ms());
1265 }
1266
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001267 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001268 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001269 } else {
1270 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1271 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001272 }
1273
peahdf3efa82015-11-28 12:35:15 -08001274 if (public_submodules_->echo_control_mobile->is_enabled() &&
1275 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001276 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001277 }
peahde65ddc2016-09-16 15:02:15 -07001278 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001279#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001280 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001281 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001282 const int gain_db =
1283 public_submodules_->gain_control->is_enabled()
1284 ? public_submodules_->gain_control->compression_gain_db()
1285 : 0;
1286 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001287 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001288 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001289 }
peah1bcfce52016-08-26 07:16:04 -07001290#endif
peah253534d2016-03-15 04:32:28 -07001291
1292 // Ensure that the stream delay was set before the call to the
1293 // AECM ProcessCaptureAudio function.
1294 if (public_submodules_->echo_control_mobile->is_enabled() &&
1295 !was_stream_delay_set()) {
1296 return AudioProcessing::kStreamParameterNotSetError;
1297 }
1298
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001299 if (!(private_submodules_->echo_controller ||
1300 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001301 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1302 capture_buffer, stream_delay_ms()));
1303 }
ivoc9f4a4a02016-10-28 05:39:16 -07001304
peahde65ddc2016-09-16 15:02:15 -07001305 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001306
peahbe615622016-02-13 16:40:47 -08001307 if (constants_.use_experimental_agc &&
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001308 public_submodules_->gain_control->is_enabled()) {
peahdf3efa82015-11-28 12:35:15 -08001309 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001310 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1311 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001312 }
peahb8fbb542016-03-15 02:28:08 -07001313 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001314 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001315
peah2ace3f92016-09-10 04:42:27 -07001316 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1317 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001318 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1319 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001320 }
1321
peah9e6a2902017-05-15 07:19:21 -07001322 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001323 RTC_DCHECK(private_submodules_->echo_detector);
1324 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001325 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1326 capture_buffer->num_frames()));
1327 }
1328
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001329 // TODO(aluebs): Investigate if the transient suppression placement should be
1330 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001331 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001332 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001333 private_submodules_->agc_manager.get()
1334 ? private_submodules_->agc_manager->voice_probability()
1335 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001336
peahdf3efa82015-11-28 12:35:15 -08001337 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001338 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1339 capture_buffer->num_channels(),
1340 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1341 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1342 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001343 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001344 }
1345
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001346 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001347 private_submodules_->gain_controller2->NotifyAnalogLevel(
1348 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001349 private_submodules_->gain_controller2->Process(capture_buffer);
1350 }
1351
Sam Zackrisson0beac582017-09-25 12:04:02 +02001352 if (private_submodules_->capture_post_processor) {
1353 private_submodules_->capture_post_processor->Process(capture_buffer);
1354 }
1355
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001356 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001357 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001358
peah1b08dc32016-12-20 13:45:58 -08001359 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1360 capture_buffer->channels_const()[0],
1361 capture_nonlocked_.capture_processing_format.num_frames()));
1362 if (log_rms) {
1363 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1364 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1365 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1366 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1367 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1368 }
1369
peahdf3efa82015-11-28 12:35:15 -08001370 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001371 return kNoError;
1372}
1373
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001374int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001375 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001376 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001377 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001378 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001379 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001380 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001381 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001382 };
1383 if (samples_per_channel != reverse_config.num_frames()) {
1384 return kBadDataLengthError;
1385 }
peahdf3efa82015-11-28 12:35:15 -08001386 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001387}
1388
peahde65ddc2016-09-16 15:02:15 -07001389int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1390 const StreamConfig& input_config,
1391 const StreamConfig& output_config,
1392 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001393 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001394 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001395 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001396 if (submodule_states_.RenderMultiBandProcessingActive() ||
1397 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001398 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1399 dest);
peah2ace3f92016-09-10 04:42:27 -07001400 } else if (formats_.api_format.reverse_input_stream() !=
1401 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001402 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1403 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001404 } else {
peahde65ddc2016-09-16 15:02:15 -07001405 CopyAudioIfNeeded(src, input_config.num_frames(),
1406 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001407 }
1408
1409 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001410}
1411
peahdf3efa82015-11-28 12:35:15 -08001412int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001413 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001414 const StreamConfig& input_config,
1415 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001416 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001417 return kNullPointerError;
1418 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001419
peahde65ddc2016-09-16 15:02:15 -07001420 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001421 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001422 }
1423
peahdf3efa82015-11-28 12:35:15 -08001424 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001425 processing_config.reverse_input_stream() = input_config;
1426 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001427
peahdf3efa82015-11-28 12:35:15 -08001428 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001429 RTC_DCHECK_EQ(input_config.num_frames(),
1430 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001431
aleloi868f32f2017-05-23 07:20:05 -07001432 if (aec_dump_) {
1433 const size_t channel_size =
1434 formats_.api_format.reverse_input_stream().num_frames();
1435 const size_t num_channels =
1436 formats_.api_format.reverse_input_stream().num_channels();
1437 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001438 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001439 }
peahdf3efa82015-11-28 12:35:15 -08001440 render_.render_audio->CopyFrom(src,
1441 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001442 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001443}
1444
1445int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001446 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001447 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001448 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001449 return kNullPointerError;
1450 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001451 // Must be a native rate.
1452 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1453 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001454 frame->sample_rate_hz_ != kSampleRate32kHz &&
1455 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001456 return kBadSampleRateError;
1457 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001458
Michael Graczyk86c6d332015-07-23 11:41:39 -07001459 if (frame->num_channels_ <= 0) {
1460 return kBadNumberChannelsError;
1461 }
1462
peahdf3efa82015-11-28 12:35:15 -08001463 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001464 processing_config.reverse_input_stream().set_sample_rate_hz(
1465 frame->sample_rate_hz_);
1466 processing_config.reverse_input_stream().set_num_channels(
1467 frame->num_channels_);
1468 processing_config.reverse_output_stream().set_sample_rate_hz(
1469 frame->sample_rate_hz_);
1470 processing_config.reverse_output_stream().set_num_channels(
1471 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001472
peahdf3efa82015-11-28 12:35:15 -08001473 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001474 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001475 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001476 return kBadDataLengthError;
1477 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001478
aleloi868f32f2017-05-23 07:20:05 -07001479 if (aec_dump_) {
1480 aec_dump_->WriteRenderStreamMessage(*frame);
1481 }
1482
peahdf3efa82015-11-28 12:35:15 -08001483 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001484 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001485 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001486 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1487 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001488 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001489}
niklase@google.com470e71d2011-07-07 08:21:25 +00001490
peahde65ddc2016-09-16 15:02:15 -07001491int AudioProcessingImpl::ProcessRenderStreamLocked() {
1492 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001493
Alex Loiko73ec0192018-05-15 10:52:28 +02001494 HandleRenderRuntimeSettings();
1495
Alex Loiko5825aa62017-12-18 16:02:40 +01001496 if (private_submodules_->render_pre_processor) {
1497 private_submodules_->render_pre_processor->Process(render_buffer);
1498 }
1499
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001500 QueueNonbandedRenderAudio(render_buffer);
1501
peah2ace3f92016-09-10 04:42:27 -07001502 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001503 SampleRateSupportsMultiBand(
1504 formats_.render_processing_format.sample_rate_hz())) {
1505 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001506 }
1507
peah1bcfce52016-08-26 07:16:04 -07001508#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001509 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001510 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001511 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001512 }
peah1bcfce52016-08-26 07:16:04 -07001513#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001514
peahce4d9152017-05-19 01:28:05 -07001515 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1516 QueueBandedRenderAudio(render_buffer);
1517 }
1518
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001519 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001520 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001521 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001522 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001523
peah2ace3f92016-09-10 04:42:27 -07001524 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001525 SampleRateSupportsMultiBand(
1526 formats_.render_processing_format.sample_rate_hz())) {
1527 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001528 }
1529
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001530 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001531}
1532
1533int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001534 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001535 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001536 capture_.was_stream_delay_set = true;
1537 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001538
niklase@google.com470e71d2011-07-07 08:21:25 +00001539 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001540 delay = 0;
1541 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001542 }
1543
1544 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1545 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001546 delay = 500;
1547 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001548 }
1549
peahdf3efa82015-11-28 12:35:15 -08001550 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001551 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001552}
1553
1554int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001555 // Used as callback from submodules, hence locking is not allowed.
1556 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001557}
1558
1559bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001560 // Used as callback from submodules, hence locking is not allowed.
1561 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001562}
1563
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001564void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001565 rtc::CritScope cs(&crit_capture_);
1566 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001567}
1568
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001569void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001570 rtc::CritScope cs(&crit_capture_);
1571 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001572}
1573
1574int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001575 rtc::CritScope cs(&crit_capture_);
1576 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001577}
1578
aleloi868f32f2017-05-23 07:20:05 -07001579void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1580 RTC_DCHECK(aec_dump);
1581 rtc::CritScope cs_render(&crit_render_);
1582 rtc::CritScope cs_capture(&crit_capture_);
1583
1584 // The previously attached AecDump will be destroyed with the
1585 // 'aec_dump' parameter, which is after locks are released.
1586 aec_dump_.swap(aec_dump);
1587 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001588 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001589}
1590
1591void AudioProcessingImpl::DetachAecDump() {
1592 // The d-tor of a task-queue based AecDump blocks until all pending
1593 // tasks are done. This construction avoids blocking while holding
1594 // the render and capture locks.
1595 std::unique_ptr<AecDump> aec_dump = nullptr;
1596 {
1597 rtc::CritScope cs_render(&crit_render_);
1598 rtc::CritScope cs_capture(&crit_capture_);
1599 aec_dump = std::move(aec_dump_);
1600 }
1601}
1602
Sam Zackrisson4d364492018-03-02 16:03:21 +01001603void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1604 std::unique_ptr<AudioGenerator> audio_generator) {
1605 // TODO(bugs.webrtc.org/8882) Stub.
1606 // Reset internal audio generator with audio_generator.
1607}
1608
1609void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1610 // TODO(bugs.webrtc.org/8882) Stub.
1611 // Delete audio generator, if one is attached.
1612}
1613
ivoc4e477a12017-01-15 08:29:46 -08001614AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1615 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1616 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1617 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1618 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1619}
1620
1621AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1622 const AudioProcessingStatistics& other) = default;
1623
1624AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1625 default;
1626
ivoc3e9a5372016-10-28 07:55:33 -07001627// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1628AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1629 const {
1630 return AudioProcessingStatistics();
1631}
1632
Ivo Creusenae026092017-11-20 13:07:16 +01001633// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001634AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001635 bool has_remote_tracks) const {
1636 return AudioProcessingStats();
1637}
1638
ivoc3e9a5372016-10-28 07:55:33 -07001639AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1640 const {
1641 AudioProcessingStatistics stats;
1642 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001643 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001644 rtc::CritScope cs_capture(&crit_capture_);
1645 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1646 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1647 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1648 // Instant value will also be used for min, max and average.
1649 stats.echo_return_loss.Set(erl, erl, erl, erl);
1650 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1651 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1652 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001653 stats.a_nlp.Set(metrics.a_nlp);
1654 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1655 stats.echo_return_loss.Set(metrics.echo_return_loss);
1656 stats.echo_return_loss_enhancement.Set(
1657 metrics.echo_return_loss_enhancement);
1658 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1659 }
ivoc9c192b22017-03-16 04:22:14 -07001660 {
1661 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001662 RTC_DCHECK(private_submodules_->echo_detector);
1663 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1664 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001665 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001666 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001667 }
ivoc3e9a5372016-10-28 07:55:33 -07001668 public_submodules_->echo_cancellation->GetDelayMetrics(
1669 &stats.delay_median, &stats.delay_standard_deviation,
1670 &stats.fraction_poor_delays);
1671 return stats;
1672}
1673
Ivo Creusen56d46092017-11-24 17:29:59 +01001674AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001675 bool has_remote_tracks) const {
1676 AudioProcessingStats stats;
1677 if (has_remote_tracks) {
1678 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001679 if (private_submodules_->echo_controller) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001680 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001681 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1682 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001683 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001684 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001685 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001686 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1687 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001688 if (metrics.divergent_filter_fraction != -1.0f) {
1689 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001690 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001691 }
1692 if (metrics.echo_return_loss.instant != -100) {
1693 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001694 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001695 }
1696 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001697 stats.echo_return_loss_enhancement = absl::optional<double>(
1698 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001699 }
1700 }
1701 if (config_.residual_echo_detector.enabled) {
1702 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001703 RTC_DCHECK(private_submodules_->echo_detector);
1704 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1705 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001706 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001707 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001708 }
1709 int delay_median, delay_std;
1710 float fraction_poor_delays;
1711 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1712 &delay_median, &delay_std, &fraction_poor_delays) ==
1713 Error::kNoError) {
1714 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001715 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001716 }
1717 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001718 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001719 }
1720 }
1721 }
1722 return stats;
1723}
1724
niklase@google.com470e71d2011-07-07 08:21:25 +00001725EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001726 return public_submodules_->echo_cancellation_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001727}
1728
1729EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001730 return public_submodules_->echo_control_mobile_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001731}
1732
1733GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001734 if (constants_.use_experimental_agc) {
1735 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001736 }
peahbfa97112016-03-10 21:09:04 -08001737 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001738}
1739
1740HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001741 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
1744LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001745 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001746}
1747
1748NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001749 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001750}
1751
1752VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001753 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001754}
1755
peah8271d042016-11-22 07:24:52 -08001756void AudioProcessingImpl::MutateConfig(
1757 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1758 rtc::CritScope cs_render(&crit_render_);
1759 rtc::CritScope cs_capture(&crit_capture_);
1760 mutator(&config_);
1761 ApplyConfig(config_);
1762}
1763
1764AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1765 rtc::CritScope cs_render(&crit_render_);
1766 rtc::CritScope cs_capture(&crit_capture_);
1767 return config_;
1768}
1769
peah2ace3f92016-09-10 04:42:27 -07001770bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1771 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001772 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001773 public_submodules_->echo_cancellation->is_enabled(),
1774 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001775 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001776 public_submodules_->noise_suppression->is_enabled(),
1777 capture_nonlocked_.intelligibility_enabled,
peah2ace3f92016-09-10 04:42:27 -07001778 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001779 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001780 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001781 public_submodules_->voice_detection->is_enabled(),
1782 public_submodules_->level_estimator->is_enabled(),
1783 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001784}
1785
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001786
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001787void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001788 if (capture_.transient_suppressor_enabled) {
1789 if (!public_submodules_->transient_suppressor.get()) {
1790 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001791 }
peahdf3efa82015-11-28 12:35:15 -08001792 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001793 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1794 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001795 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001796}
1797
ekmeyerson60d9b332015-08-14 10:35:55 -07001798void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001799#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001800 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001801 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001802 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001803 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001804 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001805 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001806 }
peah1bcfce52016-08-26 07:16:04 -07001807#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001808}
1809
peah8271d042016-11-22 07:24:52 -08001810void AudioProcessingImpl::InitializeLowCutFilter() {
1811 if (config_.high_pass_filter.enabled) {
1812 private_submodules_->low_cut_filter.reset(
1813 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1814 } else {
1815 private_submodules_->low_cut_filter.reset();
1816 }
1817}
alessiob3ec96df2017-05-22 06:57:06 -07001818
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001819void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001820 if (echo_control_factory_) {
1821 private_submodules_->echo_controller =
1822 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001823 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001824 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001825 }
1826}
peah8271d042016-11-22 07:24:52 -08001827
alessiob3ec96df2017-05-22 06:57:06 -07001828void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001829 if (config_.gain_controller2.enabled) {
1830 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001831 }
1832}
1833
Alex Loikob5c9a792018-04-16 16:31:22 +02001834void AudioProcessingImpl::InitializePreAmplifier() {
1835 if (config_.pre_amplifier.enabled) {
1836 private_submodules_->pre_amplifier.reset(
1837 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1838 } else {
1839 private_submodules_->pre_amplifier.reset();
1840 }
1841}
1842
ivoc9f4a4a02016-10-28 05:39:16 -07001843void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001844 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001845 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001846 proc_sample_rate_hz(), 1,
1847 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001848}
1849
Sam Zackrisson0beac582017-09-25 12:04:02 +02001850void AudioProcessingImpl::InitializePostProcessor() {
1851 if (private_submodules_->capture_post_processor) {
1852 private_submodules_->capture_post_processor->Initialize(
1853 proc_sample_rate_hz(), num_proc_channels());
1854 }
1855}
1856
Alex Loiko5825aa62017-12-18 16:02:40 +01001857void AudioProcessingImpl::InitializePreProcessor() {
1858 if (private_submodules_->render_pre_processor) {
1859 private_submodules_->render_pre_processor->Initialize(
1860 formats_.render_processing_format.sample_rate_hz(),
1861 formats_.render_processing_format.num_channels());
1862 }
1863}
1864
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001865void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001866 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001867
1868 if (echo_cancellation()->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001869 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1870 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001871 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001872 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001873 capture_.stream_delay_jumps = 0;
1874 }
1875 if (capture_.aec_system_delay_jumps == -1 &&
1876 echo_cancellation()->stream_has_echo()) {
1877 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001878 }
1879
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001880 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001881 const int diff_stream_delay_ms =
1882 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1883 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1884 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001885 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1886 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001887 if (capture_.stream_delay_jumps == -1) {
1888 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001889 }
peahdf3efa82015-11-28 12:35:15 -08001890 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001891 }
peahdf3efa82015-11-28 12:35:15 -08001892 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001893
1894 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001895 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001896 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001897 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001898 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001899 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1900 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001901 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001902 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001903 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001904 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001905 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1906 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1907 100);
peahdf3efa82015-11-28 12:35:15 -08001908 if (capture_.aec_system_delay_jumps == -1) {
1909 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001910 }
peahdf3efa82015-11-28 12:35:15 -08001911 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001912 }
peahdf3efa82015-11-28 12:35:15 -08001913 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001914 }
1915}
1916
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001917void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001918 // Run in a single-threaded manner.
1919 rtc::CritScope cs_render(&crit_render_);
1920 rtc::CritScope cs_capture(&crit_capture_);
1921
1922 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001923 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001924 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001925 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001926 }
peahdf3efa82015-11-28 12:35:15 -08001927 capture_.stream_delay_jumps = -1;
1928 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001929
peahdf3efa82015-11-28 12:35:15 -08001930 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001931 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1932 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001933 }
peahdf3efa82015-11-28 12:35:15 -08001934 capture_.aec_system_delay_jumps = -1;
1935 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001936}
1937
aleloi868f32f2017-05-23 07:20:05 -07001938void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1939 if (!aec_dump_) {
1940 return;
1941 }
1942 std::string experiments_description =
1943 public_submodules_->echo_cancellation->GetExperimentsDescription();
1944 // TODO(peah): Add semicolon-separated concatenations of experiment
1945 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001946 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1947 experiments_description += "AgcClippingLevelExperiment;";
1948 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001949 if (capture_nonlocked_.echo_controller_enabled) {
1950 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001951 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001952 if (config_.gain_controller2.enabled) {
1953 experiments_description += "GainController2;";
1954 }
aleloi868f32f2017-05-23 07:20:05 -07001955
1956 InternalAPMConfig apm_config;
1957
1958 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1959 apm_config.aec_delay_agnostic_enabled =
1960 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1961 apm_config.aec_drift_compensation_enabled =
1962 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1963 apm_config.aec_extended_filter_enabled =
1964 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1965 apm_config.aec_suppression_level = static_cast<int>(
1966 public_submodules_->echo_cancellation->suppression_level());
1967
1968 apm_config.aecm_enabled =
1969 public_submodules_->echo_control_mobile->is_enabled();
1970 apm_config.aecm_comfort_noise_enabled =
1971 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1972 apm_config.aecm_routing_mode =
1973 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1974
1975 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1976 apm_config.agc_mode =
1977 static_cast<int>(public_submodules_->gain_control->mode());
1978 apm_config.agc_limiter_enabled =
1979 public_submodules_->gain_control->is_limiter_enabled();
1980 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1981
1982 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1983
1984 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1985 apm_config.ns_level =
1986 static_cast<int>(public_submodules_->noise_suppression->level());
1987
1988 apm_config.transient_suppression_enabled =
1989 capture_.transient_suppressor_enabled;
1990 apm_config.intelligibility_enhancer_enabled =
1991 capture_nonlocked_.intelligibility_enabled;
1992 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001993 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1994 apm_config.pre_amplifier_fixed_gain_factor =
1995 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001996
1997 if (!forced && apm_config == apm_config_for_aec_dump_) {
1998 return;
1999 }
2000 aec_dump_->WriteConfig(apm_config);
2001 apm_config_for_aec_dump_ = apm_config;
2002}
2003
2004void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2005 const float* const* src) {
2006 RTC_DCHECK(aec_dump_);
2007 WriteAecDumpConfigMessage(false);
2008
2009 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2010 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2011 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002012 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002013 RecordAudioProcessingState();
2014}
2015
2016void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2017 const AudioFrame& capture_frame) {
2018 RTC_DCHECK(aec_dump_);
2019 WriteAecDumpConfigMessage(false);
2020
2021 aec_dump_->AddCaptureStreamInput(capture_frame);
2022 RecordAudioProcessingState();
2023}
2024
2025void AudioProcessingImpl::RecordProcessedCaptureStream(
2026 const float* const* processed_capture_stream) {
2027 RTC_DCHECK(aec_dump_);
2028
2029 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2030 const size_t num_channels =
2031 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002032 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2033 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002034 aec_dump_->WriteCaptureStreamMessage();
2035}
2036
2037void AudioProcessingImpl::RecordProcessedCaptureStream(
2038 const AudioFrame& processed_capture_frame) {
2039 RTC_DCHECK(aec_dump_);
2040
2041 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2042 aec_dump_->WriteCaptureStreamMessage();
2043}
2044
2045void AudioProcessingImpl::RecordAudioProcessingState() {
2046 RTC_DCHECK(aec_dump_);
2047 AecDump::AudioProcessingState audio_proc_state;
2048 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2049 audio_proc_state.drift =
2050 public_submodules_->echo_cancellation->stream_drift_samples();
2051 audio_proc_state.level = gain_control()->stream_analog_level();
2052 audio_proc_state.keypress = capture_.key_pressed;
2053 aec_dump_->AddAudioProcessingState(audio_proc_state);
2054}
2055
kwiberg83ffe452016-08-29 14:46:07 -07002056AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002057 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002058 : aec_system_delay_jumps(-1),
2059 delay_offset_ms(0),
2060 was_stream_delay_set(false),
2061 last_stream_delay_ms(0),
2062 last_aec_system_delay_ms(0),
2063 stream_delay_jumps(-1),
2064 output_will_be_muted(false),
2065 key_pressed(false),
2066 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002067 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002068 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002069 echo_path_gain_change(false),
2070 prev_analog_mic_level(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002071
2072AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2073
2074AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2075
2076AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2077
niklase@google.com470e71d2011-07-07 08:21:25 +00002078} // namespace webrtc