blob: 7e5955a98f857f4e3ab17bc34367e58a8ff5272a [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 Zackrisson2a959d92018-07-23 14:48:07 +0000388 capture_nonlocked_.echo_controller_enabled =
389 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200390
peahb624d8c2016-03-05 03:01:14 -0800391 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700392 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800393 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700394 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800395 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200396 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800397 public_submodules_->level_estimator.reset(
398 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800399 public_submodules_->noise_suppression.reset(
400 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800401 public_submodules_->voice_detection.reset(
402 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800403 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800404 new GainControlForExperimentalAgc(
405 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100406
407 // If no echo detector is injected, use the ResidualEchoDetector.
408 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200409 private_submodules_->echo_detector =
410 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100411 }
peahca4cac72016-06-29 15:26:12 -0700412
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200413 // TODO(alessiob): Move the injected gain controller once injection is
414 // implemented.
415 private_submodules_->gain_controller2.reset(new GainController2());
416
Mirko Bonadei675513b2017-11-09 11:09:25 +0100417 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100418 << !!private_submodules_->capture_post_processor
419 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100420 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800421 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000422
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000423 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000424}
425
426AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800427 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800428 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800429 private_submodules_->agc_manager.reset();
430 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800431 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000432}
433
niklase@google.com470e71d2011-07-07 08:21:25 +0000434int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800435 // Run in a single-threaded manner during initialization.
436 rtc::CritScope cs_render(&crit_render_);
437 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000438 return InitializeLocked();
439}
440
peahde65ddc2016-09-16 15:02:15 -0700441int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
442 int capture_output_sample_rate_hz,
443 int render_input_sample_rate_hz,
444 ChannelLayout capture_input_layout,
445 ChannelLayout capture_output_layout,
446 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700447 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700448 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
449 LayoutHasKeyboard(capture_input_layout)},
450 {capture_output_sample_rate_hz,
451 ChannelsFromLayout(capture_output_layout),
452 LayoutHasKeyboard(capture_output_layout)},
453 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
454 LayoutHasKeyboard(render_input_layout)},
455 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
456 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700457
458 return Initialize(processing_config);
459}
460
461int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800462 // Run in a single-threaded manner during initialization.
463 rtc::CritScope cs_render(&crit_render_);
464 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700465 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000466}
467
peahdf3efa82015-11-28 12:35:15 -0800468int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800469 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700470 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800471}
472
peahdf3efa82015-11-28 12:35:15 -0800473int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700474 const ProcessingConfig& processing_config,
475 bool force_initialization) {
476 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800477}
478
peah192164e2015-11-17 02:16:45 -0800479// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800480// their current values (needs to be called while holding the crit_render_lock).
481int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700482 const ProcessingConfig& processing_config,
483 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800484 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700485 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800486 return kNoError;
487 }
peahdf3efa82015-11-28 12:35:15 -0800488
489 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800490 return InitializeLocked(processing_config);
491}
492
niklase@google.com470e71d2011-07-07 08:21:25 +0000493int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200494 UpdateActiveSubmoduleStates();
495
peahde65ddc2016-09-16 15:02:15 -0700496 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800497 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700498 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800499 : formats_.api_format.reverse_output_stream().num_frames();
500 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
501 render_.render_audio.reset(new AudioBuffer(
502 formats_.api_format.reverse_input_stream().num_frames(),
503 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700504 formats_.render_processing_format.num_frames(),
505 formats_.render_processing_format.num_channels(),
506 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700507 if (formats_.api_format.reverse_input_stream() !=
508 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800509 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800510 formats_.api_format.reverse_input_stream().num_channels(),
511 formats_.api_format.reverse_input_stream().num_frames(),
512 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800513 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700514 } else {
peahdf3efa82015-11-28 12:35:15 -0800515 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700516 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700517 } else {
peahdf3efa82015-11-28 12:35:15 -0800518 render_.render_audio.reset(nullptr);
519 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700520 }
peahce4d9152017-05-19 01:28:05 -0700521
peahdf3efa82015-11-28 12:35:15 -0800522 capture_.capture_audio.reset(
523 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
524 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700525 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200526 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800527 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000528
peahde65ddc2016-09-16 15:02:15 -0700529 public_submodules_->echo_cancellation->Initialize(
530 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
531 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700532 AllocateRenderQueue();
533
ivoc3e9a5372016-10-28 07:55:33 -0700534 int success = public_submodules_->echo_cancellation->enable_metrics(true);
535 RTC_DCHECK_EQ(0, success);
536 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
537 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700538 public_submodules_->echo_control_mobile->Initialize(
539 proc_split_sample_rate_hz(), num_reverse_channels(),
540 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700541
542 public_submodules_->gain_control->Initialize(num_proc_channels(),
543 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700544 if (constants_.use_experimental_agc) {
545 if (!private_submodules_->agc_manager.get()) {
546 private_submodules_->agc_manager.reset(new AgcManagerDirect(
547 public_submodules_->gain_control.get(),
548 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200549 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
550 constants_.use_experimental_agc_agc2_level_estimation,
551 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700552 }
553 private_submodules_->agc_manager->Initialize();
554 private_submodules_->agc_manager->SetCaptureMuted(
555 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700556 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700557 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200558 InitializeTransient();
peah1bcfce52016-08-26 07:16:04 -0700559#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700560 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700561#endif
peah8271d042016-11-22 07:24:52 -0800562 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700563 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
564 proc_sample_rate_hz());
565 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
566 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700567 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200568 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700569 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200570 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100571 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800572
aleloi868f32f2017-05-23 07:20:05 -0700573 if (aec_dump_) {
Alex Loiko1aec5942018-05-15 13:13:22 +0200574 aec_dump_->WriteInitMessage(formats_.api_format);
aleloi868f32f2017-05-23 07:20:05 -0700575 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000576 return kNoError;
577}
578
Michael Graczyk86c6d332015-07-23 11:41:39 -0700579int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200580 UpdateActiveSubmoduleStates();
581
Michael Graczyk86c6d332015-07-23 11:41:39 -0700582 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700583 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
584 return kBadSampleRateError;
585 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000586 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700587
Peter Kasting69558702016-01-12 16:26:35 -0800588 const size_t num_in_channels = config.input_stream().num_channels();
589 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590
591 // Need at least one input channel.
592 // Need either one output channel or as many outputs as there are inputs.
593 if (num_in_channels == 0 ||
594 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700595 return kBadNumberChannelsError;
596 }
597
peahdf3efa82015-11-28 12:35:15 -0800598 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000599
peahde65ddc2016-09-16 15:02:15 -0700600 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700601 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700602 formats_.api_format.output_stream().sample_rate_hz()),
603 submodule_states_.CaptureMultiBandSubModulesActive() ||
604 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000605
peahde65ddc2016-09-16 15:02:15 -0700606 capture_nonlocked_.capture_processing_format =
607 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700608
peah2ce640f2017-04-07 03:57:48 -0700609 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200610 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700611 render_processing_rate = FindNativeProcessRateToUse(
612 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
613 formats_.api_format.reverse_output_stream().sample_rate_hz()),
614 submodule_states_.CaptureMultiBandSubModulesActive() ||
615 submodule_states_.RenderMultiBandSubModulesActive());
616 } else {
617 render_processing_rate = capture_processing_rate;
618 }
619
aluebseb3603b2016-04-20 15:27:58 -0700620 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
621 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700622 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200623 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700624 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
625 ? kSampleRate32kHz
626 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700627 }
peah2ce640f2017-04-07 03:57:48 -0700628
peahde65ddc2016-09-16 15:02:15 -0700629 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700630 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700631 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
632 kSampleRate8kHz) {
633 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000634 } else {
peahde65ddc2016-09-16 15:02:15 -0700635 render_processing_rate =
636 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000637 }
638
peahde65ddc2016-09-16 15:02:15 -0700639 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000640 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700641 if (submodule_states_.RenderMultiBandSubModulesActive()) {
642 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
643 } else {
644 formats_.render_processing_format = StreamConfig(
645 formats_.api_format.reverse_input_stream().sample_rate_hz(),
646 formats_.api_format.reverse_input_stream().num_channels());
647 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000648
peahde65ddc2016-09-16 15:02:15 -0700649 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
650 kSampleRate32kHz ||
651 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
652 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800653 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000654 } else {
peahdf3efa82015-11-28 12:35:15 -0800655 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700656 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000657 }
658
659 return InitializeLocked();
660}
661
peah88ac8532016-09-12 16:47:25 -0700662void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700663 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700664
peah88ac8532016-09-12 16:47:25 -0700665 // Run in a single-threaded manner when applying the settings.
666 rtc::CritScope cs_render(&crit_render_);
667 rtc::CritScope cs_capture(&crit_capture_);
668
peah8271d042016-11-22 07:24:52 -0800669 InitializeLowCutFilter();
670
Mirko Bonadei675513b2017-11-09 11:09:25 +0100671 RTC_LOG(LS_INFO) << "Highpass filter activated: "
672 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800673
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100674 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700675 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100676 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
677 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100678 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100679 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700680 config_.gain_controller2 = AudioProcessing::Config::GainController2();
681 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200682 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200683 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200684 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100685 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
686 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200687 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
688 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700689}
690
691void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800692 // Run in a single-threaded manner when setting the extra options.
693 rtc::CritScope cs_render(&crit_render_);
694 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000695
peahb624d8c2016-03-05 03:01:14 -0800696 public_submodules_->echo_cancellation->SetExtraOptions(config);
697
peahdf3efa82015-11-28 12:35:15 -0800698 if (capture_.transient_suppressor_enabled !=
699 config.Get<ExperimentalNs>().enabled) {
700 capture_.transient_suppressor_enabled =
701 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000702 InitializeTransient();
703 }
aluebs2a346882016-01-11 18:04:30 -0800704
peah1bcfce52016-08-26 07:16:04 -0700705#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700706 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700707 config.Get<Intelligibility>().enabled) {
708 capture_nonlocked_.intelligibility_enabled =
709 config.Get<Intelligibility>().enabled;
710 InitializeIntelligibility();
711 }
peah1bcfce52016-08-26 07:16:04 -0700712#endif
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000713}
714
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000715int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800716 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700717 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000718}
719
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000720int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800721 // Used as callback from submodules, hence locking is not allowed.
722 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000723}
724
Peter Kasting69558702016-01-12 16:26:35 -0800725size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800726 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700727 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000728}
729
Peter Kasting69558702016-01-12 16:26:35 -0800730size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800731 // Used as callback from submodules, hence locking is not allowed.
732 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000733}
734
Peter Kasting69558702016-01-12 16:26:35 -0800735size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800736 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200737 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800738}
739
Peter Kasting69558702016-01-12 16:26:35 -0800740size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800741 // Used as callback from submodules, hence locking is not allowed.
742 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000743}
744
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000745void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800746 rtc::CritScope cs(&crit_capture_);
747 capture_.output_will_be_muted = muted;
748 if (private_submodules_->agc_manager.get()) {
749 private_submodules_->agc_manager->SetCaptureMuted(
750 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000751 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000752}
753
Alessio Bazzicac054e782018-04-16 12:10:09 +0200754void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200755 switch (setting.type()) {
756 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
757 render_runtime_settings_enqueuer_.Enqueue(setting);
758 return;
759 case RuntimeSetting::Type::kNotSpecified:
760 RTC_NOTREACHED();
761 return;
762 case RuntimeSetting::Type::kCapturePreGain:
763 capture_runtime_settings_enqueuer_.Enqueue(setting);
764 return;
765 }
766 // The language allows the enum to have a non-enumerator
767 // value. Check that this doesn't happen.
768 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200769}
770
771AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
772 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200773 : runtime_settings_(*runtime_settings) {
774 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200775}
776
777AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
778 default;
779
780void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
781 RuntimeSetting setting) {
782 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200783 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200784 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200785 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200786 RTC_LOG(LS_ERROR)
787 << "The runtime settings queue is full. Oldest setting discarded.";
788 }
789 if (remaining_attempts == 0)
790 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
791}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000792
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000793int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700794 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000795 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000796 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000797 int output_sample_rate_hz,
798 ChannelLayout output_layout,
799 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800800 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800801 StreamConfig input_stream;
802 StreamConfig output_stream;
803 {
804 // Access the formats_.api_format.input_stream beneath the capture lock.
805 // The lock must be released as it is later required in the call
806 // to ProcessStream(,,,);
807 rtc::CritScope cs(&crit_capture_);
808 input_stream = formats_.api_format.input_stream();
809 output_stream = formats_.api_format.output_stream();
810 }
811
Michael Graczyk86c6d332015-07-23 11:41:39 -0700812 input_stream.set_sample_rate_hz(input_sample_rate_hz);
813 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
814 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700815 output_stream.set_sample_rate_hz(output_sample_rate_hz);
816 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
817 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
818
819 if (samples_per_channel != input_stream.num_frames()) {
820 return kBadDataLengthError;
821 }
822 return ProcessStream(src, input_stream, output_stream, dest);
823}
824
825int AudioProcessingImpl::ProcessStream(const float* const* src,
826 const StreamConfig& input_config,
827 const StreamConfig& output_config,
828 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800829 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800830 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700831 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800832 {
833 // Acquire the capture lock in order to safely call the function
834 // that retrieves the render side data. This function accesses apm
835 // getters that need the capture lock held when being called.
836 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700837 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800838
839 if (!src || !dest) {
840 return kNullPointerError;
841 }
842
843 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700844 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000845 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000846
Michael Graczyk86c6d332015-07-23 11:41:39 -0700847 processing_config.input_stream() = input_config;
848 processing_config.output_stream() = output_config;
849
peahdf3efa82015-11-28 12:35:15 -0800850 {
851 // Do conditional reinitialization.
852 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700853 RETURN_ON_ERR(
854 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800855 }
856 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700857 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
858 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000859
aleloi868f32f2017-05-23 07:20:05 -0700860 if (aec_dump_) {
861 RecordUnprocessedCaptureStream(src);
862 }
863
peahdf3efa82015-11-28 12:35:15 -0800864 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700865 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800866 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000867
aleloi868f32f2017-05-23 07:20:05 -0700868 if (aec_dump_) {
869 RecordProcessedCaptureStream(dest);
870 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000871 return kNoError;
872}
873
Alex Loiko73ec0192018-05-15 10:52:28 +0200874void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200875 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200876 while (capture_runtime_settings_.Remove(&setting)) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200877 switch (setting.type()) {
878 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200879 if (config_.pre_amplifier.enabled) {
880 float value;
881 setting.GetFloat(&value);
882 private_submodules_->pre_amplifier->SetGainFactor(value);
883 }
884 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200885 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200886 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
887 RTC_NOTREACHED();
888 break;
889 case RuntimeSetting::Type::kNotSpecified:
890 RTC_NOTREACHED();
891 break;
892 }
893 }
894}
895
896void AudioProcessingImpl::HandleRenderRuntimeSettings() {
897 RuntimeSetting setting;
898 while (render_runtime_settings_.Remove(&setting)) {
899 switch (setting.type()) {
900 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
901 if (private_submodules_->render_pre_processor) {
902 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
903 }
904 break;
905 case RuntimeSetting::Type::kCapturePreGain:
906 RTC_NOTREACHED();
907 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200908 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200909 RTC_NOTREACHED();
910 break;
911 }
912 }
913}
914
peah9e6a2902017-05-15 07:19:21 -0700915void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700916 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
917 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700918 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700919
kwibergaf476c72016-11-28 15:21:39 -0800920 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700921
922 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700923 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700924 // The data queue is full and needs to be emptied.
925 EmptyQueuedRenderAudio();
926
927 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700928 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700929 RTC_DCHECK(result);
930 }
931
932 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
933 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700934 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700935
936 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700937 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700938 // The data queue is full and needs to be emptied.
939 EmptyQueuedRenderAudio();
940
941 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700942 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700943 RTC_DCHECK(result);
944 }
peah701d6282016-10-25 05:42:20 -0700945
946 if (!constants_.use_experimental_agc) {
947 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
948 // Insert the samples into the queue.
949 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
950 // The data queue is full and needs to be emptied.
951 EmptyQueuedRenderAudio();
952
953 // Retry the insert (should always work).
954 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
955 RTC_DCHECK(result);
956 }
957 }
peah9e6a2902017-05-15 07:19:21 -0700958}
ivoc9f4a4a02016-10-28 05:39:16 -0700959
peah9e6a2902017-05-15 07:19:21 -0700960void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700961 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
962
963 // Insert the samples into the queue.
964 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
965 // The data queue is full and needs to be emptied.
966 EmptyQueuedRenderAudio();
967
968 // Retry the insert (should always work).
969 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
970 RTC_DCHECK(result);
971 }
peah764e3642016-10-22 05:04:30 -0700972}
973
974void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700975 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700976 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700977 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700978 EchoCancellationImpl::NumCancellersRequired(
979 num_output_channels(), num_reverse_channels()));
980
peah701d6282016-10-25 05:42:20 -0700981 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700982 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700983 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700984 EchoControlMobileImpl::NumCancellersRequired(
985 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700986
peah701d6282016-10-25 05:42:20 -0700987 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700988 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700989
ivoc9f4a4a02016-10-28 05:39:16 -0700990 const size_t new_red_render_queue_element_max_size =
991 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
992
peaha0624602016-10-25 04:45:24 -0700993 // Reallocate the queues if the queue item sizes are too small to fit the
994 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700995 if (aec_render_queue_element_max_size_ <
996 new_aec_render_queue_element_max_size) {
997 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700998
peaha0624602016-10-25 04:45:24 -0700999 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001000 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001001
peah701d6282016-10-25 05:42:20 -07001002 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001003 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1004 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001005 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001006 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001007
peah701d6282016-10-25 05:42:20 -07001008 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1009 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001010 } else {
peah701d6282016-10-25 05:42:20 -07001011 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001012 }
1013
peah701d6282016-10-25 05:42:20 -07001014 if (aecm_render_queue_element_max_size_ <
1015 new_aecm_render_queue_element_max_size) {
1016 aecm_render_queue_element_max_size_ =
1017 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001018
1019 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001020 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001021
peah701d6282016-10-25 05:42:20 -07001022 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001023 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1024 kMaxNumFramesToBuffer, template_queue_element,
1025 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001026 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001027
peah701d6282016-10-25 05:42:20 -07001028 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1029 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001030 } else {
peah701d6282016-10-25 05:42:20 -07001031 aecm_render_signal_queue_->Clear();
1032 }
1033
1034 if (agc_render_queue_element_max_size_ <
1035 new_agc_render_queue_element_max_size) {
1036 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1037
1038 std::vector<int16_t> template_queue_element(
1039 agc_render_queue_element_max_size_);
1040
1041 agc_render_signal_queue_.reset(
1042 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1043 kMaxNumFramesToBuffer, template_queue_element,
1044 RenderQueueItemVerifier<int16_t>(
1045 agc_render_queue_element_max_size_)));
1046
1047 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1048 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1049 } else {
1050 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001051 }
ivoc9f4a4a02016-10-28 05:39:16 -07001052
1053 if (red_render_queue_element_max_size_ <
1054 new_red_render_queue_element_max_size) {
1055 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1056
1057 std::vector<float> template_queue_element(
1058 red_render_queue_element_max_size_);
1059
1060 red_render_signal_queue_.reset(
1061 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1062 kMaxNumFramesToBuffer, template_queue_element,
1063 RenderQueueItemVerifier<float>(
1064 red_render_queue_element_max_size_)));
1065
1066 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1067 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1068 } else {
1069 red_render_signal_queue_->Clear();
1070 }
peah764e3642016-10-22 05:04:30 -07001071}
1072
1073void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1074 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001075 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001076 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001077 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001078 }
1079
peah701d6282016-10-25 05:42:20 -07001080 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001081 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001082 aecm_capture_queue_buffer_);
1083 }
1084
1085 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1086 public_submodules_->gain_control->ProcessRenderAudio(
1087 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001088 }
ivoc9f4a4a02016-10-28 05:39:16 -07001089
1090 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001091 RTC_DCHECK(private_submodules_->echo_detector);
1092 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001093 red_capture_queue_buffer_);
1094 }
peah764e3642016-10-22 05:04:30 -07001095}
1096
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001097int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001098 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001099 {
1100 // Acquire the capture lock in order to safely call the function
1101 // that retrieves the render side data. This function accesses apm
1102 // getters that need the capture lock held when being called.
1103 // The lock needs to be released as
1104 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1105 // as well.
1106 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001107 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001108 }
peahfa6228e2015-11-16 16:27:42 -08001109
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001110 if (!frame) {
1111 return kNullPointerError;
1112 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001113 // Must be a native rate.
1114 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1115 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001116 frame->sample_rate_hz_ != kSampleRate32kHz &&
1117 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001118 return kBadSampleRateError;
1119 }
peah192164e2015-11-17 02:16:45 -08001120
peahdf3efa82015-11-28 12:35:15 -08001121 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001122 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001123 {
1124 // Aquire lock for the access of api_format.
1125 // The lock is released immediately due to the conditional
1126 // reinitialization.
1127 rtc::CritScope cs_capture(&crit_capture_);
1128 // TODO(ajm): The input and output rates and channels are currently
1129 // constrained to be identical in the int16 interface.
1130 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001131
1132 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001133 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001134 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1135 processing_config.input_stream().set_num_channels(frame->num_channels_);
1136 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1137 processing_config.output_stream().set_num_channels(frame->num_channels_);
1138
peahdf3efa82015-11-28 12:35:15 -08001139 {
1140 // Do conditional reinitialization.
1141 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001142 RETURN_ON_ERR(
1143 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001144 }
1145 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001146 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001147 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001148 return kBadDataLengthError;
1149 }
1150
aleloi868f32f2017-05-23 07:20:05 -07001151 if (aec_dump_) {
1152 RecordUnprocessedCaptureStream(*frame);
1153 }
1154
peahdf3efa82015-11-28 12:35:15 -08001155 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001156 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001157 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001158 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1159 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001160
aleloi868f32f2017-05-23 07:20:05 -07001161 if (aec_dump_) {
1162 RecordProcessedCaptureStream(*frame);
1163 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001164
1165 return kNoError;
1166}
1167
peahde65ddc2016-09-16 15:02:15 -07001168int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001169 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001170
peahb58a1582016-03-15 09:34:24 -07001171 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001172 // TODO(peah): Simplify once the public API Enable functions for these
1173 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001174 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1175 public_submodules_->echo_control_mobile->is_enabled()));
1176
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001177 MaybeUpdateHistograms();
1178
peahde65ddc2016-09-16 15:02:15 -07001179 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001180
Alex Loikob5c9a792018-04-16 16:31:22 +02001181 if (private_submodules_->pre_amplifier) {
1182 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1183 capture_buffer->channels_f(), capture_buffer->num_channels(),
1184 capture_buffer->num_frames()));
1185 }
1186
peah1b08dc32016-12-20 13:45:58 -08001187 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001188 capture_buffer->channels_const()[0],
1189 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001190 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1191 if (log_rms) {
1192 capture_rms_interval_counter_ = 0;
1193 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001194 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1195 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1196 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1197 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001198 }
1199
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001200 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001201 // Detect and flag any change in the analog gain.
1202 int analog_mic_level = gain_control()->stream_analog_level();
1203 capture_.echo_path_gain_change =
1204 capture_.prev_analog_mic_level != analog_mic_level &&
1205 capture_.prev_analog_mic_level != -1;
1206 capture_.prev_analog_mic_level = analog_mic_level;
1207
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001208 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001209 }
1210
peahbe615622016-02-13 16:40:47 -08001211 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001212 public_submodules_->gain_control->is_enabled()) {
1213 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001214 capture_buffer->channels()[0], capture_buffer->num_channels(),
1215 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001216 }
1217
peah2ace3f92016-09-10 04:42:27 -07001218 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1219 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001220 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1221 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001222 }
1223
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001224 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001225 // Force down-mixing of the number of channels after the detection of
1226 // capture signal saturation.
1227 // TODO(peah): Look into ensuring that this kind of tampering with the
1228 // AudioBuffer functionality should not be needed.
1229 capture_buffer->set_num_channels(1);
1230 }
1231
peahe0eae3c2016-12-14 01:16:23 -08001232 // TODO(peah): Move the AEC3 low-cut filter to this place.
1233 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001234 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001235 private_submodules_->low_cut_filter->Process(capture_buffer);
1236 }
peahde65ddc2016-09-16 15:02:15 -07001237 RETURN_ON_ERR(
1238 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1239 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001240
1241 // Ensure that the stream delay was set before the call to the
1242 // AEC ProcessCaptureAudio function.
1243 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001244 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001245 return AudioProcessing::kStreamParameterNotSetError;
1246 }
1247
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001248 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001249 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1250
Per Åhgrend0fa8202018-04-18 09:35:13 +02001251 if (was_stream_delay_set()) {
1252 private_submodules_->echo_controller->SetAudioBufferDelay(
1253 stream_delay_ms());
1254 }
1255
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001256 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001257 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001258 } else {
1259 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1260 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001261 }
1262
peahdf3efa82015-11-28 12:35:15 -08001263 if (public_submodules_->echo_control_mobile->is_enabled() &&
1264 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001265 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001266 }
peahde65ddc2016-09-16 15:02:15 -07001267 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001268#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001269 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001270 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001271 const int gain_db =
1272 public_submodules_->gain_control->is_enabled()
1273 ? public_submodules_->gain_control->compression_gain_db()
1274 : 0;
1275 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001276 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001277 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001278 }
peah1bcfce52016-08-26 07:16:04 -07001279#endif
peah253534d2016-03-15 04:32:28 -07001280
1281 // Ensure that the stream delay was set before the call to the
1282 // AECM ProcessCaptureAudio function.
1283 if (public_submodules_->echo_control_mobile->is_enabled() &&
1284 !was_stream_delay_set()) {
1285 return AudioProcessing::kStreamParameterNotSetError;
1286 }
1287
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001288 if (!(private_submodules_->echo_controller ||
1289 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001290 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1291 capture_buffer, stream_delay_ms()));
1292 }
ivoc9f4a4a02016-10-28 05:39:16 -07001293
peahde65ddc2016-09-16 15:02:15 -07001294 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001295
peahbe615622016-02-13 16:40:47 -08001296 if (constants_.use_experimental_agc &&
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001297 public_submodules_->gain_control->is_enabled()) {
peahdf3efa82015-11-28 12:35:15 -08001298 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001299 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1300 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001301 }
peahb8fbb542016-03-15 02:28:08 -07001302 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001303 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001304
peah2ace3f92016-09-10 04:42:27 -07001305 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1306 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001307 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1308 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001309 }
1310
peah9e6a2902017-05-15 07:19:21 -07001311 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001312 RTC_DCHECK(private_submodules_->echo_detector);
1313 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001314 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1315 capture_buffer->num_frames()));
1316 }
1317
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001318 // TODO(aluebs): Investigate if the transient suppression placement should be
1319 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001320 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001321 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001322 private_submodules_->agc_manager.get()
1323 ? private_submodules_->agc_manager->voice_probability()
1324 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001325
peahdf3efa82015-11-28 12:35:15 -08001326 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001327 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1328 capture_buffer->num_channels(),
1329 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1330 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1331 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001332 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001333 }
1334
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001335 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001336 private_submodules_->gain_controller2->Process(capture_buffer);
1337 }
1338
Sam Zackrisson0beac582017-09-25 12:04:02 +02001339 if (private_submodules_->capture_post_processor) {
1340 private_submodules_->capture_post_processor->Process(capture_buffer);
1341 }
1342
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001343 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001344 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001345
peah1b08dc32016-12-20 13:45:58 -08001346 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1347 capture_buffer->channels_const()[0],
1348 capture_nonlocked_.capture_processing_format.num_frames()));
1349 if (log_rms) {
1350 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1351 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1352 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1353 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1354 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1355 }
1356
peahdf3efa82015-11-28 12:35:15 -08001357 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001358 return kNoError;
1359}
1360
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001361int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001362 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001363 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001364 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001365 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001366 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001367 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001368 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001369 };
1370 if (samples_per_channel != reverse_config.num_frames()) {
1371 return kBadDataLengthError;
1372 }
peahdf3efa82015-11-28 12:35:15 -08001373 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001374}
1375
peahde65ddc2016-09-16 15:02:15 -07001376int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1377 const StreamConfig& input_config,
1378 const StreamConfig& output_config,
1379 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001380 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001381 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001382 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001383 if (submodule_states_.RenderMultiBandProcessingActive() ||
1384 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001385 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1386 dest);
peah2ace3f92016-09-10 04:42:27 -07001387 } else if (formats_.api_format.reverse_input_stream() !=
1388 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001389 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1390 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001391 } else {
peahde65ddc2016-09-16 15:02:15 -07001392 CopyAudioIfNeeded(src, input_config.num_frames(),
1393 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001394 }
1395
1396 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001397}
1398
peahdf3efa82015-11-28 12:35:15 -08001399int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001400 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001401 const StreamConfig& input_config,
1402 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001403 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001404 return kNullPointerError;
1405 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001406
peahde65ddc2016-09-16 15:02:15 -07001407 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001408 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001409 }
1410
peahdf3efa82015-11-28 12:35:15 -08001411 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001412 processing_config.reverse_input_stream() = input_config;
1413 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001414
peahdf3efa82015-11-28 12:35:15 -08001415 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001416 RTC_DCHECK_EQ(input_config.num_frames(),
1417 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001418
aleloi868f32f2017-05-23 07:20:05 -07001419 if (aec_dump_) {
1420 const size_t channel_size =
1421 formats_.api_format.reverse_input_stream().num_frames();
1422 const size_t num_channels =
1423 formats_.api_format.reverse_input_stream().num_channels();
1424 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001425 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001426 }
peahdf3efa82015-11-28 12:35:15 -08001427 render_.render_audio->CopyFrom(src,
1428 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001429 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001430}
1431
1432int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001433 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001434 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001435 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001436 return kNullPointerError;
1437 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001438 // Must be a native rate.
1439 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1440 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001441 frame->sample_rate_hz_ != kSampleRate32kHz &&
1442 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001443 return kBadSampleRateError;
1444 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001445
Michael Graczyk86c6d332015-07-23 11:41:39 -07001446 if (frame->num_channels_ <= 0) {
1447 return kBadNumberChannelsError;
1448 }
1449
peahdf3efa82015-11-28 12:35:15 -08001450 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001451 processing_config.reverse_input_stream().set_sample_rate_hz(
1452 frame->sample_rate_hz_);
1453 processing_config.reverse_input_stream().set_num_channels(
1454 frame->num_channels_);
1455 processing_config.reverse_output_stream().set_sample_rate_hz(
1456 frame->sample_rate_hz_);
1457 processing_config.reverse_output_stream().set_num_channels(
1458 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001459
peahdf3efa82015-11-28 12:35:15 -08001460 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001461 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001462 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001463 return kBadDataLengthError;
1464 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001465
aleloi868f32f2017-05-23 07:20:05 -07001466 if (aec_dump_) {
1467 aec_dump_->WriteRenderStreamMessage(*frame);
1468 }
1469
peahdf3efa82015-11-28 12:35:15 -08001470 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001471 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001472 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001473 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1474 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001475 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001476}
niklase@google.com470e71d2011-07-07 08:21:25 +00001477
peahde65ddc2016-09-16 15:02:15 -07001478int AudioProcessingImpl::ProcessRenderStreamLocked() {
1479 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001480
1481 QueueNonbandedRenderAudio(render_buffer);
1482
Alex Loiko73ec0192018-05-15 10:52:28 +02001483 HandleRenderRuntimeSettings();
1484
Alex Loiko5825aa62017-12-18 16:02:40 +01001485 if (private_submodules_->render_pre_processor) {
1486 private_submodules_->render_pre_processor->Process(render_buffer);
1487 }
1488
peah2ace3f92016-09-10 04:42:27 -07001489 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001490 SampleRateSupportsMultiBand(
1491 formats_.render_processing_format.sample_rate_hz())) {
1492 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001493 }
1494
peah1bcfce52016-08-26 07:16:04 -07001495#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001496 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001497 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001498 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001499 }
peah1bcfce52016-08-26 07:16:04 -07001500#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001501
peahce4d9152017-05-19 01:28:05 -07001502 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1503 QueueBandedRenderAudio(render_buffer);
1504 }
1505
peahe0eae3c2016-12-14 01:16:23 -08001506 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001507 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001508 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001509 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001510
peah2ace3f92016-09-10 04:42:27 -07001511 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001512 SampleRateSupportsMultiBand(
1513 formats_.render_processing_format.sample_rate_hz())) {
1514 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001515 }
1516
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001517 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001518}
1519
1520int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001521 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001522 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001523 capture_.was_stream_delay_set = true;
1524 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001525
niklase@google.com470e71d2011-07-07 08:21:25 +00001526 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001527 delay = 0;
1528 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001529 }
1530
1531 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1532 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001533 delay = 500;
1534 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001535 }
1536
peahdf3efa82015-11-28 12:35:15 -08001537 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001538 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001539}
1540
1541int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001542 // Used as callback from submodules, hence locking is not allowed.
1543 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001544}
1545
1546bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001547 // Used as callback from submodules, hence locking is not allowed.
1548 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001549}
1550
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001551void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001552 rtc::CritScope cs(&crit_capture_);
1553 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001554}
1555
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001556void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001557 rtc::CritScope cs(&crit_capture_);
1558 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001559}
1560
1561int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001562 rtc::CritScope cs(&crit_capture_);
1563 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001564}
1565
aleloi868f32f2017-05-23 07:20:05 -07001566void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1567 RTC_DCHECK(aec_dump);
1568 rtc::CritScope cs_render(&crit_render_);
1569 rtc::CritScope cs_capture(&crit_capture_);
1570
1571 // The previously attached AecDump will be destroyed with the
1572 // 'aec_dump' parameter, which is after locks are released.
1573 aec_dump_.swap(aec_dump);
1574 WriteAecDumpConfigMessage(true);
Alex Loiko1aec5942018-05-15 13:13:22 +02001575 aec_dump_->WriteInitMessage(formats_.api_format);
aleloi868f32f2017-05-23 07:20:05 -07001576}
1577
1578void AudioProcessingImpl::DetachAecDump() {
1579 // The d-tor of a task-queue based AecDump blocks until all pending
1580 // tasks are done. This construction avoids blocking while holding
1581 // the render and capture locks.
1582 std::unique_ptr<AecDump> aec_dump = nullptr;
1583 {
1584 rtc::CritScope cs_render(&crit_render_);
1585 rtc::CritScope cs_capture(&crit_capture_);
1586 aec_dump = std::move(aec_dump_);
1587 }
1588}
1589
Sam Zackrisson4d364492018-03-02 16:03:21 +01001590void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1591 std::unique_ptr<AudioGenerator> audio_generator) {
1592 // TODO(bugs.webrtc.org/8882) Stub.
1593 // Reset internal audio generator with audio_generator.
1594}
1595
1596void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1597 // TODO(bugs.webrtc.org/8882) Stub.
1598 // Delete audio generator, if one is attached.
1599}
1600
ivoc4e477a12017-01-15 08:29:46 -08001601AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1602 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1603 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1604 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1605 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1606}
1607
1608AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1609 const AudioProcessingStatistics& other) = default;
1610
1611AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1612 default;
1613
ivoc3e9a5372016-10-28 07:55:33 -07001614// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1615AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1616 const {
1617 return AudioProcessingStatistics();
1618}
1619
Ivo Creusenae026092017-11-20 13:07:16 +01001620// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001621AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001622 bool has_remote_tracks) const {
1623 return AudioProcessingStats();
1624}
1625
ivoc3e9a5372016-10-28 07:55:33 -07001626AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1627 const {
1628 AudioProcessingStatistics stats;
1629 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001630 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001631 rtc::CritScope cs_capture(&crit_capture_);
1632 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1633 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1634 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1635 // Instant value will also be used for min, max and average.
1636 stats.echo_return_loss.Set(erl, erl, erl, erl);
1637 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1638 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1639 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001640 stats.a_nlp.Set(metrics.a_nlp);
1641 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1642 stats.echo_return_loss.Set(metrics.echo_return_loss);
1643 stats.echo_return_loss_enhancement.Set(
1644 metrics.echo_return_loss_enhancement);
1645 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1646 }
ivoc9c192b22017-03-16 04:22:14 -07001647 {
1648 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001649 RTC_DCHECK(private_submodules_->echo_detector);
1650 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1651 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001652 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001653 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001654 }
ivoc3e9a5372016-10-28 07:55:33 -07001655 public_submodules_->echo_cancellation->GetDelayMetrics(
1656 &stats.delay_median, &stats.delay_standard_deviation,
1657 &stats.fraction_poor_delays);
1658 return stats;
1659}
1660
Ivo Creusen56d46092017-11-24 17:29:59 +01001661AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001662 bool has_remote_tracks) const {
1663 AudioProcessingStats stats;
1664 if (has_remote_tracks) {
1665 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001666 if (private_submodules_->echo_controller) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001667 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001668 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1669 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001670 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001671 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001672 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001673 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1674 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001675 if (metrics.divergent_filter_fraction != -1.0f) {
1676 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001677 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001678 }
1679 if (metrics.echo_return_loss.instant != -100) {
1680 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001681 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001682 }
1683 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001684 stats.echo_return_loss_enhancement = absl::optional<double>(
1685 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001686 }
1687 }
1688 if (config_.residual_echo_detector.enabled) {
1689 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001690 RTC_DCHECK(private_submodules_->echo_detector);
1691 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1692 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001693 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001694 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001695 }
1696 int delay_median, delay_std;
1697 float fraction_poor_delays;
1698 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1699 &delay_median, &delay_std, &fraction_poor_delays) ==
1700 Error::kNoError) {
1701 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001702 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001703 }
1704 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001705 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001706 }
1707 }
1708 }
1709 return stats;
1710}
1711
niklase@google.com470e71d2011-07-07 08:21:25 +00001712EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001713 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001714}
1715
1716EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001717 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001718}
1719
1720GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001721 if (constants_.use_experimental_agc) {
1722 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001723 }
peahbfa97112016-03-10 21:09:04 -08001724 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001725}
1726
1727HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001728 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001729}
1730
1731LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001732 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001733}
1734
1735NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001736 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001737}
1738
1739VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001740 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001741}
1742
peah8271d042016-11-22 07:24:52 -08001743void AudioProcessingImpl::MutateConfig(
1744 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1745 rtc::CritScope cs_render(&crit_render_);
1746 rtc::CritScope cs_capture(&crit_capture_);
1747 mutator(&config_);
1748 ApplyConfig(config_);
1749}
1750
1751AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1752 rtc::CritScope cs_render(&crit_render_);
1753 rtc::CritScope cs_capture(&crit_capture_);
1754 return config_;
1755}
1756
peah2ace3f92016-09-10 04:42:27 -07001757bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1758 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001759 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001760 public_submodules_->echo_cancellation->is_enabled(),
1761 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001762 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001763 public_submodules_->noise_suppression->is_enabled(),
1764 capture_nonlocked_.intelligibility_enabled,
peah2ace3f92016-09-10 04:42:27 -07001765 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001766 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001767 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001768 public_submodules_->voice_detection->is_enabled(),
1769 public_submodules_->level_estimator->is_enabled(),
1770 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001771}
1772
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001773
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001774void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001775 if (capture_.transient_suppressor_enabled) {
1776 if (!public_submodules_->transient_suppressor.get()) {
1777 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001778 }
peahdf3efa82015-11-28 12:35:15 -08001779 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001780 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1781 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001782 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001783}
1784
ekmeyerson60d9b332015-08-14 10:35:55 -07001785void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001786#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001787 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001788 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001789 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001790 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001791 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001792 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001793 }
peah1bcfce52016-08-26 07:16:04 -07001794#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001795}
1796
peah8271d042016-11-22 07:24:52 -08001797void AudioProcessingImpl::InitializeLowCutFilter() {
1798 if (config_.high_pass_filter.enabled) {
1799 private_submodules_->low_cut_filter.reset(
1800 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1801 } else {
1802 private_submodules_->low_cut_filter.reset();
1803 }
1804}
alessiob3ec96df2017-05-22 06:57:06 -07001805
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001806void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001807 if (echo_control_factory_) {
1808 private_submodules_->echo_controller =
1809 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001810 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001811 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001812 }
1813}
peah8271d042016-11-22 07:24:52 -08001814
alessiob3ec96df2017-05-22 06:57:06 -07001815void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001816 if (config_.gain_controller2.enabled) {
1817 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001818 }
1819}
1820
Alex Loikob5c9a792018-04-16 16:31:22 +02001821void AudioProcessingImpl::InitializePreAmplifier() {
1822 if (config_.pre_amplifier.enabled) {
1823 private_submodules_->pre_amplifier.reset(
1824 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1825 } else {
1826 private_submodules_->pre_amplifier.reset();
1827 }
1828}
1829
ivoc9f4a4a02016-10-28 05:39:16 -07001830void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001831 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001832 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001833 proc_sample_rate_hz(), 1,
1834 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001835}
1836
Sam Zackrisson0beac582017-09-25 12:04:02 +02001837void AudioProcessingImpl::InitializePostProcessor() {
1838 if (private_submodules_->capture_post_processor) {
1839 private_submodules_->capture_post_processor->Initialize(
1840 proc_sample_rate_hz(), num_proc_channels());
1841 }
1842}
1843
Alex Loiko5825aa62017-12-18 16:02:40 +01001844void AudioProcessingImpl::InitializePreProcessor() {
1845 if (private_submodules_->render_pre_processor) {
1846 private_submodules_->render_pre_processor->Initialize(
1847 formats_.render_processing_format.sample_rate_hz(),
1848 formats_.render_processing_format.num_channels());
1849 }
1850}
1851
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001852void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001853 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001854
1855 if (echo_cancellation()->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001856 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1857 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001858 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001859 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001860 capture_.stream_delay_jumps = 0;
1861 }
1862 if (capture_.aec_system_delay_jumps == -1 &&
1863 echo_cancellation()->stream_has_echo()) {
1864 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001865 }
1866
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001867 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001868 const int diff_stream_delay_ms =
1869 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1870 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1871 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001872 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1873 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001874 if (capture_.stream_delay_jumps == -1) {
1875 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001876 }
peahdf3efa82015-11-28 12:35:15 -08001877 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001878 }
peahdf3efa82015-11-28 12:35:15 -08001879 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001880
1881 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001882 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001883 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001884 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001885 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001886 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1887 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001888 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001889 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001890 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001891 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001892 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1893 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1894 100);
peahdf3efa82015-11-28 12:35:15 -08001895 if (capture_.aec_system_delay_jumps == -1) {
1896 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001897 }
peahdf3efa82015-11-28 12:35:15 -08001898 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001899 }
peahdf3efa82015-11-28 12:35:15 -08001900 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001901 }
1902}
1903
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001904void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001905 // Run in a single-threaded manner.
1906 rtc::CritScope cs_render(&crit_render_);
1907 rtc::CritScope cs_capture(&crit_capture_);
1908
1909 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001910 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001911 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001912 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001913 }
peahdf3efa82015-11-28 12:35:15 -08001914 capture_.stream_delay_jumps = -1;
1915 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001916
peahdf3efa82015-11-28 12:35:15 -08001917 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001918 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1919 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001920 }
peahdf3efa82015-11-28 12:35:15 -08001921 capture_.aec_system_delay_jumps = -1;
1922 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001923}
1924
aleloi868f32f2017-05-23 07:20:05 -07001925void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1926 if (!aec_dump_) {
1927 return;
1928 }
1929 std::string experiments_description =
1930 public_submodules_->echo_cancellation->GetExperimentsDescription();
1931 // TODO(peah): Add semicolon-separated concatenations of experiment
1932 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001933 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1934 experiments_description += "AgcClippingLevelExperiment;";
1935 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001936 if (capture_nonlocked_.echo_controller_enabled) {
1937 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001938 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001939 if (config_.gain_controller2.enabled) {
1940 experiments_description += "GainController2;";
1941 }
aleloi868f32f2017-05-23 07:20:05 -07001942
1943 InternalAPMConfig apm_config;
1944
1945 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1946 apm_config.aec_delay_agnostic_enabled =
1947 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1948 apm_config.aec_drift_compensation_enabled =
1949 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1950 apm_config.aec_extended_filter_enabled =
1951 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1952 apm_config.aec_suppression_level = static_cast<int>(
1953 public_submodules_->echo_cancellation->suppression_level());
1954
1955 apm_config.aecm_enabled =
1956 public_submodules_->echo_control_mobile->is_enabled();
1957 apm_config.aecm_comfort_noise_enabled =
1958 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1959 apm_config.aecm_routing_mode =
1960 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1961
1962 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1963 apm_config.agc_mode =
1964 static_cast<int>(public_submodules_->gain_control->mode());
1965 apm_config.agc_limiter_enabled =
1966 public_submodules_->gain_control->is_limiter_enabled();
1967 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1968
1969 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1970
1971 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1972 apm_config.ns_level =
1973 static_cast<int>(public_submodules_->noise_suppression->level());
1974
1975 apm_config.transient_suppression_enabled =
1976 capture_.transient_suppressor_enabled;
1977 apm_config.intelligibility_enhancer_enabled =
1978 capture_nonlocked_.intelligibility_enabled;
1979 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001980 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1981 apm_config.pre_amplifier_fixed_gain_factor =
1982 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001983
1984 if (!forced && apm_config == apm_config_for_aec_dump_) {
1985 return;
1986 }
1987 aec_dump_->WriteConfig(apm_config);
1988 apm_config_for_aec_dump_ = apm_config;
1989}
1990
1991void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1992 const float* const* src) {
1993 RTC_DCHECK(aec_dump_);
1994 WriteAecDumpConfigMessage(false);
1995
1996 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1997 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1998 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001999 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002000 RecordAudioProcessingState();
2001}
2002
2003void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2004 const AudioFrame& capture_frame) {
2005 RTC_DCHECK(aec_dump_);
2006 WriteAecDumpConfigMessage(false);
2007
2008 aec_dump_->AddCaptureStreamInput(capture_frame);
2009 RecordAudioProcessingState();
2010}
2011
2012void AudioProcessingImpl::RecordProcessedCaptureStream(
2013 const float* const* processed_capture_stream) {
2014 RTC_DCHECK(aec_dump_);
2015
2016 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2017 const size_t num_channels =
2018 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002019 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2020 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002021 aec_dump_->WriteCaptureStreamMessage();
2022}
2023
2024void AudioProcessingImpl::RecordProcessedCaptureStream(
2025 const AudioFrame& processed_capture_frame) {
2026 RTC_DCHECK(aec_dump_);
2027
2028 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2029 aec_dump_->WriteCaptureStreamMessage();
2030}
2031
2032void AudioProcessingImpl::RecordAudioProcessingState() {
2033 RTC_DCHECK(aec_dump_);
2034 AecDump::AudioProcessingState audio_proc_state;
2035 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2036 audio_proc_state.drift =
2037 public_submodules_->echo_cancellation->stream_drift_samples();
2038 audio_proc_state.level = gain_control()->stream_analog_level();
2039 audio_proc_state.keypress = capture_.key_pressed;
2040 aec_dump_->AddAudioProcessingState(audio_proc_state);
2041}
2042
kwiberg83ffe452016-08-29 14:46:07 -07002043AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002044 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002045 : aec_system_delay_jumps(-1),
2046 delay_offset_ms(0),
2047 was_stream_delay_set(false),
2048 last_stream_delay_ms(0),
2049 last_aec_system_delay_ms(0),
2050 stream_delay_jumps(-1),
2051 output_will_be_muted(false),
2052 key_pressed(false),
2053 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002054 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002055 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002056 echo_path_gain_change(false),
2057 prev_analog_mic_level(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002058
2059AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2060
2061AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2062
2063AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2064
niklase@google.com470e71d2011-07-07 08:21:25 +00002065} // namespace webrtc