blob: 04c1ba2cf2fff96a560fbab124700d6544b917f8 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/common.h"
26#include "modules/audio_processing/echo_cancellation_impl.h"
27#include "modules/audio_processing/echo_control_mobile_impl.h"
28#include "modules/audio_processing/gain_control_for_experimental_agc.h"
29#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010030#include "modules/audio_processing/gain_controller2.h"
Per Åhgren13735822018-02-12 21:42:56 +010031#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
33#include "rtc_base/logging.h"
34#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020035#include "rtc_base/refcountedobject.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020036#include "rtc_base/system/arch.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070038#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070040#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "modules/audio_processing/level_estimator_impl.h"
42#include "modules/audio_processing/low_cut_filter.h"
43#include "modules/audio_processing/noise_suppression_impl.h"
44#include "modules/audio_processing/residual_echo_detector.h"
45#include "modules/audio_processing/transient/transient_suppressor.h"
46#include "modules/audio_processing/voice_detection_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010047#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000049
peah1bcfce52016-08-26 07:16:04 -070050// Check to verify that the define for the intelligibility enhancer is properly
51// set.
52#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
53 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
54 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
55#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
56#endif
57
Michael Graczyk86c6d332015-07-23 11:41:39 -070058#define RETURN_ON_ERR(expr) \
59 do { \
60 int err = (expr); \
61 if (err != kNoError) { \
62 return err; \
63 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000064 } while (0)
65
niklase@google.com470e71d2011-07-07 08:21:25 +000066namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070067
kwibergd59d3bb2016-09-13 07:49:33 -070068constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020069constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070070
Michael Graczyk86c6d332015-07-23 11:41:39 -070071namespace {
72
73static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
74 switch (layout) {
75 case AudioProcessing::kMono:
76 case AudioProcessing::kStereo:
77 return false;
78 case AudioProcessing::kMonoAndKeyboard:
79 case AudioProcessing::kStereoAndKeyboard:
80 return true;
81 }
82
kwiberg9e2be5f2016-09-14 05:23:22 -070083 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070084 return false;
85}
aluebsdf6416a2016-03-16 18:26:35 -070086
peah2ace3f92016-09-10 04:42:27 -070087bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070088 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
89 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
90}
91
peah2ace3f92016-09-10 04:42:27 -070092int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
93#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070094 constexpr int kMaxSplittingNativeProcessRate =
95 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070096#else
kwibergd59d3bb2016-09-13 07:49:33 -070097 constexpr int kMaxSplittingNativeProcessRate =
98 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070099#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700100 static_assert(
101 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
102 "");
peah2ace3f92016-09-10 04:42:27 -0700103 const int uppermost_native_rate = band_splitting_required
104 ? kMaxSplittingNativeProcessRate
105 : AudioProcessing::kSampleRate48kHz;
106
107 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
108 if (rate >= uppermost_native_rate) {
109 return uppermost_native_rate;
110 }
111 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700112 return rate;
113 }
114 }
peah2ace3f92016-09-10 04:42:27 -0700115 RTC_NOTREACHED();
116 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700117}
118
peah9e6a2902017-05-15 07:19:21 -0700119// Maximum lengths that frame of samples being passed from the render side to
120// the capture side can have (does not apply to AEC3).
121static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
122static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum number of frames to buffer in the render queue.
125// TODO(peah): Decrease this once we properly handle hugely unbalanced
126// reverse and forward call numbers.
127static const size_t kMaxNumFramesToBuffer = 100;
128
peah8271d042016-11-22 07:24:52 -0800129class HighPassFilterImpl : public HighPassFilter {
130 public:
131 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
132 ~HighPassFilterImpl() override = default;
133
134 // HighPassFilter implementation.
135 int Enable(bool enable) override {
136 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
137 config->high_pass_filter.enabled = enable;
138 });
139
140 return AudioProcessing::kNoError;
141 }
142
143 bool is_enabled() const override {
144 return apm_->GetConfig().high_pass_filter.enabled;
145 }
146
147 private:
148 AudioProcessingImpl* apm_;
149 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
150};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700151} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000152
153// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000154static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000155
Sam Zackrisson0beac582017-09-25 12:04:02 +0200156AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100157 bool capture_post_processor_enabled,
158 bool render_pre_processor_enabled)
159 : capture_post_processor_enabled_(capture_post_processor_enabled),
160 render_pre_processor_enabled_(render_pre_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700161
162bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800163 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700164 bool echo_canceller_enabled,
165 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700166 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700167 bool noise_suppressor_enabled,
168 bool intelligibility_enhancer_enabled,
peah2ace3f92016-09-10 04:42:27 -0700169 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700170 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200171 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200172 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700173 bool voice_activity_detector_enabled,
174 bool level_estimator_enabled,
175 bool transient_suppressor_enabled) {
176 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800177 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700178 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
179 changed |=
180 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700181 changed |=
182 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700183 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
184 changed |=
185 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700186 changed |=
187 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700188 changed |=
189 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200190 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200191 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700192 changed |= (level_estimator_enabled != level_estimator_enabled_);
193 changed |=
194 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
195 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
196 if (changed) {
peah8271d042016-11-22 07:24:52 -0800197 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700198 echo_canceller_enabled_ = echo_canceller_enabled;
199 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700200 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700201 noise_suppressor_enabled_ = noise_suppressor_enabled;
202 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
peah2ace3f92016-09-10 04:42:27 -0700203 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700204 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200205 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200206 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700207 level_estimator_enabled_ = level_estimator_enabled;
208 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
209 transient_suppressor_enabled_ = transient_suppressor_enabled;
210 }
211
212 changed |= first_update_;
213 first_update_ = false;
214 return changed;
215}
216
217bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
218 const {
219#if WEBRTC_INTELLIGIBILITY_ENHANCER
220 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700221 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700222#else
peah52775842017-05-16 06:14:09 -0700223 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700224#endif
225}
226
227bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
228 const {
peah8271d042016-11-22 07:24:52 -0800229 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700230 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200231 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700232}
233
peah23ac8b42017-05-23 05:33:56 -0700234bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
235 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200236 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
237 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700238}
239
peah2ace3f92016-09-10 04:42:27 -0700240bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
241 const {
242 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800243 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200244 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700245}
246
Alex Loiko5825aa62017-12-18 16:02:40 +0100247bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
248 const {
249 return render_pre_processor_enabled_;
250}
251
peah2ace3f92016-09-10 04:42:27 -0700252bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
253 const {
254#if WEBRTC_INTELLIGIBILITY_ENHANCER
255 return intelligibility_enhancer_enabled_;
256#else
257 return false;
258#endif
259}
260
solenberg5e465c32015-12-08 13:22:33 -0800261struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800262 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800263 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800264 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800265 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800266 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800267 std::unique_ptr<LevelEstimatorImpl> level_estimator;
268 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
269 std::unique_ptr<VoiceDetectionImpl> voice_detection;
270 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800271 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800272
273 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800274 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700275#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800276 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700277#endif
solenberg5e465c32015-12-08 13:22:33 -0800278};
279
280struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200281 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100282 std::unique_ptr<CustomProcessing> render_pre_processor,
Ivo Creusend1f970d2018-06-14 11:02:03 +0200283 rtc::scoped_refptr<EchoDetector> echo_detector)
Sam Zackrissondb389722018-06-21 10:12:24 +0200284 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100285 capture_post_processor(std::move(capture_post_processor)),
286 render_pre_processor(std::move(render_pre_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800287 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800288 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700289 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800290 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200291 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200292 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100293 std::unique_ptr<CustomProcessing> capture_post_processor;
294 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200295 std::unique_ptr<GainApplier> pre_amplifier;
solenberg5e465c32015-12-08 13:22:33 -0800296};
297
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100298AudioProcessingBuilder::AudioProcessingBuilder() = default;
299AudioProcessingBuilder::~AudioProcessingBuilder() = default;
300
301AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
302 std::unique_ptr<CustomProcessing> capture_post_processing) {
303 capture_post_processing_ = std::move(capture_post_processing);
304 return *this;
305}
306
307AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
308 std::unique_ptr<CustomProcessing> render_pre_processing) {
309 render_pre_processing_ = std::move(render_pre_processing);
310 return *this;
311}
312
313AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
314 std::unique_ptr<EchoControlFactory> echo_control_factory) {
315 echo_control_factory_ = std::move(echo_control_factory);
316 return *this;
317}
318
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100319AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200320 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100321 echo_detector_ = std::move(echo_detector);
322 return *this;
323}
324
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100325AudioProcessing* AudioProcessingBuilder::Create() {
326 webrtc::Config config;
327 return Create(config);
328}
329
330AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100331 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
332 config, std::move(capture_post_processing_),
333 std::move(render_pre_processing_), std::move(echo_control_factory_),
Sam Zackrissondb389722018-06-21 10:12:24 +0200334 std::move(echo_detector_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100335 if (apm->Initialize() != AudioProcessing::kNoError) {
336 delete apm;
337 apm = nullptr;
338 }
339 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100340}
341
peah88ac8532016-09-12 16:47:25 -0700342AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissondb389722018-06-21 10:12:24 +0200343 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000344
Per Åhgren13735822018-02-12 21:42:56 +0100345int AudioProcessingImpl::instance_count_ = 0;
346
Sam Zackrisson0beac582017-09-25 12:04:02 +0200347AudioProcessingImpl::AudioProcessingImpl(
348 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100349 std::unique_ptr<CustomProcessing> capture_post_processor,
350 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200351 std::unique_ptr<EchoControlFactory> echo_control_factory,
Sam Zackrissondb389722018-06-21 10:12:24 +0200352 rtc::scoped_refptr<EchoDetector> echo_detector)
Per Åhgren13735822018-02-12 21:42:56 +0100353 : data_dumper_(
354 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200355 capture_runtime_settings_(kRuntimeSettingQueueSize),
356 render_runtime_settings_(kRuntimeSettingQueueSize),
357 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
358 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100359 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200360 echo_control_factory_(std::move(echo_control_factory)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100361 submodule_states_(!!capture_post_processor, !!render_pre_processor),
peah8271d042016-11-22 07:24:52 -0800362 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200363 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200364 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100365 std::move(render_pre_processor),
366 std::move(echo_detector))),
peahdf3efa82015-11-28 12:35:15 -0800367 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800368 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000369#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loiko64cb83b2018-07-02 13:38:19 +0200370 false,
371 false,
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700372 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000373#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200374 config.Get<ExperimentalAgc>().enabled,
375 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
376 config.Get<ExperimentalAgc>().enabled_agc2_digital_adaptive),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000377#endif
andrew1c7075f2015-06-24 18:14:14 -0700378#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200379 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700380#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200381 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700382#endif
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200383 capture_nonlocked_(config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800384 {
385 rtc::CritScope cs_render(&crit_render_);
386 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000387
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200388 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000389 capture_nonlocked_.echo_controller_enabled =
390 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200391
peahb624d8c2016-03-05 03:01:14 -0800392 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700393 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800394 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700395 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800396 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200397 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800398 public_submodules_->level_estimator.reset(
399 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800400 public_submodules_->noise_suppression.reset(
401 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800402 public_submodules_->voice_detection.reset(
403 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800404 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800405 new GainControlForExperimentalAgc(
406 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100407
408 // If no echo detector is injected, use the ResidualEchoDetector.
409 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200410 private_submodules_->echo_detector =
411 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100412 }
peahca4cac72016-06-29 15:26:12 -0700413
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200414 // TODO(alessiob): Move the injected gain controller once injection is
415 // implemented.
416 private_submodules_->gain_controller2.reset(new GainController2());
417
Mirko Bonadei675513b2017-11-09 11:09:25 +0100418 RTC_LOG(LS_INFO) << "Capture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100419 << !!private_submodules_->capture_post_processor
420 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100421 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800422 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000423
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000424 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000425}
426
427AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800428 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800429 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800430 private_submodules_->agc_manager.reset();
431 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800432 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000433}
434
niklase@google.com470e71d2011-07-07 08:21:25 +0000435int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800436 // Run in a single-threaded manner during initialization.
437 rtc::CritScope cs_render(&crit_render_);
438 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000439 return InitializeLocked();
440}
441
peahde65ddc2016-09-16 15:02:15 -0700442int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
443 int capture_output_sample_rate_hz,
444 int render_input_sample_rate_hz,
445 ChannelLayout capture_input_layout,
446 ChannelLayout capture_output_layout,
447 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700448 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700449 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
450 LayoutHasKeyboard(capture_input_layout)},
451 {capture_output_sample_rate_hz,
452 ChannelsFromLayout(capture_output_layout),
453 LayoutHasKeyboard(capture_output_layout)},
454 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
455 LayoutHasKeyboard(render_input_layout)},
456 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
457 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700458
459 return Initialize(processing_config);
460}
461
462int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800463 // Run in a single-threaded manner during initialization.
464 rtc::CritScope cs_render(&crit_render_);
465 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700466 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000467}
468
peahdf3efa82015-11-28 12:35:15 -0800469int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800470 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700471 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800472}
473
peahdf3efa82015-11-28 12:35:15 -0800474int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700475 const ProcessingConfig& processing_config,
476 bool force_initialization) {
477 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800478}
479
peah192164e2015-11-17 02:16:45 -0800480// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800481// their current values (needs to be called while holding the crit_render_lock).
482int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700483 const ProcessingConfig& processing_config,
484 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800485 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700486 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800487 return kNoError;
488 }
peahdf3efa82015-11-28 12:35:15 -0800489
490 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800491 return InitializeLocked(processing_config);
492}
493
niklase@google.com470e71d2011-07-07 08:21:25 +0000494int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200495 UpdateActiveSubmoduleStates();
496
peahde65ddc2016-09-16 15:02:15 -0700497 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800498 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700499 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800500 : formats_.api_format.reverse_output_stream().num_frames();
501 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
502 render_.render_audio.reset(new AudioBuffer(
503 formats_.api_format.reverse_input_stream().num_frames(),
504 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700505 formats_.render_processing_format.num_frames(),
506 formats_.render_processing_format.num_channels(),
507 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700508 if (formats_.api_format.reverse_input_stream() !=
509 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800510 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800511 formats_.api_format.reverse_input_stream().num_channels(),
512 formats_.api_format.reverse_input_stream().num_frames(),
513 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800514 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700515 } else {
peahdf3efa82015-11-28 12:35:15 -0800516 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700517 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700518 } else {
peahdf3efa82015-11-28 12:35:15 -0800519 render_.render_audio.reset(nullptr);
520 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700521 }
peahce4d9152017-05-19 01:28:05 -0700522
peahdf3efa82015-11-28 12:35:15 -0800523 capture_.capture_audio.reset(
524 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
525 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700526 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200527 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800528 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000529
peahde65ddc2016-09-16 15:02:15 -0700530 public_submodules_->echo_cancellation->Initialize(
531 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
532 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700533 AllocateRenderQueue();
534
ivoc3e9a5372016-10-28 07:55:33 -0700535 int success = public_submodules_->echo_cancellation->enable_metrics(true);
536 RTC_DCHECK_EQ(0, success);
537 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
538 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700539 public_submodules_->echo_control_mobile->Initialize(
540 proc_split_sample_rate_hz(), num_reverse_channels(),
541 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700542
543 public_submodules_->gain_control->Initialize(num_proc_channels(),
544 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700545 if (constants_.use_experimental_agc) {
546 if (!private_submodules_->agc_manager.get()) {
547 private_submodules_->agc_manager.reset(new AgcManagerDirect(
548 public_submodules_->gain_control.get(),
549 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200550 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
551 constants_.use_experimental_agc_agc2_level_estimation,
552 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700553 }
554 private_submodules_->agc_manager->Initialize();
555 private_submodules_->agc_manager->SetCaptureMuted(
556 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700557 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700558 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200559 InitializeTransient();
peah1bcfce52016-08-26 07:16:04 -0700560#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700561 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700562#endif
peah8271d042016-11-22 07:24:52 -0800563 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700564 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
565 proc_sample_rate_hz());
566 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
567 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700568 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200569 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700570 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200571 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100572 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800573
aleloi868f32f2017-05-23 07:20:05 -0700574 if (aec_dump_) {
Alex Loiko1aec5942018-05-15 13:13:22 +0200575 aec_dump_->WriteInitMessage(formats_.api_format);
aleloi868f32f2017-05-23 07:20:05 -0700576 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000577 return kNoError;
578}
579
Michael Graczyk86c6d332015-07-23 11:41:39 -0700580int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200581 UpdateActiveSubmoduleStates();
582
Michael Graczyk86c6d332015-07-23 11:41:39 -0700583 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700584 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
585 return kBadSampleRateError;
586 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000587 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700588
Peter Kasting69558702016-01-12 16:26:35 -0800589 const size_t num_in_channels = config.input_stream().num_channels();
590 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700591
592 // Need at least one input channel.
593 // Need either one output channel or as many outputs as there are inputs.
594 if (num_in_channels == 0 ||
595 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700596 return kBadNumberChannelsError;
597 }
598
peahdf3efa82015-11-28 12:35:15 -0800599 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000600
peahde65ddc2016-09-16 15:02:15 -0700601 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700602 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700603 formats_.api_format.output_stream().sample_rate_hz()),
604 submodule_states_.CaptureMultiBandSubModulesActive() ||
605 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000606
peahde65ddc2016-09-16 15:02:15 -0700607 capture_nonlocked_.capture_processing_format =
608 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700609
peah2ce640f2017-04-07 03:57:48 -0700610 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200611 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700612 render_processing_rate = FindNativeProcessRateToUse(
613 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
614 formats_.api_format.reverse_output_stream().sample_rate_hz()),
615 submodule_states_.CaptureMultiBandSubModulesActive() ||
616 submodule_states_.RenderMultiBandSubModulesActive());
617 } else {
618 render_processing_rate = capture_processing_rate;
619 }
620
aluebseb3603b2016-04-20 15:27:58 -0700621 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
622 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700623 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200624 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700625 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
626 ? kSampleRate32kHz
627 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700628 }
peah2ce640f2017-04-07 03:57:48 -0700629
peahde65ddc2016-09-16 15:02:15 -0700630 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700631 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700632 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
633 kSampleRate8kHz) {
634 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000635 } else {
peahde65ddc2016-09-16 15:02:15 -0700636 render_processing_rate =
637 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000638 }
639
peahde65ddc2016-09-16 15:02:15 -0700640 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000641 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700642 if (submodule_states_.RenderMultiBandSubModulesActive()) {
643 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
644 } else {
645 formats_.render_processing_format = StreamConfig(
646 formats_.api_format.reverse_input_stream().sample_rate_hz(),
647 formats_.api_format.reverse_input_stream().num_channels());
648 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000649
peahde65ddc2016-09-16 15:02:15 -0700650 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
651 kSampleRate32kHz ||
652 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
653 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800654 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000655 } else {
peahdf3efa82015-11-28 12:35:15 -0800656 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700657 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000658 }
659
660 return InitializeLocked();
661}
662
peah88ac8532016-09-12 16:47:25 -0700663void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700664 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700665
peah88ac8532016-09-12 16:47:25 -0700666 // Run in a single-threaded manner when applying the settings.
667 rtc::CritScope cs_render(&crit_render_);
668 rtc::CritScope cs_capture(&crit_capture_);
669
peah8271d042016-11-22 07:24:52 -0800670 InitializeLowCutFilter();
671
Mirko Bonadei675513b2017-11-09 11:09:25 +0100672 RTC_LOG(LS_INFO) << "Highpass filter activated: "
673 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800674
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100675 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700676 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100677 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
678 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100679 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100680 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700681 config_.gain_controller2 = AudioProcessing::Config::GainController2();
682 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200683 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200684 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200685 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100686 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
687 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200688 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
689 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700690}
691
692void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800693 // Run in a single-threaded manner when setting the extra options.
694 rtc::CritScope cs_render(&crit_render_);
695 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000696
peahb624d8c2016-03-05 03:01:14 -0800697 public_submodules_->echo_cancellation->SetExtraOptions(config);
698
peahdf3efa82015-11-28 12:35:15 -0800699 if (capture_.transient_suppressor_enabled !=
700 config.Get<ExperimentalNs>().enabled) {
701 capture_.transient_suppressor_enabled =
702 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000703 InitializeTransient();
704 }
aluebs2a346882016-01-11 18:04:30 -0800705
peah1bcfce52016-08-26 07:16:04 -0700706#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700707 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700708 config.Get<Intelligibility>().enabled) {
709 capture_nonlocked_.intelligibility_enabled =
710 config.Get<Intelligibility>().enabled;
711 InitializeIntelligibility();
712 }
peah1bcfce52016-08-26 07:16:04 -0700713#endif
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000714}
715
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000716int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800717 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700718 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000719}
720
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000721int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800722 // Used as callback from submodules, hence locking is not allowed.
723 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000724}
725
Peter Kasting69558702016-01-12 16:26:35 -0800726size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800727 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700728 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000729}
730
Peter Kasting69558702016-01-12 16:26:35 -0800731size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800732 // Used as callback from submodules, hence locking is not allowed.
733 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000734}
735
Peter Kasting69558702016-01-12 16:26:35 -0800736size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800737 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200738 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800739}
740
Peter Kasting69558702016-01-12 16:26:35 -0800741size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800742 // Used as callback from submodules, hence locking is not allowed.
743 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000746void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800747 rtc::CritScope cs(&crit_capture_);
748 capture_.output_will_be_muted = muted;
749 if (private_submodules_->agc_manager.get()) {
750 private_submodules_->agc_manager->SetCaptureMuted(
751 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000752 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000753}
754
Alessio Bazzicac054e782018-04-16 12:10:09 +0200755void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200756 switch (setting.type()) {
757 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
758 render_runtime_settings_enqueuer_.Enqueue(setting);
759 return;
760 case RuntimeSetting::Type::kNotSpecified:
761 RTC_NOTREACHED();
762 return;
763 case RuntimeSetting::Type::kCapturePreGain:
764 capture_runtime_settings_enqueuer_.Enqueue(setting);
765 return;
766 }
767 // The language allows the enum to have a non-enumerator
768 // value. Check that this doesn't happen.
769 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200770}
771
772AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
773 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200774 : runtime_settings_(*runtime_settings) {
775 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200776}
777
778AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
779 default;
780
781void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
782 RuntimeSetting setting) {
783 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200784 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200785 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200786 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200787 RTC_LOG(LS_ERROR)
788 << "The runtime settings queue is full. Oldest setting discarded.";
789 }
790 if (remaining_attempts == 0)
791 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
792}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000793
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000794int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700795 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000796 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000797 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000798 int output_sample_rate_hz,
799 ChannelLayout output_layout,
800 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800801 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800802 StreamConfig input_stream;
803 StreamConfig output_stream;
804 {
805 // Access the formats_.api_format.input_stream beneath the capture lock.
806 // The lock must be released as it is later required in the call
807 // to ProcessStream(,,,);
808 rtc::CritScope cs(&crit_capture_);
809 input_stream = formats_.api_format.input_stream();
810 output_stream = formats_.api_format.output_stream();
811 }
812
Michael Graczyk86c6d332015-07-23 11:41:39 -0700813 input_stream.set_sample_rate_hz(input_sample_rate_hz);
814 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
815 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700816 output_stream.set_sample_rate_hz(output_sample_rate_hz);
817 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
818 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
819
820 if (samples_per_channel != input_stream.num_frames()) {
821 return kBadDataLengthError;
822 }
823 return ProcessStream(src, input_stream, output_stream, dest);
824}
825
826int AudioProcessingImpl::ProcessStream(const float* const* src,
827 const StreamConfig& input_config,
828 const StreamConfig& output_config,
829 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800830 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800831 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700832 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800833 {
834 // Acquire the capture lock in order to safely call the function
835 // that retrieves the render side data. This function accesses apm
836 // getters that need the capture lock held when being called.
837 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700838 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800839
840 if (!src || !dest) {
841 return kNullPointerError;
842 }
843
844 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700845 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000846 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000847
Michael Graczyk86c6d332015-07-23 11:41:39 -0700848 processing_config.input_stream() = input_config;
849 processing_config.output_stream() = output_config;
850
peahdf3efa82015-11-28 12:35:15 -0800851 {
852 // Do conditional reinitialization.
853 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700854 RETURN_ON_ERR(
855 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800856 }
857 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700858 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
859 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000860
aleloi868f32f2017-05-23 07:20:05 -0700861 if (aec_dump_) {
862 RecordUnprocessedCaptureStream(src);
863 }
864
peahdf3efa82015-11-28 12:35:15 -0800865 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700866 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800867 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000868
aleloi868f32f2017-05-23 07:20:05 -0700869 if (aec_dump_) {
870 RecordProcessedCaptureStream(dest);
871 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000872 return kNoError;
873}
874
Alex Loiko73ec0192018-05-15 10:52:28 +0200875void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200876 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200877 while (capture_runtime_settings_.Remove(&setting)) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200878 switch (setting.type()) {
879 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200880 if (config_.pre_amplifier.enabled) {
881 float value;
882 setting.GetFloat(&value);
883 private_submodules_->pre_amplifier->SetGainFactor(value);
884 }
885 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200886 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200887 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
888 RTC_NOTREACHED();
889 break;
890 case RuntimeSetting::Type::kNotSpecified:
891 RTC_NOTREACHED();
892 break;
893 }
894 }
895}
896
897void AudioProcessingImpl::HandleRenderRuntimeSettings() {
898 RuntimeSetting setting;
899 while (render_runtime_settings_.Remove(&setting)) {
900 switch (setting.type()) {
901 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
902 if (private_submodules_->render_pre_processor) {
903 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
904 }
905 break;
906 case RuntimeSetting::Type::kCapturePreGain:
907 RTC_NOTREACHED();
908 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200909 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200910 RTC_NOTREACHED();
911 break;
912 }
913 }
914}
915
peah9e6a2902017-05-15 07:19:21 -0700916void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700917 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
918 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700919 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700920
kwibergaf476c72016-11-28 15:21:39 -0800921 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700922
923 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700924 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700925 // The data queue is full and needs to be emptied.
926 EmptyQueuedRenderAudio();
927
928 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700929 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700930 RTC_DCHECK(result);
931 }
932
933 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
934 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700935 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700936
937 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700938 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700939 // The data queue is full and needs to be emptied.
940 EmptyQueuedRenderAudio();
941
942 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700943 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700944 RTC_DCHECK(result);
945 }
peah701d6282016-10-25 05:42:20 -0700946
947 if (!constants_.use_experimental_agc) {
948 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
949 // Insert the samples into the queue.
950 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
951 // The data queue is full and needs to be emptied.
952 EmptyQueuedRenderAudio();
953
954 // Retry the insert (should always work).
955 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
956 RTC_DCHECK(result);
957 }
958 }
peah9e6a2902017-05-15 07:19:21 -0700959}
ivoc9f4a4a02016-10-28 05:39:16 -0700960
peah9e6a2902017-05-15 07:19:21 -0700961void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700962 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
963
964 // Insert the samples into the queue.
965 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
966 // The data queue is full and needs to be emptied.
967 EmptyQueuedRenderAudio();
968
969 // Retry the insert (should always work).
970 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
971 RTC_DCHECK(result);
972 }
peah764e3642016-10-22 05:04:30 -0700973}
974
975void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700976 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700977 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700978 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700979 EchoCancellationImpl::NumCancellersRequired(
980 num_output_channels(), num_reverse_channels()));
981
peah701d6282016-10-25 05:42:20 -0700982 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700983 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700984 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700985 EchoControlMobileImpl::NumCancellersRequired(
986 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700987
peah701d6282016-10-25 05:42:20 -0700988 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700989 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700990
ivoc9f4a4a02016-10-28 05:39:16 -0700991 const size_t new_red_render_queue_element_max_size =
992 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
993
peaha0624602016-10-25 04:45:24 -0700994 // Reallocate the queues if the queue item sizes are too small to fit the
995 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700996 if (aec_render_queue_element_max_size_ <
997 new_aec_render_queue_element_max_size) {
998 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700999
peaha0624602016-10-25 04:45:24 -07001000 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001001 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001002
peah701d6282016-10-25 05:42:20 -07001003 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001004 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1005 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001006 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001007 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001008
peah701d6282016-10-25 05:42:20 -07001009 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1010 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001011 } else {
peah701d6282016-10-25 05:42:20 -07001012 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001013 }
1014
peah701d6282016-10-25 05:42:20 -07001015 if (aecm_render_queue_element_max_size_ <
1016 new_aecm_render_queue_element_max_size) {
1017 aecm_render_queue_element_max_size_ =
1018 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001019
1020 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001021 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001022
peah701d6282016-10-25 05:42:20 -07001023 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001024 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1025 kMaxNumFramesToBuffer, template_queue_element,
1026 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001027 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001028
peah701d6282016-10-25 05:42:20 -07001029 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1030 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001031 } else {
peah701d6282016-10-25 05:42:20 -07001032 aecm_render_signal_queue_->Clear();
1033 }
1034
1035 if (agc_render_queue_element_max_size_ <
1036 new_agc_render_queue_element_max_size) {
1037 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1038
1039 std::vector<int16_t> template_queue_element(
1040 agc_render_queue_element_max_size_);
1041
1042 agc_render_signal_queue_.reset(
1043 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1044 kMaxNumFramesToBuffer, template_queue_element,
1045 RenderQueueItemVerifier<int16_t>(
1046 agc_render_queue_element_max_size_)));
1047
1048 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1049 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1050 } else {
1051 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001052 }
ivoc9f4a4a02016-10-28 05:39:16 -07001053
1054 if (red_render_queue_element_max_size_ <
1055 new_red_render_queue_element_max_size) {
1056 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1057
1058 std::vector<float> template_queue_element(
1059 red_render_queue_element_max_size_);
1060
1061 red_render_signal_queue_.reset(
1062 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1063 kMaxNumFramesToBuffer, template_queue_element,
1064 RenderQueueItemVerifier<float>(
1065 red_render_queue_element_max_size_)));
1066
1067 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1068 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1069 } else {
1070 red_render_signal_queue_->Clear();
1071 }
peah764e3642016-10-22 05:04:30 -07001072}
1073
1074void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1075 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001076 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001077 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001078 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001079 }
1080
peah701d6282016-10-25 05:42:20 -07001081 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001082 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001083 aecm_capture_queue_buffer_);
1084 }
1085
1086 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1087 public_submodules_->gain_control->ProcessRenderAudio(
1088 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001089 }
ivoc9f4a4a02016-10-28 05:39:16 -07001090
1091 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001092 RTC_DCHECK(private_submodules_->echo_detector);
1093 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001094 red_capture_queue_buffer_);
1095 }
peah764e3642016-10-22 05:04:30 -07001096}
1097
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001098int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001099 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001100 {
1101 // Acquire the capture lock in order to safely call the function
1102 // that retrieves the render side data. This function accesses apm
1103 // getters that need the capture lock held when being called.
1104 // The lock needs to be released as
1105 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1106 // as well.
1107 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001108 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001109 }
peahfa6228e2015-11-16 16:27:42 -08001110
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001111 if (!frame) {
1112 return kNullPointerError;
1113 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001114 // Must be a native rate.
1115 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1116 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001117 frame->sample_rate_hz_ != kSampleRate32kHz &&
1118 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001119 return kBadSampleRateError;
1120 }
peah192164e2015-11-17 02:16:45 -08001121
peahdf3efa82015-11-28 12:35:15 -08001122 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001123 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001124 {
1125 // Aquire lock for the access of api_format.
1126 // The lock is released immediately due to the conditional
1127 // reinitialization.
1128 rtc::CritScope cs_capture(&crit_capture_);
1129 // TODO(ajm): The input and output rates and channels are currently
1130 // constrained to be identical in the int16 interface.
1131 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001132
1133 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001134 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001135 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1136 processing_config.input_stream().set_num_channels(frame->num_channels_);
1137 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1138 processing_config.output_stream().set_num_channels(frame->num_channels_);
1139
peahdf3efa82015-11-28 12:35:15 -08001140 {
1141 // Do conditional reinitialization.
1142 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001143 RETURN_ON_ERR(
1144 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001145 }
1146 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001147 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001148 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001149 return kBadDataLengthError;
1150 }
1151
aleloi868f32f2017-05-23 07:20:05 -07001152 if (aec_dump_) {
1153 RecordUnprocessedCaptureStream(*frame);
1154 }
1155
peahdf3efa82015-11-28 12:35:15 -08001156 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001157 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001158 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001159 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1160 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001161
aleloi868f32f2017-05-23 07:20:05 -07001162 if (aec_dump_) {
1163 RecordProcessedCaptureStream(*frame);
1164 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001165
1166 return kNoError;
1167}
1168
peahde65ddc2016-09-16 15:02:15 -07001169int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001170 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001171
peahb58a1582016-03-15 09:34:24 -07001172 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001173 // TODO(peah): Simplify once the public API Enable functions for these
1174 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001175 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1176 public_submodules_->echo_control_mobile->is_enabled()));
1177
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001178 MaybeUpdateHistograms();
1179
peahde65ddc2016-09-16 15:02:15 -07001180 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001181
Alex Loikob5c9a792018-04-16 16:31:22 +02001182 if (private_submodules_->pre_amplifier) {
1183 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1184 capture_buffer->channels_f(), capture_buffer->num_channels(),
1185 capture_buffer->num_frames()));
1186 }
1187
peah1b08dc32016-12-20 13:45:58 -08001188 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001189 capture_buffer->channels_const()[0],
1190 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001191 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1192 if (log_rms) {
1193 capture_rms_interval_counter_ = 0;
1194 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001195 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1196 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1197 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1198 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001199 }
1200
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001201 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001202 // Detect and flag any change in the analog gain.
1203 int analog_mic_level = gain_control()->stream_analog_level();
1204 capture_.echo_path_gain_change =
1205 capture_.prev_analog_mic_level != analog_mic_level &&
1206 capture_.prev_analog_mic_level != -1;
1207 capture_.prev_analog_mic_level = analog_mic_level;
1208
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001209 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001210 }
1211
peahbe615622016-02-13 16:40:47 -08001212 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001213 public_submodules_->gain_control->is_enabled()) {
1214 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001215 capture_buffer->channels()[0], capture_buffer->num_channels(),
1216 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001217 }
1218
peah2ace3f92016-09-10 04:42:27 -07001219 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1220 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001221 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1222 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001223 }
1224
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001225 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001226 // Force down-mixing of the number of channels after the detection of
1227 // capture signal saturation.
1228 // TODO(peah): Look into ensuring that this kind of tampering with the
1229 // AudioBuffer functionality should not be needed.
1230 capture_buffer->set_num_channels(1);
1231 }
1232
peahe0eae3c2016-12-14 01:16:23 -08001233 // TODO(peah): Move the AEC3 low-cut filter to this place.
1234 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001235 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001236 private_submodules_->low_cut_filter->Process(capture_buffer);
1237 }
peahde65ddc2016-09-16 15:02:15 -07001238 RETURN_ON_ERR(
1239 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1240 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001241
1242 // Ensure that the stream delay was set before the call to the
1243 // AEC ProcessCaptureAudio function.
1244 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001245 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001246 return AudioProcessing::kStreamParameterNotSetError;
1247 }
1248
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001249 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001250 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1251
Per Åhgrend0fa8202018-04-18 09:35:13 +02001252 if (was_stream_delay_set()) {
1253 private_submodules_->echo_controller->SetAudioBufferDelay(
1254 stream_delay_ms());
1255 }
1256
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001257 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001258 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001259 } else {
1260 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1261 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001262 }
1263
peahdf3efa82015-11-28 12:35:15 -08001264 if (public_submodules_->echo_control_mobile->is_enabled() &&
1265 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001266 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001267 }
peahde65ddc2016-09-16 15:02:15 -07001268 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001269#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001270 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001271 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Sam Zackrissonab1aee02018-03-05 15:59:06 +01001272 const int gain_db =
1273 public_submodules_->gain_control->is_enabled()
1274 ? public_submodules_->gain_control->compression_gain_db()
1275 : 0;
1276 const float gain = DbToRatio(gain_db);
aluebsc466bad2016-02-10 12:03:00 -08001277 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001278 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001279 }
peah1bcfce52016-08-26 07:16:04 -07001280#endif
peah253534d2016-03-15 04:32:28 -07001281
1282 // Ensure that the stream delay was set before the call to the
1283 // AECM ProcessCaptureAudio function.
1284 if (public_submodules_->echo_control_mobile->is_enabled() &&
1285 !was_stream_delay_set()) {
1286 return AudioProcessing::kStreamParameterNotSetError;
1287 }
1288
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001289 if (!(private_submodules_->echo_controller ||
1290 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001291 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1292 capture_buffer, stream_delay_ms()));
1293 }
ivoc9f4a4a02016-10-28 05:39:16 -07001294
peahde65ddc2016-09-16 15:02:15 -07001295 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001296
peahbe615622016-02-13 16:40:47 -08001297 if (constants_.use_experimental_agc &&
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001298 public_submodules_->gain_control->is_enabled()) {
peahdf3efa82015-11-28 12:35:15 -08001299 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001300 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1301 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001302 }
peahb8fbb542016-03-15 02:28:08 -07001303 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001304 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001305
peah2ace3f92016-09-10 04:42:27 -07001306 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1307 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001308 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1309 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001310 }
1311
peah9e6a2902017-05-15 07:19:21 -07001312 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001313 RTC_DCHECK(private_submodules_->echo_detector);
1314 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001315 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1316 capture_buffer->num_frames()));
1317 }
1318
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001319 // TODO(aluebs): Investigate if the transient suppression placement should be
1320 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001321 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001322 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001323 private_submodules_->agc_manager.get()
1324 ? private_submodules_->agc_manager->voice_probability()
1325 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001326
peahdf3efa82015-11-28 12:35:15 -08001327 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001328 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1329 capture_buffer->num_channels(),
1330 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1331 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1332 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001333 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001334 }
1335
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001336 if (config_.gain_controller2.enabled) {
alessiob3ec96df2017-05-22 06:57:06 -07001337 private_submodules_->gain_controller2->Process(capture_buffer);
1338 }
1339
Sam Zackrisson0beac582017-09-25 12:04:02 +02001340 if (private_submodules_->capture_post_processor) {
1341 private_submodules_->capture_post_processor->Process(capture_buffer);
1342 }
1343
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001344 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001345 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001346
peah1b08dc32016-12-20 13:45:58 -08001347 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1348 capture_buffer->channels_const()[0],
1349 capture_nonlocked_.capture_processing_format.num_frames()));
1350 if (log_rms) {
1351 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1352 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1353 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1354 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1355 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1356 }
1357
peahdf3efa82015-11-28 12:35:15 -08001358 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001359 return kNoError;
1360}
1361
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001362int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001363 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001364 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001365 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001366 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001367 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001368 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001369 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001370 };
1371 if (samples_per_channel != reverse_config.num_frames()) {
1372 return kBadDataLengthError;
1373 }
peahdf3efa82015-11-28 12:35:15 -08001374 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001375}
1376
peahde65ddc2016-09-16 15:02:15 -07001377int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1378 const StreamConfig& input_config,
1379 const StreamConfig& output_config,
1380 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001381 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001382 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001383 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001384 if (submodule_states_.RenderMultiBandProcessingActive() ||
1385 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001386 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1387 dest);
peah2ace3f92016-09-10 04:42:27 -07001388 } else if (formats_.api_format.reverse_input_stream() !=
1389 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001390 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1391 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001392 } else {
peahde65ddc2016-09-16 15:02:15 -07001393 CopyAudioIfNeeded(src, input_config.num_frames(),
1394 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001395 }
1396
1397 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001398}
1399
peahdf3efa82015-11-28 12:35:15 -08001400int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001401 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001402 const StreamConfig& input_config,
1403 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001404 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001405 return kNullPointerError;
1406 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001407
peahde65ddc2016-09-16 15:02:15 -07001408 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001409 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001410 }
1411
peahdf3efa82015-11-28 12:35:15 -08001412 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001413 processing_config.reverse_input_stream() = input_config;
1414 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001415
peahdf3efa82015-11-28 12:35:15 -08001416 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001417 RTC_DCHECK_EQ(input_config.num_frames(),
1418 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001419
aleloi868f32f2017-05-23 07:20:05 -07001420 if (aec_dump_) {
1421 const size_t channel_size =
1422 formats_.api_format.reverse_input_stream().num_frames();
1423 const size_t num_channels =
1424 formats_.api_format.reverse_input_stream().num_channels();
1425 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001426 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001427 }
peahdf3efa82015-11-28 12:35:15 -08001428 render_.render_audio->CopyFrom(src,
1429 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001430 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001431}
1432
1433int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001434 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001435 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001436 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001437 return kNullPointerError;
1438 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001439 // Must be a native rate.
1440 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1441 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001442 frame->sample_rate_hz_ != kSampleRate32kHz &&
1443 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001444 return kBadSampleRateError;
1445 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001446
Michael Graczyk86c6d332015-07-23 11:41:39 -07001447 if (frame->num_channels_ <= 0) {
1448 return kBadNumberChannelsError;
1449 }
1450
peahdf3efa82015-11-28 12:35:15 -08001451 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001452 processing_config.reverse_input_stream().set_sample_rate_hz(
1453 frame->sample_rate_hz_);
1454 processing_config.reverse_input_stream().set_num_channels(
1455 frame->num_channels_);
1456 processing_config.reverse_output_stream().set_sample_rate_hz(
1457 frame->sample_rate_hz_);
1458 processing_config.reverse_output_stream().set_num_channels(
1459 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001460
peahdf3efa82015-11-28 12:35:15 -08001461 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001462 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001463 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001464 return kBadDataLengthError;
1465 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001466
aleloi868f32f2017-05-23 07:20:05 -07001467 if (aec_dump_) {
1468 aec_dump_->WriteRenderStreamMessage(*frame);
1469 }
1470
peahdf3efa82015-11-28 12:35:15 -08001471 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001472 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001473 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001474 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1475 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001476 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001477}
niklase@google.com470e71d2011-07-07 08:21:25 +00001478
peahde65ddc2016-09-16 15:02:15 -07001479int AudioProcessingImpl::ProcessRenderStreamLocked() {
1480 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001481
1482 QueueNonbandedRenderAudio(render_buffer);
1483
Alex Loiko73ec0192018-05-15 10:52:28 +02001484 HandleRenderRuntimeSettings();
1485
Alex Loiko5825aa62017-12-18 16:02:40 +01001486 if (private_submodules_->render_pre_processor) {
1487 private_submodules_->render_pre_processor->Process(render_buffer);
1488 }
1489
peah2ace3f92016-09-10 04:42:27 -07001490 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001491 SampleRateSupportsMultiBand(
1492 formats_.render_processing_format.sample_rate_hz())) {
1493 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001494 }
1495
peah1bcfce52016-08-26 07:16:04 -07001496#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001497 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001498 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001499 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001500 }
peah1bcfce52016-08-26 07:16:04 -07001501#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001502
peahce4d9152017-05-19 01:28:05 -07001503 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1504 QueueBandedRenderAudio(render_buffer);
1505 }
1506
peahe0eae3c2016-12-14 01:16:23 -08001507 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001508 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001509 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001510 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001511
peah2ace3f92016-09-10 04:42:27 -07001512 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001513 SampleRateSupportsMultiBand(
1514 formats_.render_processing_format.sample_rate_hz())) {
1515 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001516 }
1517
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001518 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001519}
1520
1521int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001522 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001523 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001524 capture_.was_stream_delay_set = true;
1525 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001526
niklase@google.com470e71d2011-07-07 08:21:25 +00001527 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001528 delay = 0;
1529 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001530 }
1531
1532 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1533 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001534 delay = 500;
1535 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001536 }
1537
peahdf3efa82015-11-28 12:35:15 -08001538 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001539 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001540}
1541
1542int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001543 // Used as callback from submodules, hence locking is not allowed.
1544 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001545}
1546
1547bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001548 // Used as callback from submodules, hence locking is not allowed.
1549 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001550}
1551
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001552void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001553 rtc::CritScope cs(&crit_capture_);
1554 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001555}
1556
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001557void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001558 rtc::CritScope cs(&crit_capture_);
1559 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001560}
1561
1562int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001563 rtc::CritScope cs(&crit_capture_);
1564 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001565}
1566
aleloi868f32f2017-05-23 07:20:05 -07001567void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1568 RTC_DCHECK(aec_dump);
1569 rtc::CritScope cs_render(&crit_render_);
1570 rtc::CritScope cs_capture(&crit_capture_);
1571
1572 // The previously attached AecDump will be destroyed with the
1573 // 'aec_dump' parameter, which is after locks are released.
1574 aec_dump_.swap(aec_dump);
1575 WriteAecDumpConfigMessage(true);
Alex Loiko1aec5942018-05-15 13:13:22 +02001576 aec_dump_->WriteInitMessage(formats_.api_format);
aleloi868f32f2017-05-23 07:20:05 -07001577}
1578
1579void AudioProcessingImpl::DetachAecDump() {
1580 // The d-tor of a task-queue based AecDump blocks until all pending
1581 // tasks are done. This construction avoids blocking while holding
1582 // the render and capture locks.
1583 std::unique_ptr<AecDump> aec_dump = nullptr;
1584 {
1585 rtc::CritScope cs_render(&crit_render_);
1586 rtc::CritScope cs_capture(&crit_capture_);
1587 aec_dump = std::move(aec_dump_);
1588 }
1589}
1590
Sam Zackrisson4d364492018-03-02 16:03:21 +01001591void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1592 std::unique_ptr<AudioGenerator> audio_generator) {
1593 // TODO(bugs.webrtc.org/8882) Stub.
1594 // Reset internal audio generator with audio_generator.
1595}
1596
1597void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1598 // TODO(bugs.webrtc.org/8882) Stub.
1599 // Delete audio generator, if one is attached.
1600}
1601
ivoc4e477a12017-01-15 08:29:46 -08001602AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1603 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1604 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1605 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1606 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1607}
1608
1609AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1610 const AudioProcessingStatistics& other) = default;
1611
1612AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1613 default;
1614
ivoc3e9a5372016-10-28 07:55:33 -07001615// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1616AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1617 const {
1618 return AudioProcessingStatistics();
1619}
1620
Ivo Creusenae026092017-11-20 13:07:16 +01001621// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001622AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001623 bool has_remote_tracks) const {
1624 return AudioProcessingStats();
1625}
1626
ivoc3e9a5372016-10-28 07:55:33 -07001627AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1628 const {
1629 AudioProcessingStatistics stats;
1630 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001631 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001632 rtc::CritScope cs_capture(&crit_capture_);
1633 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1634 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1635 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1636 // Instant value will also be used for min, max and average.
1637 stats.echo_return_loss.Set(erl, erl, erl, erl);
1638 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1639 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1640 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001641 stats.a_nlp.Set(metrics.a_nlp);
1642 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1643 stats.echo_return_loss.Set(metrics.echo_return_loss);
1644 stats.echo_return_loss_enhancement.Set(
1645 metrics.echo_return_loss_enhancement);
1646 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1647 }
ivoc9c192b22017-03-16 04:22:14 -07001648 {
1649 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001650 RTC_DCHECK(private_submodules_->echo_detector);
1651 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1652 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001653 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001654 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001655 }
ivoc3e9a5372016-10-28 07:55:33 -07001656 public_submodules_->echo_cancellation->GetDelayMetrics(
1657 &stats.delay_median, &stats.delay_standard_deviation,
1658 &stats.fraction_poor_delays);
1659 return stats;
1660}
1661
Ivo Creusen56d46092017-11-24 17:29:59 +01001662AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001663 bool has_remote_tracks) const {
1664 AudioProcessingStats stats;
1665 if (has_remote_tracks) {
1666 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001667 if (private_submodules_->echo_controller) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001668 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001669 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1670 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001671 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001672 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001673 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001674 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1675 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001676 if (metrics.divergent_filter_fraction != -1.0f) {
1677 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001678 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001679 }
1680 if (metrics.echo_return_loss.instant != -100) {
1681 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001682 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001683 }
1684 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001685 stats.echo_return_loss_enhancement = absl::optional<double>(
1686 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001687 }
1688 }
1689 if (config_.residual_echo_detector.enabled) {
1690 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001691 RTC_DCHECK(private_submodules_->echo_detector);
1692 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1693 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001694 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001695 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001696 }
1697 int delay_median, delay_std;
1698 float fraction_poor_delays;
1699 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1700 &delay_median, &delay_std, &fraction_poor_delays) ==
1701 Error::kNoError) {
1702 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001703 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001704 }
1705 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001706 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001707 }
1708 }
1709 }
1710 return stats;
1711}
1712
niklase@google.com470e71d2011-07-07 08:21:25 +00001713EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001714 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001715}
1716
1717EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001718 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001719}
1720
1721GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001722 if (constants_.use_experimental_agc) {
1723 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001724 }
peahbfa97112016-03-10 21:09:04 -08001725 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001726}
1727
1728HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001729 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001730}
1731
1732LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001733 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001734}
1735
1736NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001737 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001738}
1739
1740VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001741 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
peah8271d042016-11-22 07:24:52 -08001744void AudioProcessingImpl::MutateConfig(
1745 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1746 rtc::CritScope cs_render(&crit_render_);
1747 rtc::CritScope cs_capture(&crit_capture_);
1748 mutator(&config_);
1749 ApplyConfig(config_);
1750}
1751
1752AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1753 rtc::CritScope cs_render(&crit_render_);
1754 rtc::CritScope cs_capture(&crit_capture_);
1755 return config_;
1756}
1757
peah2ace3f92016-09-10 04:42:27 -07001758bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1759 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001760 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001761 public_submodules_->echo_cancellation->is_enabled(),
1762 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001763 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001764 public_submodules_->noise_suppression->is_enabled(),
1765 capture_nonlocked_.intelligibility_enabled,
peah2ace3f92016-09-10 04:42:27 -07001766 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001767 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001768 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001769 public_submodules_->voice_detection->is_enabled(),
1770 public_submodules_->level_estimator->is_enabled(),
1771 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001772}
1773
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001774
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001775void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001776 if (capture_.transient_suppressor_enabled) {
1777 if (!public_submodules_->transient_suppressor.get()) {
1778 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001779 }
peahdf3efa82015-11-28 12:35:15 -08001780 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001781 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1782 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001783 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001784}
1785
ekmeyerson60d9b332015-08-14 10:35:55 -07001786void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001787#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001788 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001789 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001790 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001791 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001792 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001793 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001794 }
peah1bcfce52016-08-26 07:16:04 -07001795#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001796}
1797
peah8271d042016-11-22 07:24:52 -08001798void AudioProcessingImpl::InitializeLowCutFilter() {
1799 if (config_.high_pass_filter.enabled) {
1800 private_submodules_->low_cut_filter.reset(
1801 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1802 } else {
1803 private_submodules_->low_cut_filter.reset();
1804 }
1805}
alessiob3ec96df2017-05-22 06:57:06 -07001806
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001807void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001808 if (echo_control_factory_) {
1809 private_submodules_->echo_controller =
1810 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001811 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001812 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001813 }
1814}
peah8271d042016-11-22 07:24:52 -08001815
alessiob3ec96df2017-05-22 06:57:06 -07001816void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001817 if (config_.gain_controller2.enabled) {
1818 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001819 }
1820}
1821
Alex Loikob5c9a792018-04-16 16:31:22 +02001822void AudioProcessingImpl::InitializePreAmplifier() {
1823 if (config_.pre_amplifier.enabled) {
1824 private_submodules_->pre_amplifier.reset(
1825 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1826 } else {
1827 private_submodules_->pre_amplifier.reset();
1828 }
1829}
1830
ivoc9f4a4a02016-10-28 05:39:16 -07001831void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001832 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001833 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001834 proc_sample_rate_hz(), 1,
1835 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001836}
1837
Sam Zackrisson0beac582017-09-25 12:04:02 +02001838void AudioProcessingImpl::InitializePostProcessor() {
1839 if (private_submodules_->capture_post_processor) {
1840 private_submodules_->capture_post_processor->Initialize(
1841 proc_sample_rate_hz(), num_proc_channels());
1842 }
1843}
1844
Alex Loiko5825aa62017-12-18 16:02:40 +01001845void AudioProcessingImpl::InitializePreProcessor() {
1846 if (private_submodules_->render_pre_processor) {
1847 private_submodules_->render_pre_processor->Initialize(
1848 formats_.render_processing_format.sample_rate_hz(),
1849 formats_.render_processing_format.num_channels());
1850 }
1851}
1852
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001853void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001854 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001855
1856 if (echo_cancellation()->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001857 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1858 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001859 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001860 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001861 capture_.stream_delay_jumps = 0;
1862 }
1863 if (capture_.aec_system_delay_jumps == -1 &&
1864 echo_cancellation()->stream_has_echo()) {
1865 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001866 }
1867
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001868 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001869 const int diff_stream_delay_ms =
1870 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1871 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1872 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001873 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1874 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001875 if (capture_.stream_delay_jumps == -1) {
1876 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001877 }
peahdf3efa82015-11-28 12:35:15 -08001878 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001879 }
peahdf3efa82015-11-28 12:35:15 -08001880 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001881
1882 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001883 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001884 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001885 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001886 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001887 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1888 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001889 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001890 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001891 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001892 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001893 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1894 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1895 100);
peahdf3efa82015-11-28 12:35:15 -08001896 if (capture_.aec_system_delay_jumps == -1) {
1897 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001898 }
peahdf3efa82015-11-28 12:35:15 -08001899 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001900 }
peahdf3efa82015-11-28 12:35:15 -08001901 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001902 }
1903}
1904
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001905void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001906 // Run in a single-threaded manner.
1907 rtc::CritScope cs_render(&crit_render_);
1908 rtc::CritScope cs_capture(&crit_capture_);
1909
1910 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001911 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001912 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001913 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001914 }
peahdf3efa82015-11-28 12:35:15 -08001915 capture_.stream_delay_jumps = -1;
1916 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001917
peahdf3efa82015-11-28 12:35:15 -08001918 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001919 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1920 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001921 }
peahdf3efa82015-11-28 12:35:15 -08001922 capture_.aec_system_delay_jumps = -1;
1923 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001924}
1925
aleloi868f32f2017-05-23 07:20:05 -07001926void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1927 if (!aec_dump_) {
1928 return;
1929 }
1930 std::string experiments_description =
1931 public_submodules_->echo_cancellation->GetExperimentsDescription();
1932 // TODO(peah): Add semicolon-separated concatenations of experiment
1933 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001934 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1935 experiments_description += "AgcClippingLevelExperiment;";
1936 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001937 if (capture_nonlocked_.echo_controller_enabled) {
1938 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001939 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001940 if (config_.gain_controller2.enabled) {
1941 experiments_description += "GainController2;";
1942 }
aleloi868f32f2017-05-23 07:20:05 -07001943
1944 InternalAPMConfig apm_config;
1945
1946 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1947 apm_config.aec_delay_agnostic_enabled =
1948 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1949 apm_config.aec_drift_compensation_enabled =
1950 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1951 apm_config.aec_extended_filter_enabled =
1952 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1953 apm_config.aec_suppression_level = static_cast<int>(
1954 public_submodules_->echo_cancellation->suppression_level());
1955
1956 apm_config.aecm_enabled =
1957 public_submodules_->echo_control_mobile->is_enabled();
1958 apm_config.aecm_comfort_noise_enabled =
1959 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1960 apm_config.aecm_routing_mode =
1961 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1962
1963 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1964 apm_config.agc_mode =
1965 static_cast<int>(public_submodules_->gain_control->mode());
1966 apm_config.agc_limiter_enabled =
1967 public_submodules_->gain_control->is_limiter_enabled();
1968 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1969
1970 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1971
1972 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1973 apm_config.ns_level =
1974 static_cast<int>(public_submodules_->noise_suppression->level());
1975
1976 apm_config.transient_suppression_enabled =
1977 capture_.transient_suppressor_enabled;
1978 apm_config.intelligibility_enhancer_enabled =
1979 capture_nonlocked_.intelligibility_enabled;
1980 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001981 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1982 apm_config.pre_amplifier_fixed_gain_factor =
1983 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001984
1985 if (!forced && apm_config == apm_config_for_aec_dump_) {
1986 return;
1987 }
1988 aec_dump_->WriteConfig(apm_config);
1989 apm_config_for_aec_dump_ = apm_config;
1990}
1991
1992void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1993 const float* const* src) {
1994 RTC_DCHECK(aec_dump_);
1995 WriteAecDumpConfigMessage(false);
1996
1997 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1998 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1999 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002000 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002001 RecordAudioProcessingState();
2002}
2003
2004void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2005 const AudioFrame& capture_frame) {
2006 RTC_DCHECK(aec_dump_);
2007 WriteAecDumpConfigMessage(false);
2008
2009 aec_dump_->AddCaptureStreamInput(capture_frame);
2010 RecordAudioProcessingState();
2011}
2012
2013void AudioProcessingImpl::RecordProcessedCaptureStream(
2014 const float* const* processed_capture_stream) {
2015 RTC_DCHECK(aec_dump_);
2016
2017 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2018 const size_t num_channels =
2019 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002020 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2021 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002022 aec_dump_->WriteCaptureStreamMessage();
2023}
2024
2025void AudioProcessingImpl::RecordProcessedCaptureStream(
2026 const AudioFrame& processed_capture_frame) {
2027 RTC_DCHECK(aec_dump_);
2028
2029 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2030 aec_dump_->WriteCaptureStreamMessage();
2031}
2032
2033void AudioProcessingImpl::RecordAudioProcessingState() {
2034 RTC_DCHECK(aec_dump_);
2035 AecDump::AudioProcessingState audio_proc_state;
2036 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2037 audio_proc_state.drift =
2038 public_submodules_->echo_cancellation->stream_drift_samples();
2039 audio_proc_state.level = gain_control()->stream_analog_level();
2040 audio_proc_state.keypress = capture_.key_pressed;
2041 aec_dump_->AddAudioProcessingState(audio_proc_state);
2042}
2043
kwiberg83ffe452016-08-29 14:46:07 -07002044AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002045 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002046 : aec_system_delay_jumps(-1),
2047 delay_offset_ms(0),
2048 was_stream_delay_set(false),
2049 last_stream_delay_ms(0),
2050 last_aec_system_delay_ms(0),
2051 stream_delay_jumps(-1),
2052 output_will_be_muted(false),
2053 key_pressed(false),
2054 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002055 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002056 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002057 echo_path_gain_change(false),
2058 prev_analog_mic_level(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002059
2060AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2061
2062AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2063
2064AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2065
niklase@google.com470e71d2011-07-07 08:21:25 +00002066} // namespace webrtc