blob: e229b455ac32851c486fe0ce7446fc3d98401373 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/common.h"
26#include "modules/audio_processing/echo_cancellation_impl.h"
27#include "modules/audio_processing/echo_control_mobile_impl.h"
28#include "modules/audio_processing/gain_control_for_experimental_agc.h"
29#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010030#include "modules/audio_processing/gain_controller2.h"
Per Åhgren13735822018-02-12 21:42:56 +010031#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
33#include "rtc_base/logging.h"
34#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020035#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070037#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070039#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "modules/audio_processing/level_estimator_impl.h"
41#include "modules/audio_processing/low_cut_filter.h"
42#include "modules/audio_processing/noise_suppression_impl.h"
43#include "modules/audio_processing/residual_echo_detector.h"
44#include "modules/audio_processing/transient/transient_suppressor.h"
45#include "modules/audio_processing/voice_detection_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010046#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000048
peah1bcfce52016-08-26 07:16:04 -070049// Check to verify that the define for the intelligibility enhancer is properly
50// set.
51#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
52 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
53 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
54#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
55#endif
56
Michael Graczyk86c6d332015-07-23 11:41:39 -070057#define RETURN_ON_ERR(expr) \
58 do { \
59 int err = (expr); \
60 if (err != kNoError) { \
61 return err; \
62 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000063 } while (0)
64
niklase@google.com470e71d2011-07-07 08:21:25 +000065namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070066
kwibergd59d3bb2016-09-13 07:49:33 -070067constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020068constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070069
Michael Graczyk86c6d332015-07-23 11:41:39 -070070namespace {
71
72static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
73 switch (layout) {
74 case AudioProcessing::kMono:
75 case AudioProcessing::kStereo:
76 return false;
77 case AudioProcessing::kMonoAndKeyboard:
78 case AudioProcessing::kStereoAndKeyboard:
79 return true;
80 }
81
kwiberg9e2be5f2016-09-14 05:23:22 -070082 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070083 return false;
84}
aluebsdf6416a2016-03-16 18:26:35 -070085
peah2ace3f92016-09-10 04:42:27 -070086bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070087 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
88 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
89}
90
peah2ace3f92016-09-10 04:42:27 -070091int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
92#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070093 constexpr int kMaxSplittingNativeProcessRate =
94 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070095#else
kwibergd59d3bb2016-09-13 07:49:33 -070096 constexpr int kMaxSplittingNativeProcessRate =
97 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070098#endif
kwibergd59d3bb2016-09-13 07:49:33 -070099 static_assert(
100 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
101 "");
peah2ace3f92016-09-10 04:42:27 -0700102 const int uppermost_native_rate = band_splitting_required
103 ? kMaxSplittingNativeProcessRate
104 : AudioProcessing::kSampleRate48kHz;
105
106 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
107 if (rate >= uppermost_native_rate) {
108 return uppermost_native_rate;
109 }
110 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700111 return rate;
112 }
113 }
peah2ace3f92016-09-10 04:42:27 -0700114 RTC_NOTREACHED();
115 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700116}
117
peah9e6a2902017-05-15 07:19:21 -0700118// Maximum lengths that frame of samples being passed from the render side to
119// the capture side can have (does not apply to AEC3).
120static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
121static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
122
peah764e3642016-10-22 05:04:30 -0700123// Maximum number of frames to buffer in the render queue.
124// TODO(peah): Decrease this once we properly handle hugely unbalanced
125// reverse and forward call numbers.
126static const size_t kMaxNumFramesToBuffer = 100;
127
peah8271d042016-11-22 07:24:52 -0800128class HighPassFilterImpl : public HighPassFilter {
129 public:
130 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
131 ~HighPassFilterImpl() override = default;
132
133 // HighPassFilter implementation.
134 int Enable(bool enable) override {
135 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
136 config->high_pass_filter.enabled = enable;
137 });
138
139 return AudioProcessing::kNoError;
140 }
141
142 bool is_enabled() const override {
143 return apm_->GetConfig().high_pass_filter.enabled;
144 }
145
146 private:
147 AudioProcessingImpl* apm_;
148 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
149};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700150} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000151
152// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000153static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000154
Sam Zackrisson0beac582017-09-25 12:04:02 +0200155AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100156 bool capture_post_processor_enabled,
157 bool render_pre_processor_enabled)
158 : capture_post_processor_enabled_(capture_post_processor_enabled),
159 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700160
161bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800162 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700163 bool echo_canceller_enabled,
164 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700165 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool noise_suppressor_enabled,
167 bool intelligibility_enhancer_enabled,
peah2ace3f92016-09-10 04:42:27 -0700168 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700169 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200170 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200171 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700172 bool voice_activity_detector_enabled,
173 bool level_estimator_enabled,
174 bool transient_suppressor_enabled) {
175 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800176 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700177 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
178 changed |=
179 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700180 changed |=
181 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700182 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
183 changed |=
184 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700185 changed |=
186 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700187 changed |=
188 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200189 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200190 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700191 changed |= (level_estimator_enabled != level_estimator_enabled_);
192 changed |=
193 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
194 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
195 if (changed) {
peah8271d042016-11-22 07:24:52 -0800196 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700197 echo_canceller_enabled_ = echo_canceller_enabled;
198 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700199 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700200 noise_suppressor_enabled_ = noise_suppressor_enabled;
201 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
peah2ace3f92016-09-10 04:42:27 -0700202 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700203 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200204 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200205 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700206 level_estimator_enabled_ = level_estimator_enabled;
207 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
208 transient_suppressor_enabled_ = transient_suppressor_enabled;
209 }
210
211 changed |= first_update_;
212 first_update_ = false;
213 return changed;
214}
215
216bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
217 const {
218#if WEBRTC_INTELLIGIBILITY_ENHANCER
219 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700220 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700221#else
peah52775842017-05-16 06:14:09 -0700222 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700223#endif
224}
225
226bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
227 const {
peah8271d042016-11-22 07:24:52 -0800228 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700229 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200230 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700231}
232
peah23ac8b42017-05-23 05:33:56 -0700233bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
234 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200235 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
236 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700237}
238
peah2ace3f92016-09-10 04:42:27 -0700239bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
240 const {
241 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800242 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200243 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700244}
245
Alex Loiko5825aa62017-12-18 16:02:40 +0100246bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
247 const {
248 return render_pre_processor_enabled_;
249}
250
peah2ace3f92016-09-10 04:42:27 -0700251bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
252 const {
253#if WEBRTC_INTELLIGIBILITY_ENHANCER
254 return intelligibility_enhancer_enabled_;
255#else
256 return false;
257#endif
258}
259
solenberg5e465c32015-12-08 13:22:33 -0800260struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800261 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800262 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800263 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800264 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800265 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800266 std::unique_ptr<LevelEstimatorImpl> level_estimator;
267 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
268 std::unique_ptr<VoiceDetectionImpl> voice_detection;
269 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800270 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800271
272 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800273 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700274#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800275 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700276#endif
solenberg5e465c32015-12-08 13:22:33 -0800277};
278
279struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200280 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100281 std::unique_ptr<CustomProcessing> render_pre_processor,
Ivo Creusend1f970d2018-06-14 11:02:03 +0200282 rtc::scoped_refptr<EchoDetector> echo_detector)
Sam Zackrissondb389722018-06-21 10:12:24 +0200283 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100284 capture_post_processor(std::move(capture_post_processor)),
285 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800286 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800287 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700288 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800289 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200290 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200291 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100292 std::unique_ptr<CustomProcessing> capture_post_processor;
293 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200294 std::unique_ptr<GainApplier> pre_amplifier;
solenberg5e465c32015-12-08 13:22:33 -0800295};
296
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100297AudioProcessingBuilder::AudioProcessingBuilder() = default;
298AudioProcessingBuilder::~AudioProcessingBuilder() = default;
299
300AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
301 std::unique_ptr<CustomProcessing> capture_post_processing) {
302 capture_post_processing_ = std::move(capture_post_processing);
303 return *this;
304}
305
306AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
307 std::unique_ptr<CustomProcessing> render_pre_processing) {
308 render_pre_processing_ = std::move(render_pre_processing);
309 return *this;
310}
311
312AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
313 std::unique_ptr<EchoControlFactory> echo_control_factory) {
314 echo_control_factory_ = std::move(echo_control_factory);
315 return *this;
316}
317
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100318AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200319 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100320 echo_detector_ = std::move(echo_detector);
321 return *this;
322}
323
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100324AudioProcessing* AudioProcessingBuilder::Create() {
325 webrtc::Config config;
326 return Create(config);
327}
328
329AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100330 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
331 config, std::move(capture_post_processing_),
332 std::move(render_pre_processing_), std::move(echo_control_factory_),
Sam Zackrissondb389722018-06-21 10:12:24 +0200333 std::move(echo_detector_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100334 if (apm->Initialize() != AudioProcessing::kNoError) {
335 delete apm;
336 apm = nullptr;
337 }
338 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100339}
340
peah88ac8532016-09-12 16:47:25 -0700341AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissondb389722018-06-21 10:12:24 +0200342 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000343
Per Åhgren13735822018-02-12 21:42:56 +0100344int AudioProcessingImpl::instance_count_ = 0;
345
Sam Zackrisson0beac582017-09-25 12:04:02 +0200346AudioProcessingImpl::AudioProcessingImpl(
347 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100348 std::unique_ptr<CustomProcessing> capture_post_processor,
349 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200350 std::unique_ptr<EchoControlFactory> echo_control_factory,
Sam Zackrissondb389722018-06-21 10:12:24 +0200351 rtc::scoped_refptr<EchoDetector> echo_detector)
Per Åhgren13735822018-02-12 21:42:56 +0100352 : data_dumper_(
353 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200354 capture_runtime_settings_(kRuntimeSettingQueueSize),
355 render_runtime_settings_(kRuntimeSettingQueueSize),
356 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
357 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100358 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200359 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100360 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800361 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200362 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200363 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100364 std::move(render_pre_processor),
365 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800366 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800367 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000368#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loiko64cb83b2018-07-02 13:38:19 +0200369 false,
370 false,
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700371 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000372#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200373 config.Get<ExperimentalAgc>().enabled,
374 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
375 config.Get<ExperimentalAgc>().enabled_agc2_digital_adaptive),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000376#endif
andrew1c7075f2015-06-24 18:14:14 -0700377#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200378 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700379#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200380 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700381#endif
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200382 capture_nonlocked_(config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800383 {
384 rtc::CritScope cs_render(&crit_render_);
385 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000386
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200387 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson771b50c2018-07-23 15:21:52 +0200388 if (echo_control_factory_) {
389 config_.echo_cancellation.enabled = true;
390 capture_nonlocked_.echo_controller_enabled = true;
391 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200392
peahb624d8c2016-03-05 03:01:14 -0800393 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700394 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800395 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700396 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800397 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200398 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800399 public_submodules_->level_estimator.reset(
400 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800401 public_submodules_->noise_suppression.reset(
402 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800403 public_submodules_->voice_detection.reset(
404 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800405 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800406 new GainControlForExperimentalAgc(
407 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100408
409 // If no echo detector is injected, use the ResidualEchoDetector.
410 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200411 private_submodules_->echo_detector =
412 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100413 }
peahca4cac72016-06-29 15:26:12 -0700414
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200415 // TODO(alessiob): Move the injected gain controller once injection is
416 // implemented.
417 private_submodules_->gain_controller2.reset(new GainController2());
418
Mirko Bonadei675513b2017-11-09 11:09:25 +0100419 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100420 << !!private_submodules_->capture_post_processor
421 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100422 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800423 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000424
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000425 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000426}
427
428AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800429 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800430 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800431 private_submodules_->agc_manager.reset();
432 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800433 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000434}
435
niklase@google.com470e71d2011-07-07 08:21:25 +0000436int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800437 // Run in a single-threaded manner during initialization.
438 rtc::CritScope cs_render(&crit_render_);
439 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000440 return InitializeLocked();
441}
442
peahde65ddc2016-09-16 15:02:15 -0700443int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
444 int capture_output_sample_rate_hz,
445 int render_input_sample_rate_hz,
446 ChannelLayout capture_input_layout,
447 ChannelLayout capture_output_layout,
448 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700449 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700450 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
451 LayoutHasKeyboard(capture_input_layout)},
452 {capture_output_sample_rate_hz,
453 ChannelsFromLayout(capture_output_layout),
454 LayoutHasKeyboard(capture_output_layout)},
455 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
456 LayoutHasKeyboard(render_input_layout)},
457 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
458 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700459
460 return Initialize(processing_config);
461}
462
463int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800464 // Run in a single-threaded manner during initialization.
465 rtc::CritScope cs_render(&crit_render_);
466 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700467 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000468}
469
peahdf3efa82015-11-28 12:35:15 -0800470int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800471 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700472 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800473}
474
peahdf3efa82015-11-28 12:35:15 -0800475int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700476 const ProcessingConfig& processing_config,
477 bool force_initialization) {
478 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800479}
480
peah192164e2015-11-17 02:16:45 -0800481// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800482// their current values (needs to be called while holding the crit_render_lock).
483int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700484 const ProcessingConfig& processing_config,
485 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800486 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700487 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800488 return kNoError;
489 }
peahdf3efa82015-11-28 12:35:15 -0800490
491 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800492 return InitializeLocked(processing_config);
493}
494
niklase@google.com470e71d2011-07-07 08:21:25 +0000495int AudioProcessingImpl::InitializeLocked() {
Sam Zackrisson771b50c2018-07-23 15:21:52 +0200496 // Ensure at most one built-in AEC is active, by arbitrarily preferring AEC2.
497 if (public_submodules_->echo_cancellation->is_enabled()) {
498 echo_control_mobile()->Enable(false);
499 config_.echo_cancellation.enabled = true;
500 config_.echo_cancellation.mobile_mode = false;
501 } else if (public_submodules_->echo_control_mobile->is_enabled()) {
502 config_.echo_cancellation.enabled = true;
503 config_.echo_cancellation.mobile_mode = true;
504 }
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_) {
Alex Loiko1aec5942018-05-15 13:13:22 +0200585 aec_dump_->WriteInitMessage(formats_.api_format);
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
Sam Zackrisson771b50c2018-07-23 15:21:52 +0200680 capture_nonlocked_.echo_controller_enabled =
681 config_.echo_cancellation.enabled && private_submodules_->echo_controller;
682 echo_cancellation()->Enable(config_.echo_cancellation.enabled &&
683 !config_.echo_cancellation.mobile_mode);
684 echo_control_mobile()->Enable(config_.echo_cancellation.enabled &&
685 config_.echo_cancellation.mobile_mode);
686
peah8271d042016-11-22 07:24:52 -0800687 InitializeLowCutFilter();
688
Mirko Bonadei675513b2017-11-09 11:09:25 +0100689 RTC_LOG(LS_INFO) << "Highpass filter activated: "
690 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800691
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100692 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700693 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100694 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
695 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100696 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100697 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700698 config_.gain_controller2 = AudioProcessing::Config::GainController2();
699 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200700 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200701 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200702 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100703 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
704 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200705 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
706 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700707}
708
709void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800710 // Run in a single-threaded manner when setting the extra options.
711 rtc::CritScope cs_render(&crit_render_);
712 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000713
peahb624d8c2016-03-05 03:01:14 -0800714 public_submodules_->echo_cancellation->SetExtraOptions(config);
715
peahdf3efa82015-11-28 12:35:15 -0800716 if (capture_.transient_suppressor_enabled !=
717 config.Get<ExperimentalNs>().enabled) {
718 capture_.transient_suppressor_enabled =
719 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000720 InitializeTransient();
721 }
aluebs2a346882016-01-11 18:04:30 -0800722
peah1bcfce52016-08-26 07:16:04 -0700723#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700724 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700725 config.Get<Intelligibility>().enabled) {
726 capture_nonlocked_.intelligibility_enabled =
727 config.Get<Intelligibility>().enabled;
728 InitializeIntelligibility();
729 }
peah1bcfce52016-08-26 07:16:04 -0700730#endif
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000731}
732
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000733int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800734 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700735 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000736}
737
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000738int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800739 // Used as callback from submodules, hence locking is not allowed.
740 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000741}
742
Peter Kasting69558702016-01-12 16:26:35 -0800743size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800744 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700745 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000746}
747
Peter Kasting69558702016-01-12 16:26:35 -0800748size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800749 // Used as callback from submodules, hence locking is not allowed.
750 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000751}
752
Peter Kasting69558702016-01-12 16:26:35 -0800753size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800754 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200755 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800756}
757
Peter Kasting69558702016-01-12 16:26:35 -0800758size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800759 // Used as callback from submodules, hence locking is not allowed.
760 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000761}
762
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000763void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800764 rtc::CritScope cs(&crit_capture_);
765 capture_.output_will_be_muted = muted;
766 if (private_submodules_->agc_manager.get()) {
767 private_submodules_->agc_manager->SetCaptureMuted(
768 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000769 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000770}
771
Alessio Bazzicac054e782018-04-16 12:10:09 +0200772void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200773 switch (setting.type()) {
774 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
775 render_runtime_settings_enqueuer_.Enqueue(setting);
776 return;
777 case RuntimeSetting::Type::kNotSpecified:
778 RTC_NOTREACHED();
779 return;
780 case RuntimeSetting::Type::kCapturePreGain:
781 capture_runtime_settings_enqueuer_.Enqueue(setting);
782 return;
783 }
784 // The language allows the enum to have a non-enumerator
785 // value. Check that this doesn't happen.
786 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200787}
788
789AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
790 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200791 : runtime_settings_(*runtime_settings) {
792 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200793}
794
795AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
796 default;
797
798void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
799 RuntimeSetting setting) {
800 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200801 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200802 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200803 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200804 RTC_LOG(LS_ERROR)
805 << "The runtime settings queue is full. Oldest setting discarded.";
806 }
807 if (remaining_attempts == 0)
808 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
809}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000810
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000811int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700812 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000813 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000814 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000815 int output_sample_rate_hz,
816 ChannelLayout output_layout,
817 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800818 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800819 StreamConfig input_stream;
820 StreamConfig output_stream;
821 {
822 // Access the formats_.api_format.input_stream beneath the capture lock.
823 // The lock must be released as it is later required in the call
824 // to ProcessStream(,,,);
825 rtc::CritScope cs(&crit_capture_);
826 input_stream = formats_.api_format.input_stream();
827 output_stream = formats_.api_format.output_stream();
828 }
829
Michael Graczyk86c6d332015-07-23 11:41:39 -0700830 input_stream.set_sample_rate_hz(input_sample_rate_hz);
831 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
832 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700833 output_stream.set_sample_rate_hz(output_sample_rate_hz);
834 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
835 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
836
837 if (samples_per_channel != input_stream.num_frames()) {
838 return kBadDataLengthError;
839 }
840 return ProcessStream(src, input_stream, output_stream, dest);
841}
842
843int AudioProcessingImpl::ProcessStream(const float* const* src,
844 const StreamConfig& input_config,
845 const StreamConfig& output_config,
846 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800847 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800848 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700849 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800850 {
851 // Acquire the capture lock in order to safely call the function
852 // that retrieves the render side data. This function accesses apm
853 // getters that need the capture lock held when being called.
854 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700855 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800856
857 if (!src || !dest) {
858 return kNullPointerError;
859 }
860
861 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700862 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000863 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000864
Michael Graczyk86c6d332015-07-23 11:41:39 -0700865 processing_config.input_stream() = input_config;
866 processing_config.output_stream() = output_config;
867
peahdf3efa82015-11-28 12:35:15 -0800868 {
869 // Do conditional reinitialization.
870 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700871 RETURN_ON_ERR(
872 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800873 }
874 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700875 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
876 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000877
aleloi868f32f2017-05-23 07:20:05 -0700878 if (aec_dump_) {
879 RecordUnprocessedCaptureStream(src);
880 }
881
peahdf3efa82015-11-28 12:35:15 -0800882 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700883 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800884 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000885
aleloi868f32f2017-05-23 07:20:05 -0700886 if (aec_dump_) {
887 RecordProcessedCaptureStream(dest);
888 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000889 return kNoError;
890}
891
Alex Loiko73ec0192018-05-15 10:52:28 +0200892void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200893 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200894 while (capture_runtime_settings_.Remove(&setting)) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200895 switch (setting.type()) {
896 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200897 if (config_.pre_amplifier.enabled) {
898 float value;
899 setting.GetFloat(&value);
900 private_submodules_->pre_amplifier->SetGainFactor(value);
901 }
902 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200903 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200904 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
905 RTC_NOTREACHED();
906 break;
907 case RuntimeSetting::Type::kNotSpecified:
908 RTC_NOTREACHED();
909 break;
910 }
911 }
912}
913
914void AudioProcessingImpl::HandleRenderRuntimeSettings() {
915 RuntimeSetting setting;
916 while (render_runtime_settings_.Remove(&setting)) {
917 switch (setting.type()) {
918 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
919 if (private_submodules_->render_pre_processor) {
920 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
921 }
922 break;
923 case RuntimeSetting::Type::kCapturePreGain:
924 RTC_NOTREACHED();
925 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200926 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200927 RTC_NOTREACHED();
928 break;
929 }
930 }
931}
932
peah9e6a2902017-05-15 07:19:21 -0700933void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700934 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
935 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700936 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700937
kwibergaf476c72016-11-28 15:21:39 -0800938 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700939
940 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700941 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700942 // The data queue is full and needs to be emptied.
943 EmptyQueuedRenderAudio();
944
945 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700946 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700947 RTC_DCHECK(result);
948 }
949
950 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
951 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700952 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700953
954 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700955 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700956 // The data queue is full and needs to be emptied.
957 EmptyQueuedRenderAudio();
958
959 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700960 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700961 RTC_DCHECK(result);
962 }
peah701d6282016-10-25 05:42:20 -0700963
964 if (!constants_.use_experimental_agc) {
965 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
966 // Insert the samples into the queue.
967 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
968 // The data queue is full and needs to be emptied.
969 EmptyQueuedRenderAudio();
970
971 // Retry the insert (should always work).
972 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
973 RTC_DCHECK(result);
974 }
975 }
peah9e6a2902017-05-15 07:19:21 -0700976}
ivoc9f4a4a02016-10-28 05:39:16 -0700977
peah9e6a2902017-05-15 07:19:21 -0700978void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700979 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
980
981 // Insert the samples into the queue.
982 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
983 // The data queue is full and needs to be emptied.
984 EmptyQueuedRenderAudio();
985
986 // Retry the insert (should always work).
987 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
988 RTC_DCHECK(result);
989 }
peah764e3642016-10-22 05:04:30 -0700990}
991
992void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700993 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700994 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700995 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700996 EchoCancellationImpl::NumCancellersRequired(
997 num_output_channels(), num_reverse_channels()));
998
peah701d6282016-10-25 05:42:20 -0700999 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001000 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001001 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001002 EchoControlMobileImpl::NumCancellersRequired(
1003 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001004
peah701d6282016-10-25 05:42:20 -07001005 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001006 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001007
ivoc9f4a4a02016-10-28 05:39:16 -07001008 const size_t new_red_render_queue_element_max_size =
1009 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1010
peaha0624602016-10-25 04:45:24 -07001011 // Reallocate the queues if the queue item sizes are too small to fit the
1012 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001013 if (aec_render_queue_element_max_size_ <
1014 new_aec_render_queue_element_max_size) {
1015 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001016
peaha0624602016-10-25 04:45:24 -07001017 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001018 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001019
peah701d6282016-10-25 05:42:20 -07001020 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001021 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1022 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001023 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001024 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001025
peah701d6282016-10-25 05:42:20 -07001026 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1027 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001028 } else {
peah701d6282016-10-25 05:42:20 -07001029 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001030 }
1031
peah701d6282016-10-25 05:42:20 -07001032 if (aecm_render_queue_element_max_size_ <
1033 new_aecm_render_queue_element_max_size) {
1034 aecm_render_queue_element_max_size_ =
1035 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001036
1037 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001038 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001039
peah701d6282016-10-25 05:42:20 -07001040 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001041 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1042 kMaxNumFramesToBuffer, template_queue_element,
1043 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001044 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001045
peah701d6282016-10-25 05:42:20 -07001046 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1047 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001048 } else {
peah701d6282016-10-25 05:42:20 -07001049 aecm_render_signal_queue_->Clear();
1050 }
1051
1052 if (agc_render_queue_element_max_size_ <
1053 new_agc_render_queue_element_max_size) {
1054 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1055
1056 std::vector<int16_t> template_queue_element(
1057 agc_render_queue_element_max_size_);
1058
1059 agc_render_signal_queue_.reset(
1060 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1061 kMaxNumFramesToBuffer, template_queue_element,
1062 RenderQueueItemVerifier<int16_t>(
1063 agc_render_queue_element_max_size_)));
1064
1065 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1066 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1067 } else {
1068 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001069 }
ivoc9f4a4a02016-10-28 05:39:16 -07001070
1071 if (red_render_queue_element_max_size_ <
1072 new_red_render_queue_element_max_size) {
1073 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1074
1075 std::vector<float> template_queue_element(
1076 red_render_queue_element_max_size_);
1077
1078 red_render_signal_queue_.reset(
1079 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1080 kMaxNumFramesToBuffer, template_queue_element,
1081 RenderQueueItemVerifier<float>(
1082 red_render_queue_element_max_size_)));
1083
1084 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1085 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1086 } else {
1087 red_render_signal_queue_->Clear();
1088 }
peah764e3642016-10-22 05:04:30 -07001089}
1090
1091void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1092 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001093 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001094 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001095 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001096 }
1097
peah701d6282016-10-25 05:42:20 -07001098 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001099 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001100 aecm_capture_queue_buffer_);
1101 }
1102
1103 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1104 public_submodules_->gain_control->ProcessRenderAudio(
1105 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001106 }
ivoc9f4a4a02016-10-28 05:39:16 -07001107
1108 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001109 RTC_DCHECK(private_submodules_->echo_detector);
1110 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001111 red_capture_queue_buffer_);
1112 }
peah764e3642016-10-22 05:04:30 -07001113}
1114
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001115int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001116 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001117 {
1118 // Acquire the capture lock in order to safely call the function
1119 // that retrieves the render side data. This function accesses apm
1120 // getters that need the capture lock held when being called.
1121 // The lock needs to be released as
1122 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1123 // as well.
1124 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001125 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001126 }
peahfa6228e2015-11-16 16:27:42 -08001127
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001128 if (!frame) {
1129 return kNullPointerError;
1130 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001131 // Must be a native rate.
1132 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1133 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001134 frame->sample_rate_hz_ != kSampleRate32kHz &&
1135 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001136 return kBadSampleRateError;
1137 }
peah192164e2015-11-17 02:16:45 -08001138
peahdf3efa82015-11-28 12:35:15 -08001139 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001140 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001141 {
1142 // Aquire lock for the access of api_format.
1143 // The lock is released immediately due to the conditional
1144 // reinitialization.
1145 rtc::CritScope cs_capture(&crit_capture_);
1146 // TODO(ajm): The input and output rates and channels are currently
1147 // constrained to be identical in the int16 interface.
1148 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001149
1150 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001151 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001152 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1153 processing_config.input_stream().set_num_channels(frame->num_channels_);
1154 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1155 processing_config.output_stream().set_num_channels(frame->num_channels_);
1156
peahdf3efa82015-11-28 12:35:15 -08001157 {
1158 // Do conditional reinitialization.
1159 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001160 RETURN_ON_ERR(
1161 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001162 }
1163 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001164 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001165 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001166 return kBadDataLengthError;
1167 }
1168
aleloi868f32f2017-05-23 07:20:05 -07001169 if (aec_dump_) {
1170 RecordUnprocessedCaptureStream(*frame);
1171 }
1172
peahdf3efa82015-11-28 12:35:15 -08001173 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001174 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001175 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001176 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1177 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001178
aleloi868f32f2017-05-23 07:20:05 -07001179 if (aec_dump_) {
1180 RecordProcessedCaptureStream(*frame);
1181 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001182
1183 return kNoError;
1184}
1185
peahde65ddc2016-09-16 15:02:15 -07001186int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001187 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001188
peahb58a1582016-03-15 09:34:24 -07001189 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001190 // TODO(bugs.webrtc.org/9535): Simplify once the public API Enable functions
1191 // for these are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001192 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1193 public_submodules_->echo_control_mobile->is_enabled()));
1194
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001195 MaybeUpdateHistograms();
1196
peahde65ddc2016-09-16 15:02:15 -07001197 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001198
Alex Loikob5c9a792018-04-16 16:31:22 +02001199 if (private_submodules_->pre_amplifier) {
1200 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1201 capture_buffer->channels_f(), capture_buffer->num_channels(),
1202 capture_buffer->num_frames()));
1203 }
1204
peah1b08dc32016-12-20 13:45:58 -08001205 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001206 capture_buffer->channels_const()[0],
1207 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001208 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1209 if (log_rms) {
1210 capture_rms_interval_counter_ = 0;
1211 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001212 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1213 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1214 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1215 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001216 }
1217
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001218 if (capture_nonlocked_.echo_controller_enabled) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001219 // Detect and flag any change in the analog gain.
1220 int analog_mic_level = gain_control()->stream_analog_level();
1221 capture_.echo_path_gain_change =
1222 capture_.prev_analog_mic_level != analog_mic_level &&
1223 capture_.prev_analog_mic_level != -1;
1224 capture_.prev_analog_mic_level = analog_mic_level;
1225
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001226 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001227 }
1228
peahbe615622016-02-13 16:40:47 -08001229 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001230 public_submodules_->gain_control->is_enabled()) {
1231 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001232 capture_buffer->channels()[0], capture_buffer->num_channels(),
1233 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001234 }
1235
peah2ace3f92016-09-10 04:42:27 -07001236 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1237 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001238 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1239 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001240 }
1241
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001242 if (capture_nonlocked_.echo_controller_enabled) {
peah522d71b2017-02-23 05:16:26 -08001243 // Force down-mixing of the number of channels after the detection of
1244 // capture signal saturation.
1245 // TODO(peah): Look into ensuring that this kind of tampering with the
1246 // AudioBuffer functionality should not be needed.
1247 capture_buffer->set_num_channels(1);
1248 }
1249
peahe0eae3c2016-12-14 01:16:23 -08001250 // TODO(peah): Move the AEC3 low-cut filter to this place.
1251 if (private_submodules_->low_cut_filter &&
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001252 !capture_nonlocked_.echo_controller_enabled) {
peah8271d042016-11-22 07:24:52 -08001253 private_submodules_->low_cut_filter->Process(capture_buffer);
1254 }
peahde65ddc2016-09-16 15:02:15 -07001255 RETURN_ON_ERR(
1256 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1257 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001258
1259 // Ensure that the stream delay was set before the call to the
1260 // AEC ProcessCaptureAudio function.
1261 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001262 !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001263 return AudioProcessing::kStreamParameterNotSetError;
1264 }
1265
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001266 if (capture_nonlocked_.echo_controller_enabled) {
Per Åhgren13735822018-02-12 21:42:56 +01001267 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1268
Per Åhgrend0fa8202018-04-18 09:35:13 +02001269 if (was_stream_delay_set()) {
1270 private_submodules_->echo_controller->SetAudioBufferDelay(
1271 stream_delay_ms());
1272 }
1273
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001274 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001275 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001276 } else {
1277 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1278 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001279 }
1280
peahdf3efa82015-11-28 12:35:15 -08001281 if (public_submodules_->echo_control_mobile->is_enabled() &&
1282 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001283 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001284 }
peahde65ddc2016-09-16 15:02:15 -07001285 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001286#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001287 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001288 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001289 const int gain_db =
1290 public_submodules_->gain_control->is_enabled()
1291 ? public_submodules_->gain_control->compression_gain_db()
1292 : 0;
1293 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001294 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001295 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001296 }
peah1bcfce52016-08-26 07:16:04 -07001297#endif
peah253534d2016-03-15 04:32:28 -07001298
1299 // Ensure that the stream delay was set before the call to the
1300 // AECM ProcessCaptureAudio function.
1301 if (public_submodules_->echo_control_mobile->is_enabled() &&
1302 !was_stream_delay_set()) {
1303 return AudioProcessing::kStreamParameterNotSetError;
1304 }
1305
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001306 if (public_submodules_->echo_control_mobile->is_enabled()) {
Per Åhgren46537a32017-06-07 10:08:10 +02001307 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1308 capture_buffer, stream_delay_ms()));
1309 }
ivoc9f4a4a02016-10-28 05:39:16 -07001310
peahde65ddc2016-09-16 15:02:15 -07001311 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001312
peahbe615622016-02-13 16:40:47 -08001313 if (constants_.use_experimental_agc &&
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001314 public_submodules_->gain_control->is_enabled()) {
peahdf3efa82015-11-28 12:35:15 -08001315 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001316 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1317 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001318 }
peahb8fbb542016-03-15 02:28:08 -07001319 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001320 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001321
peah2ace3f92016-09-10 04:42:27 -07001322 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1323 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001324 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1325 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001326 }
1327
peah9e6a2902017-05-15 07:19:21 -07001328 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001329 RTC_DCHECK(private_submodules_->echo_detector);
1330 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001331 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1332 capture_buffer->num_frames()));
1333 }
1334
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001335 // TODO(aluebs): Investigate if the transient suppression placement should be
1336 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001337 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001338 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001339 private_submodules_->agc_manager.get()
1340 ? private_submodules_->agc_manager->voice_probability()
1341 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001342
peahdf3efa82015-11-28 12:35:15 -08001343 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001344 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1345 capture_buffer->num_channels(),
1346 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1347 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1348 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001349 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001350 }
1351
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001352 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001353 private_submodules_->gain_controller2->Process(capture_buffer);
1354 }
1355
Sam Zackrisson0beac582017-09-25 12:04:02 +02001356 if (private_submodules_->capture_post_processor) {
1357 private_submodules_->capture_post_processor->Process(capture_buffer);
1358 }
1359
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001360 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001361 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001362
peah1b08dc32016-12-20 13:45:58 -08001363 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1364 capture_buffer->channels_const()[0],
1365 capture_nonlocked_.capture_processing_format.num_frames()));
1366 if (log_rms) {
1367 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1368 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1369 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1370 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1371 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1372 }
1373
peahdf3efa82015-11-28 12:35:15 -08001374 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001375 return kNoError;
1376}
1377
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001378int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001379 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001380 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001381 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001382 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001383 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001384 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001385 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001386 };
1387 if (samples_per_channel != reverse_config.num_frames()) {
1388 return kBadDataLengthError;
1389 }
peahdf3efa82015-11-28 12:35:15 -08001390 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001391}
1392
peahde65ddc2016-09-16 15:02:15 -07001393int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1394 const StreamConfig& input_config,
1395 const StreamConfig& output_config,
1396 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001397 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001398 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001399 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001400 if (submodule_states_.RenderMultiBandProcessingActive() ||
1401 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001402 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1403 dest);
peah2ace3f92016-09-10 04:42:27 -07001404 } else if (formats_.api_format.reverse_input_stream() !=
1405 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001406 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1407 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001408 } else {
peahde65ddc2016-09-16 15:02:15 -07001409 CopyAudioIfNeeded(src, input_config.num_frames(),
1410 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001411 }
1412
1413 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001414}
1415
peahdf3efa82015-11-28 12:35:15 -08001416int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001417 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001418 const StreamConfig& input_config,
1419 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001420 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001421 return kNullPointerError;
1422 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001423
peahde65ddc2016-09-16 15:02:15 -07001424 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001425 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001426 }
1427
peahdf3efa82015-11-28 12:35:15 -08001428 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001429 processing_config.reverse_input_stream() = input_config;
1430 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001431
peahdf3efa82015-11-28 12:35:15 -08001432 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001433 RTC_DCHECK_EQ(input_config.num_frames(),
1434 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001435
aleloi868f32f2017-05-23 07:20:05 -07001436 if (aec_dump_) {
1437 const size_t channel_size =
1438 formats_.api_format.reverse_input_stream().num_frames();
1439 const size_t num_channels =
1440 formats_.api_format.reverse_input_stream().num_channels();
1441 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001442 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001443 }
peahdf3efa82015-11-28 12:35:15 -08001444 render_.render_audio->CopyFrom(src,
1445 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001446 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001447}
1448
1449int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001450 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001451 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001452 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001453 return kNullPointerError;
1454 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001455 // Must be a native rate.
1456 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1457 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001458 frame->sample_rate_hz_ != kSampleRate32kHz &&
1459 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001460 return kBadSampleRateError;
1461 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001462
Michael Graczyk86c6d332015-07-23 11:41:39 -07001463 if (frame->num_channels_ <= 0) {
1464 return kBadNumberChannelsError;
1465 }
1466
peahdf3efa82015-11-28 12:35:15 -08001467 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001468 processing_config.reverse_input_stream().set_sample_rate_hz(
1469 frame->sample_rate_hz_);
1470 processing_config.reverse_input_stream().set_num_channels(
1471 frame->num_channels_);
1472 processing_config.reverse_output_stream().set_sample_rate_hz(
1473 frame->sample_rate_hz_);
1474 processing_config.reverse_output_stream().set_num_channels(
1475 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001476
peahdf3efa82015-11-28 12:35:15 -08001477 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001478 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001479 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001480 return kBadDataLengthError;
1481 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001482
aleloi868f32f2017-05-23 07:20:05 -07001483 if (aec_dump_) {
1484 aec_dump_->WriteRenderStreamMessage(*frame);
1485 }
1486
peahdf3efa82015-11-28 12:35:15 -08001487 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001488 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001489 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001490 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1491 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001492 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001493}
niklase@google.com470e71d2011-07-07 08:21:25 +00001494
peahde65ddc2016-09-16 15:02:15 -07001495int AudioProcessingImpl::ProcessRenderStreamLocked() {
1496 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001497
1498 QueueNonbandedRenderAudio(render_buffer);
1499
Alex Loiko73ec0192018-05-15 10:52:28 +02001500 HandleRenderRuntimeSettings();
1501
Alex Loiko5825aa62017-12-18 16:02:40 +01001502 if (private_submodules_->render_pre_processor) {
1503 private_submodules_->render_pre_processor->Process(render_buffer);
1504 }
1505
peah2ace3f92016-09-10 04:42:27 -07001506 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001507 SampleRateSupportsMultiBand(
1508 formats_.render_processing_format.sample_rate_hz())) {
1509 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001510 }
1511
peah1bcfce52016-08-26 07:16:04 -07001512#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001513 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001514 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001515 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001516 }
peah1bcfce52016-08-26 07:16:04 -07001517#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001518
peahce4d9152017-05-19 01:28:05 -07001519 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1520 QueueBandedRenderAudio(render_buffer);
1521 }
1522
peahe0eae3c2016-12-14 01:16:23 -08001523 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001524 if (capture_nonlocked_.echo_controller_enabled) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001525 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001526 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001527
peah2ace3f92016-09-10 04:42:27 -07001528 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001529 SampleRateSupportsMultiBand(
1530 formats_.render_processing_format.sample_rate_hz())) {
1531 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001532 }
1533
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001534 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001535}
1536
1537int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001538 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001539 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001540 capture_.was_stream_delay_set = true;
1541 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001542
niklase@google.com470e71d2011-07-07 08:21:25 +00001543 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001544 delay = 0;
1545 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001546 }
1547
1548 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1549 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001550 delay = 500;
1551 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001552 }
1553
peahdf3efa82015-11-28 12:35:15 -08001554 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001555 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001556}
1557
1558int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001559 // Used as callback from submodules, hence locking is not allowed.
1560 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001561}
1562
1563bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001564 // Used as callback from submodules, hence locking is not allowed.
1565 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001566}
1567
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001568void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001569 rtc::CritScope cs(&crit_capture_);
1570 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001571}
1572
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001573void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001574 rtc::CritScope cs(&crit_capture_);
1575 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001576}
1577
1578int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001579 rtc::CritScope cs(&crit_capture_);
1580 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001581}
1582
aleloi868f32f2017-05-23 07:20:05 -07001583void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1584 RTC_DCHECK(aec_dump);
1585 rtc::CritScope cs_render(&crit_render_);
1586 rtc::CritScope cs_capture(&crit_capture_);
1587
1588 // The previously attached AecDump will be destroyed with the
1589 // 'aec_dump' parameter, which is after locks are released.
1590 aec_dump_.swap(aec_dump);
1591 WriteAecDumpConfigMessage(true);
Alex Loiko1aec5942018-05-15 13:13:22 +02001592 aec_dump_->WriteInitMessage(formats_.api_format);
aleloi868f32f2017-05-23 07:20:05 -07001593}
1594
1595void AudioProcessingImpl::DetachAecDump() {
1596 // The d-tor of a task-queue based AecDump blocks until all pending
1597 // tasks are done. This construction avoids blocking while holding
1598 // the render and capture locks.
1599 std::unique_ptr<AecDump> aec_dump = nullptr;
1600 {
1601 rtc::CritScope cs_render(&crit_render_);
1602 rtc::CritScope cs_capture(&crit_capture_);
1603 aec_dump = std::move(aec_dump_);
1604 }
1605}
1606
Sam Zackrisson4d364492018-03-02 16:03:21 +01001607void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1608 std::unique_ptr<AudioGenerator> audio_generator) {
1609 // TODO(bugs.webrtc.org/8882) Stub.
1610 // Reset internal audio generator with audio_generator.
1611}
1612
1613void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1614 // TODO(bugs.webrtc.org/8882) Stub.
1615 // Delete audio generator, if one is attached.
1616}
1617
ivoc4e477a12017-01-15 08:29:46 -08001618AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1619 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1620 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1621 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1622 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1623}
1624
1625AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1626 const AudioProcessingStatistics& other) = default;
1627
1628AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1629 default;
1630
ivoc3e9a5372016-10-28 07:55:33 -07001631// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1632AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1633 const {
1634 return AudioProcessingStatistics();
1635}
1636
Ivo Creusenae026092017-11-20 13:07:16 +01001637// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001638AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001639 bool has_remote_tracks) const {
1640 return AudioProcessingStats();
1641}
1642
ivoc3e9a5372016-10-28 07:55:33 -07001643AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1644 const {
1645 AudioProcessingStatistics stats;
1646 EchoCancellation::Metrics metrics;
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001647 if (capture_nonlocked_.echo_controller_enabled) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001648 rtc::CritScope cs_capture(&crit_capture_);
1649 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1650 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1651 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1652 // Instant value will also be used for min, max and average.
1653 stats.echo_return_loss.Set(erl, erl, erl, erl);
1654 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1655 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1656 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001657 stats.a_nlp.Set(metrics.a_nlp);
1658 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1659 stats.echo_return_loss.Set(metrics.echo_return_loss);
1660 stats.echo_return_loss_enhancement.Set(
1661 metrics.echo_return_loss_enhancement);
1662 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1663 }
ivoc9c192b22017-03-16 04:22:14 -07001664 {
1665 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001666 RTC_DCHECK(private_submodules_->echo_detector);
1667 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1668 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001669 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001670 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001671 }
ivoc3e9a5372016-10-28 07:55:33 -07001672 public_submodules_->echo_cancellation->GetDelayMetrics(
1673 &stats.delay_median, &stats.delay_standard_deviation,
1674 &stats.fraction_poor_delays);
1675 return stats;
1676}
1677
Ivo Creusen56d46092017-11-24 17:29:59 +01001678AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001679 bool has_remote_tracks) const {
1680 AudioProcessingStats stats;
1681 if (has_remote_tracks) {
1682 EchoCancellation::Metrics metrics;
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001683 if (capture_nonlocked_.echo_controller_enabled) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001684 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001685 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1686 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001687 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001688 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001689 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001690 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1691 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001692 if (metrics.divergent_filter_fraction != -1.0f) {
1693 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001694 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001695 }
1696 if (metrics.echo_return_loss.instant != -100) {
1697 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001698 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001699 }
1700 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001701 stats.echo_return_loss_enhancement = absl::optional<double>(
1702 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001703 }
1704 }
1705 if (config_.residual_echo_detector.enabled) {
1706 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001707 RTC_DCHECK(private_submodules_->echo_detector);
1708 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1709 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001710 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001711 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001712 }
1713 int delay_median, delay_std;
1714 float fraction_poor_delays;
1715 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1716 &delay_median, &delay_std, &fraction_poor_delays) ==
1717 Error::kNoError) {
1718 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001719 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001720 }
1721 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001722 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001723 }
1724 }
1725 }
1726 return stats;
1727}
1728
niklase@google.com470e71d2011-07-07 08:21:25 +00001729EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001730 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001731}
1732
1733EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001734 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001735}
1736
1737GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001738 if (constants_.use_experimental_agc) {
1739 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001740 }
peahbfa97112016-03-10 21:09:04 -08001741 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
1744HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001745 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001746}
1747
1748LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001749 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001750}
1751
1752NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001753 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001754}
1755
1756VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001757 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001758}
1759
peah8271d042016-11-22 07:24:52 -08001760void AudioProcessingImpl::MutateConfig(
1761 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1762 rtc::CritScope cs_render(&crit_render_);
1763 rtc::CritScope cs_capture(&crit_capture_);
1764 mutator(&config_);
1765 ApplyConfig(config_);
1766}
1767
1768AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1769 rtc::CritScope cs_render(&crit_render_);
1770 rtc::CritScope cs_capture(&crit_capture_);
1771 return config_;
1772}
1773
peah2ace3f92016-09-10 04:42:27 -07001774bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1775 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001776 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001777 public_submodules_->echo_cancellation->is_enabled(),
1778 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001779 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001780 public_submodules_->noise_suppression->is_enabled(),
1781 capture_nonlocked_.intelligibility_enabled,
peah2ace3f92016-09-10 04:42:27 -07001782 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001783 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001784 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001785 public_submodules_->voice_detection->is_enabled(),
1786 public_submodules_->level_estimator->is_enabled(),
1787 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001788}
1789
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001790
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001791void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001792 if (capture_.transient_suppressor_enabled) {
1793 if (!public_submodules_->transient_suppressor.get()) {
1794 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001795 }
peahdf3efa82015-11-28 12:35:15 -08001796 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001797 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1798 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001799 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001800}
1801
ekmeyerson60d9b332015-08-14 10:35:55 -07001802void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001803#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001804 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001805 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001806 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001807 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001808 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001809 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001810 }
peah1bcfce52016-08-26 07:16:04 -07001811#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001812}
1813
peah8271d042016-11-22 07:24:52 -08001814void AudioProcessingImpl::InitializeLowCutFilter() {
1815 if (config_.high_pass_filter.enabled) {
1816 private_submodules_->low_cut_filter.reset(
1817 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1818 } else {
1819 private_submodules_->low_cut_filter.reset();
1820 }
1821}
alessiob3ec96df2017-05-22 06:57:06 -07001822
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001823void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001824 if (echo_control_factory_) {
1825 private_submodules_->echo_controller =
1826 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001827 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001828 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001829 }
1830}
peah8271d042016-11-22 07:24:52 -08001831
alessiob3ec96df2017-05-22 06:57:06 -07001832void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001833 if (config_.gain_controller2.enabled) {
1834 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001835 }
1836}
1837
Alex Loikob5c9a792018-04-16 16:31:22 +02001838void AudioProcessingImpl::InitializePreAmplifier() {
1839 if (config_.pre_amplifier.enabled) {
1840 private_submodules_->pre_amplifier.reset(
1841 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1842 } else {
1843 private_submodules_->pre_amplifier.reset();
1844 }
1845}
1846
ivoc9f4a4a02016-10-28 05:39:16 -07001847void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001848 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001849 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001850 proc_sample_rate_hz(), 1,
1851 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001852}
1853
Sam Zackrisson0beac582017-09-25 12:04:02 +02001854void AudioProcessingImpl::InitializePostProcessor() {
1855 if (private_submodules_->capture_post_processor) {
1856 private_submodules_->capture_post_processor->Initialize(
1857 proc_sample_rate_hz(), num_proc_channels());
1858 }
1859}
1860
Alex Loiko5825aa62017-12-18 16:02:40 +01001861void AudioProcessingImpl::InitializePreProcessor() {
1862 if (private_submodules_->render_pre_processor) {
1863 private_submodules_->render_pre_processor->Initialize(
1864 formats_.render_processing_format.sample_rate_hz(),
1865 formats_.render_processing_format.num_channels());
1866 }
1867}
1868
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001869void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001870 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001871
1872 if (echo_cancellation()->is_enabled()) {
Sam Zackrisson771b50c2018-07-23 15:21:52 +02001873 // Activate delay_jumps_ counters if we know AEC2 is running.
1874 // If a stream has echo we know that echo cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001875 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001876 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001877 capture_.stream_delay_jumps = 0;
1878 }
1879 if (capture_.aec_system_delay_jumps == -1 &&
1880 echo_cancellation()->stream_has_echo()) {
1881 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001882 }
1883
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001884 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001885 const int diff_stream_delay_ms =
1886 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1887 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1888 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001889 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1890 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001891 if (capture_.stream_delay_jumps == -1) {
1892 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001893 }
peahdf3efa82015-11-28 12:35:15 -08001894 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001895 }
peahdf3efa82015-11-28 12:35:15 -08001896 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001897
1898 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001899 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001900 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001901 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001902 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001903 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1904 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001905 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001906 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001907 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001908 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001909 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1910 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1911 100);
peahdf3efa82015-11-28 12:35:15 -08001912 if (capture_.aec_system_delay_jumps == -1) {
1913 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001914 }
peahdf3efa82015-11-28 12:35:15 -08001915 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001916 }
peahdf3efa82015-11-28 12:35:15 -08001917 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001918 }
1919}
1920
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001921void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001922 // Run in a single-threaded manner.
1923 rtc::CritScope cs_render(&crit_render_);
1924 rtc::CritScope cs_capture(&crit_capture_);
1925
1926 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001927 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001928 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001929 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001930 }
peahdf3efa82015-11-28 12:35:15 -08001931 capture_.stream_delay_jumps = -1;
1932 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001933
peahdf3efa82015-11-28 12:35:15 -08001934 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001935 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1936 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001937 }
peahdf3efa82015-11-28 12:35:15 -08001938 capture_.aec_system_delay_jumps = -1;
1939 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001940}
1941
aleloi868f32f2017-05-23 07:20:05 -07001942void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1943 if (!aec_dump_) {
1944 return;
1945 }
1946 std::string experiments_description =
1947 public_submodules_->echo_cancellation->GetExperimentsDescription();
1948 // TODO(peah): Add semicolon-separated concatenations of experiment
1949 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001950 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1951 experiments_description += "AgcClippingLevelExperiment;";
1952 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001953 if (capture_nonlocked_.echo_controller_enabled) {
1954 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001955 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001956 if (config_.gain_controller2.enabled) {
1957 experiments_description += "GainController2;";
1958 }
aleloi868f32f2017-05-23 07:20:05 -07001959
1960 InternalAPMConfig apm_config;
1961
1962 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1963 apm_config.aec_delay_agnostic_enabled =
1964 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1965 apm_config.aec_drift_compensation_enabled =
1966 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1967 apm_config.aec_extended_filter_enabled =
1968 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1969 apm_config.aec_suppression_level = static_cast<int>(
1970 public_submodules_->echo_cancellation->suppression_level());
1971
1972 apm_config.aecm_enabled =
1973 public_submodules_->echo_control_mobile->is_enabled();
1974 apm_config.aecm_comfort_noise_enabled =
1975 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1976 apm_config.aecm_routing_mode =
1977 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1978
1979 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1980 apm_config.agc_mode =
1981 static_cast<int>(public_submodules_->gain_control->mode());
1982 apm_config.agc_limiter_enabled =
1983 public_submodules_->gain_control->is_limiter_enabled();
1984 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1985
1986 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1987
1988 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1989 apm_config.ns_level =
1990 static_cast<int>(public_submodules_->noise_suppression->level());
1991
1992 apm_config.transient_suppression_enabled =
1993 capture_.transient_suppressor_enabled;
1994 apm_config.intelligibility_enhancer_enabled =
1995 capture_nonlocked_.intelligibility_enabled;
1996 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001997 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1998 apm_config.pre_amplifier_fixed_gain_factor =
1999 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002000
2001 if (!forced && apm_config == apm_config_for_aec_dump_) {
2002 return;
2003 }
2004 aec_dump_->WriteConfig(apm_config);
2005 apm_config_for_aec_dump_ = apm_config;
2006}
2007
2008void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2009 const float* const* src) {
2010 RTC_DCHECK(aec_dump_);
2011 WriteAecDumpConfigMessage(false);
2012
2013 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2014 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2015 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002016 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002017 RecordAudioProcessingState();
2018}
2019
2020void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2021 const AudioFrame& capture_frame) {
2022 RTC_DCHECK(aec_dump_);
2023 WriteAecDumpConfigMessage(false);
2024
2025 aec_dump_->AddCaptureStreamInput(capture_frame);
2026 RecordAudioProcessingState();
2027}
2028
2029void AudioProcessingImpl::RecordProcessedCaptureStream(
2030 const float* const* processed_capture_stream) {
2031 RTC_DCHECK(aec_dump_);
2032
2033 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2034 const size_t num_channels =
2035 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002036 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2037 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002038 aec_dump_->WriteCaptureStreamMessage();
2039}
2040
2041void AudioProcessingImpl::RecordProcessedCaptureStream(
2042 const AudioFrame& processed_capture_frame) {
2043 RTC_DCHECK(aec_dump_);
2044
2045 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2046 aec_dump_->WriteCaptureStreamMessage();
2047}
2048
2049void AudioProcessingImpl::RecordAudioProcessingState() {
2050 RTC_DCHECK(aec_dump_);
2051 AecDump::AudioProcessingState audio_proc_state;
2052 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2053 audio_proc_state.drift =
2054 public_submodules_->echo_cancellation->stream_drift_samples();
2055 audio_proc_state.level = gain_control()->stream_analog_level();
2056 audio_proc_state.keypress = capture_.key_pressed;
2057 aec_dump_->AddAudioProcessingState(audio_proc_state);
2058}
2059
kwiberg83ffe452016-08-29 14:46:07 -07002060AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002061 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002062 : aec_system_delay_jumps(-1),
2063 delay_offset_ms(0),
2064 was_stream_delay_set(false),
2065 last_stream_delay_ms(0),
2066 last_aec_system_delay_ms(0),
2067 stream_delay_jumps(-1),
2068 output_will_be_muted(false),
2069 key_pressed(false),
2070 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002071 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002072 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002073 echo_path_gain_change(false),
2074 prev_analog_mic_level(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002075
2076AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2077
2078AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2079
2080AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2081
niklase@google.com470e71d2011-07-07 08:21:25 +00002082} // namespace webrtc