blob: d5bb04696411212a5a0a97e4b3d6d09572908617 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/common.h"
26#include "modules/audio_processing/echo_cancellation_impl.h"
Sam Zackrisson74ed7342018-08-16 10:54:07 +020027#include "modules/audio_processing/echo_cancellation_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/echo_control_mobile_impl.h"
Sam Zackrisson74ed7342018-08-16 10:54:07 +020029#include "modules/audio_processing/echo_control_mobile_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "modules/audio_processing/gain_control_for_experimental_agc.h"
31#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010032#include "modules/audio_processing/gain_controller2.h"
Per Åhgren13735822018-02-12 21:42:56 +010033#include "modules/audio_processing/logging/apm_data_dumper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/checks.h"
35#include "rtc_base/logging.h"
36#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020037#include "rtc_base/refcountedobject.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020038#include "rtc_base/system/arch.h"
Minyue Li656d6092018-08-10 15:38:52 +020039#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/trace_event.h"
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
Michael Graczyk86c6d332015-07-23 11:41:39 -070050#define RETURN_ON_ERR(expr) \
51 do { \
52 int err = (expr); \
53 if (err != kNoError) { \
54 return err; \
55 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000056 } while (0)
57
niklase@google.com470e71d2011-07-07 08:21:25 +000058namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070059
kwibergd59d3bb2016-09-13 07:49:33 -070060constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020061constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070062
Michael Graczyk86c6d332015-07-23 11:41:39 -070063namespace {
64
65static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
66 switch (layout) {
67 case AudioProcessing::kMono:
68 case AudioProcessing::kStereo:
69 return false;
70 case AudioProcessing::kMonoAndKeyboard:
71 case AudioProcessing::kStereoAndKeyboard:
72 return true;
73 }
74
kwiberg9e2be5f2016-09-14 05:23:22 -070075 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070076 return false;
77}
aluebsdf6416a2016-03-16 18:26:35 -070078
peah2ace3f92016-09-10 04:42:27 -070079bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070080 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
81 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
82}
83
peah2ace3f92016-09-10 04:42:27 -070084int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
85#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070086 constexpr int kMaxSplittingNativeProcessRate =
87 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070088#else
kwibergd59d3bb2016-09-13 07:49:33 -070089 constexpr int kMaxSplittingNativeProcessRate =
90 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070091#endif
kwibergd59d3bb2016-09-13 07:49:33 -070092 static_assert(
93 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
94 "");
peah2ace3f92016-09-10 04:42:27 -070095 const int uppermost_native_rate = band_splitting_required
96 ? kMaxSplittingNativeProcessRate
97 : AudioProcessing::kSampleRate48kHz;
98
99 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
100 if (rate >= uppermost_native_rate) {
101 return uppermost_native_rate;
102 }
103 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700104 return rate;
105 }
106 }
peah2ace3f92016-09-10 04:42:27 -0700107 RTC_NOTREACHED();
108 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700109}
110
peah9e6a2902017-05-15 07:19:21 -0700111// Maximum lengths that frame of samples being passed from the render side to
112// the capture side can have (does not apply to AEC3).
113static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
114static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
115
peah764e3642016-10-22 05:04:30 -0700116// Maximum number of frames to buffer in the render queue.
117// TODO(peah): Decrease this once we properly handle hugely unbalanced
118// reverse and forward call numbers.
119static const size_t kMaxNumFramesToBuffer = 100;
120
peah8271d042016-11-22 07:24:52 -0800121class HighPassFilterImpl : public HighPassFilter {
122 public:
123 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
124 ~HighPassFilterImpl() override = default;
125
126 // HighPassFilter implementation.
127 int Enable(bool enable) override {
128 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
129 config->high_pass_filter.enabled = enable;
130 });
131
132 return AudioProcessing::kNoError;
133 }
134
135 bool is_enabled() const override {
136 return apm_->GetConfig().high_pass_filter.enabled;
137 }
138
139 private:
140 AudioProcessingImpl* apm_;
141 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
142};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700143} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000144
145// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000146static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000147
Sam Zackrisson0beac582017-09-25 12:04:02 +0200148AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100149 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200150 bool render_pre_processor_enabled,
151 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100152 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200153 render_pre_processor_enabled_(render_pre_processor_enabled),
154 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700155
156bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800157 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700158 bool echo_canceller_enabled,
159 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700160 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700161 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700162 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700163 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200164 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200165 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool voice_activity_detector_enabled,
167 bool level_estimator_enabled,
168 bool transient_suppressor_enabled) {
169 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800170 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700171 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
172 changed |=
173 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700174 changed |=
175 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700176 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
177 changed |=
peah2ace3f92016-09-10 04:42:27 -0700178 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700179 changed |=
180 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200181 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200182 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700183 changed |= (level_estimator_enabled != level_estimator_enabled_);
184 changed |=
185 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
186 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
187 if (changed) {
peah8271d042016-11-22 07:24:52 -0800188 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700189 echo_canceller_enabled_ = echo_canceller_enabled;
190 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700191 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700192 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700193 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700194 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200195 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200196 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700197 level_estimator_enabled_ = level_estimator_enabled;
198 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
199 transient_suppressor_enabled_ = transient_suppressor_enabled;
200 }
201
202 changed |= first_update_;
203 first_update_ = false;
204 return changed;
205}
206
207bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
208 const {
peah52775842017-05-16 06:14:09 -0700209 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700210}
211
212bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
213 const {
peah8271d042016-11-22 07:24:52 -0800214 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700215 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200216 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700217}
218
peah23ac8b42017-05-23 05:33:56 -0700219bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
220 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200221 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
222 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700223}
224
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200225bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
226 return capture_analyzer_enabled_;
227}
228
peah2ace3f92016-09-10 04:42:27 -0700229bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
230 const {
231 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800232 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200233 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700234}
235
Alex Loiko5825aa62017-12-18 16:02:40 +0100236bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
237 const {
238 return render_pre_processor_enabled_;
239}
240
peah2ace3f92016-09-10 04:42:27 -0700241bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
242 const {
peah2ace3f92016-09-10 04:42:27 -0700243 return false;
peah2ace3f92016-09-10 04:42:27 -0700244}
245
solenberg5e465c32015-12-08 13:22:33 -0800246struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800247 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800248 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800249 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800250 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Sam Zackrisson74ed7342018-08-16 10:54:07 +0200251 std::unique_ptr<EchoCancellationProxy> echo_cancellation_proxy;
252 std::unique_ptr<EchoControlMobileProxy> echo_control_mobile_proxy;
peahbfa97112016-03-10 21:09:04 -0800253 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800254 std::unique_ptr<LevelEstimatorImpl> level_estimator;
255 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
256 std::unique_ptr<VoiceDetectionImpl> voice_detection;
257 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800258 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800259
260 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800261 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800262};
263
264struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200265 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100266 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200267 rtc::scoped_refptr<EchoDetector> echo_detector,
268 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200269 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100270 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200271 render_pre_processor(std::move(render_pre_processor)),
272 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800273 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800274 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700275 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800276 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200277 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200278 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100279 std::unique_ptr<CustomProcessing> capture_post_processor;
280 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200281 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200282 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
solenberg5e465c32015-12-08 13:22:33 -0800283};
284
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100285AudioProcessingBuilder::AudioProcessingBuilder() = default;
286AudioProcessingBuilder::~AudioProcessingBuilder() = default;
287
288AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
289 std::unique_ptr<CustomProcessing> capture_post_processing) {
290 capture_post_processing_ = std::move(capture_post_processing);
291 return *this;
292}
293
294AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
295 std::unique_ptr<CustomProcessing> render_pre_processing) {
296 render_pre_processing_ = std::move(render_pre_processing);
297 return *this;
298}
299
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200300AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
301 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
302 capture_analyzer_ = std::move(capture_analyzer);
303 return *this;
304}
305
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100306AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
307 std::unique_ptr<EchoControlFactory> echo_control_factory) {
308 echo_control_factory_ = std::move(echo_control_factory);
309 return *this;
310}
311
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100312AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200313 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100314 echo_detector_ = std::move(echo_detector);
315 return *this;
316}
317
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100318AudioProcessing* AudioProcessingBuilder::Create() {
319 webrtc::Config config;
320 return Create(config);
321}
322
323AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100324 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
325 config, std::move(capture_post_processing_),
326 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200327 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100328 if (apm->Initialize() != AudioProcessing::kNoError) {
329 delete apm;
330 apm = nullptr;
331 }
332 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100333}
334
peah88ac8532016-09-12 16:47:25 -0700335AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200336 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
337}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000338
Per Åhgren13735822018-02-12 21:42:56 +0100339int AudioProcessingImpl::instance_count_ = 0;
340
Sam Zackrisson0beac582017-09-25 12:04:02 +0200341AudioProcessingImpl::AudioProcessingImpl(
342 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100343 std::unique_ptr<CustomProcessing> capture_post_processor,
344 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200345 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200346 rtc::scoped_refptr<EchoDetector> echo_detector,
347 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100348 : data_dumper_(
349 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200350 capture_runtime_settings_(kRuntimeSettingQueueSize),
351 render_runtime_settings_(kRuntimeSettingQueueSize),
352 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
353 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100354 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200355 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200356 submodule_states_(!!capture_post_processor,
357 !!render_pre_processor,
358 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800359 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200360 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200361 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100362 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200363 std::move(echo_detector),
364 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800365 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800366 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000367#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200368 /* enabled= */ false,
369 /* enabled_agc2_level_estimator= */ false,
370 /* digital_adaptive_disabled= */ false,
371 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000372#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200373 config.Get<ExperimentalAgc>().enabled,
374 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200375 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
376 config.Get<ExperimentalAgc>().analyze_before_aec),
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
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200383 capture_nonlocked_() {
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_));
Sam Zackrisson74ed7342018-08-16 10:54:07 +0200396 public_submodules_->echo_cancellation_proxy.reset(new EchoCancellationProxy(
397 this, public_submodules_->echo_cancellation.get()));
398 public_submodules_->echo_control_mobile_proxy.reset(
399 new EchoControlMobileProxy(
400 this, public_submodules_->echo_control_mobile.get()));
peahbfa97112016-03-10 21:09:04 -0800401 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200402 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800403 public_submodules_->level_estimator.reset(
404 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800405 public_submodules_->noise_suppression.reset(
406 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800407 public_submodules_->voice_detection.reset(
408 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800409 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800410 new GainControlForExperimentalAgc(
411 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100412
413 // If no echo detector is injected, use the ResidualEchoDetector.
414 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200415 private_submodules_->echo_detector =
416 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100417 }
peahca4cac72016-06-29 15:26:12 -0700418
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200419 // TODO(alessiob): Move the injected gain controller once injection is
420 // implemented.
421 private_submodules_->gain_controller2.reset(new GainController2());
422
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200423 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
424 << !!private_submodules_->capture_analyzer
425 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100426 << !!private_submodules_->capture_post_processor
427 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100428 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800429 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000430
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000431 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000432}
433
434AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800435 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800436 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800437 private_submodules_->agc_manager.reset();
438 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800439 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000440}
441
niklase@google.com470e71d2011-07-07 08:21:25 +0000442int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800443 // Run in a single-threaded manner during initialization.
444 rtc::CritScope cs_render(&crit_render_);
445 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000446 return InitializeLocked();
447}
448
peahde65ddc2016-09-16 15:02:15 -0700449int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
450 int capture_output_sample_rate_hz,
451 int render_input_sample_rate_hz,
452 ChannelLayout capture_input_layout,
453 ChannelLayout capture_output_layout,
454 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700455 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700456 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
457 LayoutHasKeyboard(capture_input_layout)},
458 {capture_output_sample_rate_hz,
459 ChannelsFromLayout(capture_output_layout),
460 LayoutHasKeyboard(capture_output_layout)},
461 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
462 LayoutHasKeyboard(render_input_layout)},
463 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
464 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700465
466 return Initialize(processing_config);
467}
468
469int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800470 // Run in a single-threaded manner during initialization.
471 rtc::CritScope cs_render(&crit_render_);
472 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700473 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000474}
475
peahdf3efa82015-11-28 12:35:15 -0800476int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800477 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700478 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800479}
480
peahdf3efa82015-11-28 12:35:15 -0800481int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700482 const ProcessingConfig& processing_config,
483 bool force_initialization) {
484 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800485}
486
peah192164e2015-11-17 02:16:45 -0800487// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800488// their current values (needs to be called while holding the crit_render_lock).
489int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700490 const ProcessingConfig& processing_config,
491 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800492 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700493 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800494 return kNoError;
495 }
peahdf3efa82015-11-28 12:35:15 -0800496
497 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800498 return InitializeLocked(processing_config);
499}
500
niklase@google.com470e71d2011-07-07 08:21:25 +0000501int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200502 UpdateActiveSubmoduleStates();
503
peahde65ddc2016-09-16 15:02:15 -0700504 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800505 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700506 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800507 : formats_.api_format.reverse_output_stream().num_frames();
508 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
509 render_.render_audio.reset(new AudioBuffer(
510 formats_.api_format.reverse_input_stream().num_frames(),
511 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700512 formats_.render_processing_format.num_frames(),
513 formats_.render_processing_format.num_channels(),
514 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700515 if (formats_.api_format.reverse_input_stream() !=
516 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800517 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800518 formats_.api_format.reverse_input_stream().num_channels(),
519 formats_.api_format.reverse_input_stream().num_frames(),
520 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800521 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700522 } else {
peahdf3efa82015-11-28 12:35:15 -0800523 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700524 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700525 } else {
peahdf3efa82015-11-28 12:35:15 -0800526 render_.render_audio.reset(nullptr);
527 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700528 }
peahce4d9152017-05-19 01:28:05 -0700529
peahdf3efa82015-11-28 12:35:15 -0800530 capture_.capture_audio.reset(
531 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
532 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700533 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200534 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800535 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000536
peahde65ddc2016-09-16 15:02:15 -0700537 public_submodules_->echo_cancellation->Initialize(
538 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
539 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700540 AllocateRenderQueue();
541
ivoc3e9a5372016-10-28 07:55:33 -0700542 int success = public_submodules_->echo_cancellation->enable_metrics(true);
543 RTC_DCHECK_EQ(0, success);
544 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
545 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700546 public_submodules_->echo_control_mobile->Initialize(
547 proc_split_sample_rate_hz(), num_reverse_channels(),
548 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700549
550 public_submodules_->gain_control->Initialize(num_proc_channels(),
551 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700552 if (constants_.use_experimental_agc) {
553 if (!private_submodules_->agc_manager.get()) {
554 private_submodules_->agc_manager.reset(new AgcManagerDirect(
555 public_submodules_->gain_control.get(),
556 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200557 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
558 constants_.use_experimental_agc_agc2_level_estimation,
559 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700560 }
561 private_submodules_->agc_manager->Initialize();
562 private_submodules_->agc_manager->SetCaptureMuted(
563 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700564 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700565 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200566 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800567 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700568 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
569 proc_sample_rate_hz());
570 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
571 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700572 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200573 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700574 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200575 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200576 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100577 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800578
aleloi868f32f2017-05-23 07:20:05 -0700579 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200580 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700581 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000582 return kNoError;
583}
584
Michael Graczyk86c6d332015-07-23 11:41:39 -0700585int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200586 UpdateActiveSubmoduleStates();
587
Michael Graczyk86c6d332015-07-23 11:41:39 -0700588 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700589 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
590 return kBadSampleRateError;
591 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000592 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700593
Peter Kasting69558702016-01-12 16:26:35 -0800594 const size_t num_in_channels = config.input_stream().num_channels();
595 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700596
597 // Need at least one input channel.
598 // Need either one output channel or as many outputs as there are inputs.
599 if (num_in_channels == 0 ||
600 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700601 return kBadNumberChannelsError;
602 }
603
peahdf3efa82015-11-28 12:35:15 -0800604 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000605
peahde65ddc2016-09-16 15:02:15 -0700606 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700607 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700608 formats_.api_format.output_stream().sample_rate_hz()),
609 submodule_states_.CaptureMultiBandSubModulesActive() ||
610 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000611
peahde65ddc2016-09-16 15:02:15 -0700612 capture_nonlocked_.capture_processing_format =
613 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700614
peah2ce640f2017-04-07 03:57:48 -0700615 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200616 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700617 render_processing_rate = FindNativeProcessRateToUse(
618 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
619 formats_.api_format.reverse_output_stream().sample_rate_hz()),
620 submodule_states_.CaptureMultiBandSubModulesActive() ||
621 submodule_states_.RenderMultiBandSubModulesActive());
622 } else {
623 render_processing_rate = capture_processing_rate;
624 }
625
aluebseb3603b2016-04-20 15:27:58 -0700626 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
627 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700628 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200629 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700630 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
631 ? kSampleRate32kHz
632 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700633 }
peah2ce640f2017-04-07 03:57:48 -0700634
peahde65ddc2016-09-16 15:02:15 -0700635 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700636 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700637 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
638 kSampleRate8kHz) {
639 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000640 } else {
peahde65ddc2016-09-16 15:02:15 -0700641 render_processing_rate =
642 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000643 }
644
peahde65ddc2016-09-16 15:02:15 -0700645 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000646 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700647 if (submodule_states_.RenderMultiBandSubModulesActive()) {
648 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
649 } else {
650 formats_.render_processing_format = StreamConfig(
651 formats_.api_format.reverse_input_stream().sample_rate_hz(),
652 formats_.api_format.reverse_input_stream().num_channels());
653 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000654
peahde65ddc2016-09-16 15:02:15 -0700655 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
656 kSampleRate32kHz ||
657 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
658 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800659 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000660 } else {
peahdf3efa82015-11-28 12:35:15 -0800661 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700662 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000663 }
664
665 return InitializeLocked();
666}
667
peah88ac8532016-09-12 16:47:25 -0700668void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700669 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700670
peah88ac8532016-09-12 16:47:25 -0700671 // Run in a single-threaded manner when applying the settings.
672 rtc::CritScope cs_render(&crit_render_);
673 rtc::CritScope cs_capture(&crit_capture_);
674
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200675 public_submodules_->echo_cancellation->Enable(
676 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200677 static_cast<EchoControlMobile*>(public_submodules_->echo_control_mobile.get())
678 ->Enable(config_.echo_canceller.enabled &&
679 config_.echo_canceller.mobile_mode);
680
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200681 public_submodules_->echo_cancellation->set_suppression_level(
682 config.echo_canceller.legacy_moderate_suppression_level
683 ? EchoCancellation::SuppressionLevel::kModerateSuppression
684 : EchoCancellation::SuppressionLevel::kHighSuppression);
685
peah8271d042016-11-22 07:24:52 -0800686 InitializeLowCutFilter();
687
Mirko Bonadei675513b2017-11-09 11:09:25 +0100688 RTC_LOG(LS_INFO) << "Highpass filter activated: "
689 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800690
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100691 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700692 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100693 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
694 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100695 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100696 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700697 config_.gain_controller2 = AudioProcessing::Config::GainController2();
698 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200699 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200700 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200701 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100702 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
703 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200704 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
705 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700706}
707
708void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800709 // Run in a single-threaded manner when setting the extra options.
710 rtc::CritScope cs_render(&crit_render_);
711 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000712
peahb624d8c2016-03-05 03:01:14 -0800713 public_submodules_->echo_cancellation->SetExtraOptions(config);
714
peahdf3efa82015-11-28 12:35:15 -0800715 if (capture_.transient_suppressor_enabled !=
716 config.Get<ExperimentalNs>().enabled) {
717 capture_.transient_suppressor_enabled =
718 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000719 InitializeTransient();
720 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000721}
722
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000723int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800724 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700725 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000726}
727
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000728int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800729 // Used as callback from submodules, hence locking is not allowed.
730 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000731}
732
Peter Kasting69558702016-01-12 16:26:35 -0800733size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800734 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700735 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000736}
737
Peter Kasting69558702016-01-12 16:26:35 -0800738size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800739 // Used as callback from submodules, hence locking is not allowed.
740 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000741}
742
Peter Kasting69558702016-01-12 16:26:35 -0800743size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800744 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200745 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800746}
747
Peter Kasting69558702016-01-12 16:26:35 -0800748size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800749 // Used as callback from submodules, hence locking is not allowed.
750 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000751}
752
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000753void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800754 rtc::CritScope cs(&crit_capture_);
755 capture_.output_will_be_muted = muted;
756 if (private_submodules_->agc_manager.get()) {
757 private_submodules_->agc_manager->SetCaptureMuted(
758 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000759 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000760}
761
Alessio Bazzicac054e782018-04-16 12:10:09 +0200762void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200763 switch (setting.type()) {
764 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
765 render_runtime_settings_enqueuer_.Enqueue(setting);
766 return;
767 case RuntimeSetting::Type::kNotSpecified:
768 RTC_NOTREACHED();
769 return;
770 case RuntimeSetting::Type::kCapturePreGain:
771 capture_runtime_settings_enqueuer_.Enqueue(setting);
772 return;
773 }
774 // The language allows the enum to have a non-enumerator
775 // value. Check that this doesn't happen.
776 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200777}
778
779AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
780 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200781 : runtime_settings_(*runtime_settings) {
782 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200783}
784
785AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
786 default;
787
788void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
789 RuntimeSetting setting) {
790 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200791 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200792 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200793 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200794 RTC_LOG(LS_ERROR)
795 << "The runtime settings queue is full. Oldest setting discarded.";
796 }
797 if (remaining_attempts == 0)
798 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
799}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000800
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000801int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700802 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000803 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000804 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000805 int output_sample_rate_hz,
806 ChannelLayout output_layout,
807 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800808 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800809 StreamConfig input_stream;
810 StreamConfig output_stream;
811 {
812 // Access the formats_.api_format.input_stream beneath the capture lock.
813 // The lock must be released as it is later required in the call
814 // to ProcessStream(,,,);
815 rtc::CritScope cs(&crit_capture_);
816 input_stream = formats_.api_format.input_stream();
817 output_stream = formats_.api_format.output_stream();
818 }
819
Michael Graczyk86c6d332015-07-23 11:41:39 -0700820 input_stream.set_sample_rate_hz(input_sample_rate_hz);
821 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
822 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700823 output_stream.set_sample_rate_hz(output_sample_rate_hz);
824 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
825 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
826
827 if (samples_per_channel != input_stream.num_frames()) {
828 return kBadDataLengthError;
829 }
830 return ProcessStream(src, input_stream, output_stream, dest);
831}
832
833int AudioProcessingImpl::ProcessStream(const float* const* src,
834 const StreamConfig& input_config,
835 const StreamConfig& output_config,
836 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800837 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800838 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700839 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800840 {
841 // Acquire the capture lock in order to safely call the function
842 // that retrieves the render side data. This function accesses apm
843 // getters that need the capture lock held when being called.
844 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700845 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800846
847 if (!src || !dest) {
848 return kNullPointerError;
849 }
850
851 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700852 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000853 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000854
Michael Graczyk86c6d332015-07-23 11:41:39 -0700855 processing_config.input_stream() = input_config;
856 processing_config.output_stream() = output_config;
857
peahdf3efa82015-11-28 12:35:15 -0800858 {
859 // Do conditional reinitialization.
860 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700861 RETURN_ON_ERR(
862 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800863 }
864 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700865 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
866 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000867
aleloi868f32f2017-05-23 07:20:05 -0700868 if (aec_dump_) {
869 RecordUnprocessedCaptureStream(src);
870 }
871
peahdf3efa82015-11-28 12:35:15 -0800872 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700873 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800874 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000875
aleloi868f32f2017-05-23 07:20:05 -0700876 if (aec_dump_) {
877 RecordProcessedCaptureStream(dest);
878 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000879 return kNoError;
880}
881
Alex Loiko73ec0192018-05-15 10:52:28 +0200882void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200883 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200884 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200885 if (aec_dump_) {
886 aec_dump_->WriteRuntimeSetting(setting);
887 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200888 switch (setting.type()) {
889 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200890 if (config_.pre_amplifier.enabled) {
891 float value;
892 setting.GetFloat(&value);
893 private_submodules_->pre_amplifier->SetGainFactor(value);
894 }
895 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200896 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200897 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
898 RTC_NOTREACHED();
899 break;
900 case RuntimeSetting::Type::kNotSpecified:
901 RTC_NOTREACHED();
902 break;
903 }
904 }
905}
906
907void AudioProcessingImpl::HandleRenderRuntimeSettings() {
908 RuntimeSetting setting;
909 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200910 if (aec_dump_) {
911 aec_dump_->WriteRuntimeSetting(setting);
912 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200913 switch (setting.type()) {
914 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
915 if (private_submodules_->render_pre_processor) {
916 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
917 }
918 break;
919 case RuntimeSetting::Type::kCapturePreGain:
920 RTC_NOTREACHED();
921 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200922 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200923 RTC_NOTREACHED();
924 break;
925 }
926 }
927}
928
peah9e6a2902017-05-15 07:19:21 -0700929void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700930 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
931 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700932 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700933
kwibergaf476c72016-11-28 15:21:39 -0800934 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700935
936 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700937 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700938 // The data queue is full and needs to be emptied.
939 EmptyQueuedRenderAudio();
940
941 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700942 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700943 RTC_DCHECK(result);
944 }
945
946 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
947 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700948 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700949
950 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700951 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700952 // The data queue is full and needs to be emptied.
953 EmptyQueuedRenderAudio();
954
955 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700956 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700957 RTC_DCHECK(result);
958 }
peah701d6282016-10-25 05:42:20 -0700959
960 if (!constants_.use_experimental_agc) {
961 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
962 // Insert the samples into the queue.
963 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
964 // The data queue is full and needs to be emptied.
965 EmptyQueuedRenderAudio();
966
967 // Retry the insert (should always work).
968 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
969 RTC_DCHECK(result);
970 }
971 }
peah9e6a2902017-05-15 07:19:21 -0700972}
ivoc9f4a4a02016-10-28 05:39:16 -0700973
peah9e6a2902017-05-15 07:19:21 -0700974void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700975 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
976
977 // Insert the samples into the queue.
978 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
979 // The data queue is full and needs to be emptied.
980 EmptyQueuedRenderAudio();
981
982 // Retry the insert (should always work).
983 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
984 RTC_DCHECK(result);
985 }
peah764e3642016-10-22 05:04:30 -0700986}
987
988void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700989 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700990 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700991 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700992 EchoCancellationImpl::NumCancellersRequired(
993 num_output_channels(), num_reverse_channels()));
994
peah701d6282016-10-25 05:42:20 -0700995 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700996 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700997 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700998 EchoControlMobileImpl::NumCancellersRequired(
999 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001000
peah701d6282016-10-25 05:42:20 -07001001 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001002 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001003
ivoc9f4a4a02016-10-28 05:39:16 -07001004 const size_t new_red_render_queue_element_max_size =
1005 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1006
peaha0624602016-10-25 04:45:24 -07001007 // Reallocate the queues if the queue item sizes are too small to fit the
1008 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001009 if (aec_render_queue_element_max_size_ <
1010 new_aec_render_queue_element_max_size) {
1011 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001012
peaha0624602016-10-25 04:45:24 -07001013 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001014 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001015
peah701d6282016-10-25 05:42:20 -07001016 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001017 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1018 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001019 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001020 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001021
peah701d6282016-10-25 05:42:20 -07001022 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1023 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001024 } else {
peah701d6282016-10-25 05:42:20 -07001025 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001026 }
1027
peah701d6282016-10-25 05:42:20 -07001028 if (aecm_render_queue_element_max_size_ <
1029 new_aecm_render_queue_element_max_size) {
1030 aecm_render_queue_element_max_size_ =
1031 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001032
1033 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001034 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001035
peah701d6282016-10-25 05:42:20 -07001036 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001037 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1038 kMaxNumFramesToBuffer, template_queue_element,
1039 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001040 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001041
peah701d6282016-10-25 05:42:20 -07001042 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1043 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001044 } else {
peah701d6282016-10-25 05:42:20 -07001045 aecm_render_signal_queue_->Clear();
1046 }
1047
1048 if (agc_render_queue_element_max_size_ <
1049 new_agc_render_queue_element_max_size) {
1050 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1051
1052 std::vector<int16_t> template_queue_element(
1053 agc_render_queue_element_max_size_);
1054
1055 agc_render_signal_queue_.reset(
1056 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1057 kMaxNumFramesToBuffer, template_queue_element,
1058 RenderQueueItemVerifier<int16_t>(
1059 agc_render_queue_element_max_size_)));
1060
1061 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1062 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1063 } else {
1064 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001065 }
ivoc9f4a4a02016-10-28 05:39:16 -07001066
1067 if (red_render_queue_element_max_size_ <
1068 new_red_render_queue_element_max_size) {
1069 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1070
1071 std::vector<float> template_queue_element(
1072 red_render_queue_element_max_size_);
1073
1074 red_render_signal_queue_.reset(
1075 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1076 kMaxNumFramesToBuffer, template_queue_element,
1077 RenderQueueItemVerifier<float>(
1078 red_render_queue_element_max_size_)));
1079
1080 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1081 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1082 } else {
1083 red_render_signal_queue_->Clear();
1084 }
peah764e3642016-10-22 05:04:30 -07001085}
1086
1087void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1088 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001089 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001090 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001091 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001092 }
1093
peah701d6282016-10-25 05:42:20 -07001094 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001095 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001096 aecm_capture_queue_buffer_);
1097 }
1098
1099 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1100 public_submodules_->gain_control->ProcessRenderAudio(
1101 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001102 }
ivoc9f4a4a02016-10-28 05:39:16 -07001103
1104 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001105 RTC_DCHECK(private_submodules_->echo_detector);
1106 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001107 red_capture_queue_buffer_);
1108 }
peah764e3642016-10-22 05:04:30 -07001109}
1110
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001111int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001112 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001113 {
1114 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001115 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001116 // getters that need the capture lock held when being called.
1117 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001118 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001119 // as well.
1120 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001121 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001122 }
peahfa6228e2015-11-16 16:27:42 -08001123
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001124 if (!frame) {
1125 return kNullPointerError;
1126 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001127 // Must be a native rate.
1128 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1129 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001130 frame->sample_rate_hz_ != kSampleRate32kHz &&
1131 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001132 return kBadSampleRateError;
1133 }
peah192164e2015-11-17 02:16:45 -08001134
peahdf3efa82015-11-28 12:35:15 -08001135 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001136 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001137 {
1138 // Aquire lock for the access of api_format.
1139 // The lock is released immediately due to the conditional
1140 // reinitialization.
1141 rtc::CritScope cs_capture(&crit_capture_);
1142 // TODO(ajm): The input and output rates and channels are currently
1143 // constrained to be identical in the int16 interface.
1144 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001145
1146 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001147 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001148 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1149 processing_config.input_stream().set_num_channels(frame->num_channels_);
1150 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1151 processing_config.output_stream().set_num_channels(frame->num_channels_);
1152
peahdf3efa82015-11-28 12:35:15 -08001153 {
1154 // Do conditional reinitialization.
1155 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001156 RETURN_ON_ERR(
1157 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001158 }
1159 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001160 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001161 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001162 return kBadDataLengthError;
1163 }
1164
aleloi868f32f2017-05-23 07:20:05 -07001165 if (aec_dump_) {
1166 RecordUnprocessedCaptureStream(*frame);
1167 }
1168
peahdf3efa82015-11-28 12:35:15 -08001169 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001170 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001171 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001172 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1173 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001174
aleloi868f32f2017-05-23 07:20:05 -07001175 if (aec_dump_) {
1176 RecordProcessedCaptureStream(*frame);
1177 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001178
1179 return kNoError;
1180}
1181
peahde65ddc2016-09-16 15:02:15 -07001182int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001183 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001184
peahb58a1582016-03-15 09:34:24 -07001185 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001186 // TODO(peah): Simplify once the public API Enable functions for these
1187 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001188 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1189 public_submodules_->echo_control_mobile->is_enabled()));
1190
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001191 MaybeUpdateHistograms();
1192
peahde65ddc2016-09-16 15:02:15 -07001193 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001194
Alex Loikob5c9a792018-04-16 16:31:22 +02001195 if (private_submodules_->pre_amplifier) {
1196 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1197 capture_buffer->channels_f(), capture_buffer->num_channels(),
1198 capture_buffer->num_frames()));
1199 }
1200
peah1b08dc32016-12-20 13:45:58 -08001201 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001202 capture_buffer->channels_const()[0],
1203 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001204 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1205 if (log_rms) {
1206 capture_rms_interval_counter_ = 0;
1207 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001208 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1209 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1210 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1211 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001212 }
1213
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001214 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001215 // Detect and flag any change in the analog gain.
1216 int analog_mic_level = gain_control()->stream_analog_level();
1217 capture_.echo_path_gain_change =
1218 capture_.prev_analog_mic_level != analog_mic_level &&
1219 capture_.prev_analog_mic_level != -1;
1220 capture_.prev_analog_mic_level = analog_mic_level;
1221
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001222 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001223 }
1224
peahbe615622016-02-13 16:40:47 -08001225 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001226 public_submodules_->gain_control->is_enabled()) {
1227 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001228 capture_buffer->channels()[0], capture_buffer->num_channels(),
1229 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001230
1231 if (constants_.use_experimental_agc_process_before_aec) {
1232 private_submodules_->agc_manager->Process(
1233 capture_buffer->channels()[0],
1234 capture_nonlocked_.capture_processing_format.num_frames(),
1235 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1236 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001237 }
1238
peah2ace3f92016-09-10 04:42:27 -07001239 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1240 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001241 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1242 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001243 }
1244
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001245 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001246 // Force down-mixing of the number of channels after the detection of
1247 // capture signal saturation.
1248 // TODO(peah): Look into ensuring that this kind of tampering with the
1249 // AudioBuffer functionality should not be needed.
1250 capture_buffer->set_num_channels(1);
1251 }
1252
peahe0eae3c2016-12-14 01:16:23 -08001253 // TODO(peah): Move the AEC3 low-cut filter to this place.
1254 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001255 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001256 private_submodules_->low_cut_filter->Process(capture_buffer);
1257 }
peahde65ddc2016-09-16 15:02:15 -07001258 RETURN_ON_ERR(
1259 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1260 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001261
1262 // Ensure that the stream delay was set before the call to the
1263 // AEC ProcessCaptureAudio function.
1264 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001265 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001266 return AudioProcessing::kStreamParameterNotSetError;
1267 }
1268
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001269 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001270 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1271
Per Åhgrend0fa8202018-04-18 09:35:13 +02001272 if (was_stream_delay_set()) {
1273 private_submodules_->echo_controller->SetAudioBufferDelay(
1274 stream_delay_ms());
1275 }
1276
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001277 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001278 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001279 } else {
1280 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1281 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001282 }
1283
peahdf3efa82015-11-28 12:35:15 -08001284 if (public_submodules_->echo_control_mobile->is_enabled() &&
1285 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001286 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001287 }
peahde65ddc2016-09-16 15:02:15 -07001288 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001289
1290 // Ensure that the stream delay was set before the call to the
1291 // AECM ProcessCaptureAudio function.
1292 if (public_submodules_->echo_control_mobile->is_enabled() &&
1293 !was_stream_delay_set()) {
1294 return AudioProcessing::kStreamParameterNotSetError;
1295 }
1296
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001297 if (!(private_submodules_->echo_controller ||
1298 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001299 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1300 capture_buffer, stream_delay_ms()));
1301 }
ivoc9f4a4a02016-10-28 05:39:16 -07001302
peahde65ddc2016-09-16 15:02:15 -07001303 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001304
peahbe615622016-02-13 16:40:47 -08001305 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001306 public_submodules_->gain_control->is_enabled() &&
1307 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001308 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001309 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1310 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001311 }
peahb8fbb542016-03-15 02:28:08 -07001312 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001313 capture_buffer,
1314 public_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001315
peah2ace3f92016-09-10 04:42:27 -07001316 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1317 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001318 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1319 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001320 }
1321
peah9e6a2902017-05-15 07:19:21 -07001322 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001323 RTC_DCHECK(private_submodules_->echo_detector);
1324 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001325 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1326 capture_buffer->num_frames()));
1327 }
1328
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001329 // TODO(aluebs): Investigate if the transient suppression placement should be
1330 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001331 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001332 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001333 private_submodules_->agc_manager.get()
1334 ? private_submodules_->agc_manager->voice_probability()
1335 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001336
peahdf3efa82015-11-28 12:35:15 -08001337 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001338 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1339 capture_buffer->num_channels(),
1340 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1341 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1342 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001343 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001344 }
1345
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001346 // Experimental APM sub-module that analyzes |capture_buffer|.
1347 if (private_submodules_->capture_analyzer) {
1348 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1349 }
1350
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001351 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001352 private_submodules_->gain_controller2->NotifyAnalogLevel(
1353 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001354 private_submodules_->gain_controller2->Process(capture_buffer);
1355 }
1356
Sam Zackrisson0beac582017-09-25 12:04:02 +02001357 if (private_submodules_->capture_post_processor) {
1358 private_submodules_->capture_post_processor->Process(capture_buffer);
1359 }
1360
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001361 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001362 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001363
peah1b08dc32016-12-20 13:45:58 -08001364 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1365 capture_buffer->channels_const()[0],
1366 capture_nonlocked_.capture_processing_format.num_frames()));
1367 if (log_rms) {
1368 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1369 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1370 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1371 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1372 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1373 }
1374
peahdf3efa82015-11-28 12:35:15 -08001375 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001376 return kNoError;
1377}
1378
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001379int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001380 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001381 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001382 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001383 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001384 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001385 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001386 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001387 };
1388 if (samples_per_channel != reverse_config.num_frames()) {
1389 return kBadDataLengthError;
1390 }
peahdf3efa82015-11-28 12:35:15 -08001391 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001392}
1393
peahde65ddc2016-09-16 15:02:15 -07001394int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1395 const StreamConfig& input_config,
1396 const StreamConfig& output_config,
1397 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001398 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001399 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001400 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001401 if (submodule_states_.RenderMultiBandProcessingActive() ||
1402 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001403 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1404 dest);
peah2ace3f92016-09-10 04:42:27 -07001405 } else if (formats_.api_format.reverse_input_stream() !=
1406 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001407 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1408 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001409 } else {
peahde65ddc2016-09-16 15:02:15 -07001410 CopyAudioIfNeeded(src, input_config.num_frames(),
1411 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001412 }
1413
1414 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001415}
1416
peahdf3efa82015-11-28 12:35:15 -08001417int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001418 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001419 const StreamConfig& input_config,
1420 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001421 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001422 return kNullPointerError;
1423 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001424
peahde65ddc2016-09-16 15:02:15 -07001425 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001426 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001427 }
1428
peahdf3efa82015-11-28 12:35:15 -08001429 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001430 processing_config.reverse_input_stream() = input_config;
1431 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001432
peahdf3efa82015-11-28 12:35:15 -08001433 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001434 RTC_DCHECK_EQ(input_config.num_frames(),
1435 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001436
aleloi868f32f2017-05-23 07:20:05 -07001437 if (aec_dump_) {
1438 const size_t channel_size =
1439 formats_.api_format.reverse_input_stream().num_frames();
1440 const size_t num_channels =
1441 formats_.api_format.reverse_input_stream().num_channels();
1442 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001443 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001444 }
peahdf3efa82015-11-28 12:35:15 -08001445 render_.render_audio->CopyFrom(src,
1446 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001447 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001448}
1449
1450int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001451 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001452 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001453 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001454 return kNullPointerError;
1455 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001456 // Must be a native rate.
1457 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1458 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001459 frame->sample_rate_hz_ != kSampleRate32kHz &&
1460 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001461 return kBadSampleRateError;
1462 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001463
Michael Graczyk86c6d332015-07-23 11:41:39 -07001464 if (frame->num_channels_ <= 0) {
1465 return kBadNumberChannelsError;
1466 }
1467
peahdf3efa82015-11-28 12:35:15 -08001468 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001469 processing_config.reverse_input_stream().set_sample_rate_hz(
1470 frame->sample_rate_hz_);
1471 processing_config.reverse_input_stream().set_num_channels(
1472 frame->num_channels_);
1473 processing_config.reverse_output_stream().set_sample_rate_hz(
1474 frame->sample_rate_hz_);
1475 processing_config.reverse_output_stream().set_num_channels(
1476 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001477
peahdf3efa82015-11-28 12:35:15 -08001478 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001479 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001480 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001481 return kBadDataLengthError;
1482 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001483
aleloi868f32f2017-05-23 07:20:05 -07001484 if (aec_dump_) {
1485 aec_dump_->WriteRenderStreamMessage(*frame);
1486 }
1487
peahdf3efa82015-11-28 12:35:15 -08001488 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001489 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001490 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001491 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1492 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001493 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001494}
niklase@google.com470e71d2011-07-07 08:21:25 +00001495
peahde65ddc2016-09-16 15:02:15 -07001496int AudioProcessingImpl::ProcessRenderStreamLocked() {
1497 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001498
Alex Loiko73ec0192018-05-15 10:52:28 +02001499 HandleRenderRuntimeSettings();
1500
Alex Loiko5825aa62017-12-18 16:02:40 +01001501 if (private_submodules_->render_pre_processor) {
1502 private_submodules_->render_pre_processor->Process(render_buffer);
1503 }
1504
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001505 QueueNonbandedRenderAudio(render_buffer);
1506
peah2ace3f92016-09-10 04:42:27 -07001507 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001508 SampleRateSupportsMultiBand(
1509 formats_.render_processing_format.sample_rate_hz())) {
1510 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001511 }
1512
peahce4d9152017-05-19 01:28:05 -07001513 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1514 QueueBandedRenderAudio(render_buffer);
1515 }
1516
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001517 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001518 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001519 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001520 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001521
peah2ace3f92016-09-10 04:42:27 -07001522 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001523 SampleRateSupportsMultiBand(
1524 formats_.render_processing_format.sample_rate_hz())) {
1525 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001526 }
1527
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001528 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001529}
1530
1531int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001532 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001533 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001534 capture_.was_stream_delay_set = true;
1535 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001536
niklase@google.com470e71d2011-07-07 08:21:25 +00001537 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001538 delay = 0;
1539 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001540 }
1541
1542 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1543 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001544 delay = 500;
1545 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001546 }
1547
peahdf3efa82015-11-28 12:35:15 -08001548 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001549 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001550}
1551
1552int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001553 // Used as callback from submodules, hence locking is not allowed.
1554 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001555}
1556
1557bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001558 // Used as callback from submodules, hence locking is not allowed.
1559 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001560}
1561
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001562void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001563 rtc::CritScope cs(&crit_capture_);
1564 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001565}
1566
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001567void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001568 rtc::CritScope cs(&crit_capture_);
1569 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001570}
1571
1572int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001573 rtc::CritScope cs(&crit_capture_);
1574 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001575}
1576
aleloi868f32f2017-05-23 07:20:05 -07001577void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1578 RTC_DCHECK(aec_dump);
1579 rtc::CritScope cs_render(&crit_render_);
1580 rtc::CritScope cs_capture(&crit_capture_);
1581
1582 // The previously attached AecDump will be destroyed with the
1583 // 'aec_dump' parameter, which is after locks are released.
1584 aec_dump_.swap(aec_dump);
1585 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001586 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001587}
1588
1589void AudioProcessingImpl::DetachAecDump() {
1590 // The d-tor of a task-queue based AecDump blocks until all pending
1591 // tasks are done. This construction avoids blocking while holding
1592 // the render and capture locks.
1593 std::unique_ptr<AecDump> aec_dump = nullptr;
1594 {
1595 rtc::CritScope cs_render(&crit_render_);
1596 rtc::CritScope cs_capture(&crit_capture_);
1597 aec_dump = std::move(aec_dump_);
1598 }
1599}
1600
Sam Zackrisson4d364492018-03-02 16:03:21 +01001601void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1602 std::unique_ptr<AudioGenerator> audio_generator) {
1603 // TODO(bugs.webrtc.org/8882) Stub.
1604 // Reset internal audio generator with audio_generator.
1605}
1606
1607void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1608 // TODO(bugs.webrtc.org/8882) Stub.
1609 // Delete audio generator, if one is attached.
1610}
1611
ivoc4e477a12017-01-15 08:29:46 -08001612AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1613 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1614 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1615 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1616 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1617}
1618
1619AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1620 const AudioProcessingStatistics& other) = default;
1621
1622AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1623 default;
1624
ivoc3e9a5372016-10-28 07:55:33 -07001625// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1626AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1627 const {
1628 return AudioProcessingStatistics();
1629}
1630
Ivo Creusenae026092017-11-20 13:07:16 +01001631// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001632AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001633 bool has_remote_tracks) const {
1634 return AudioProcessingStats();
1635}
1636
ivoc3e9a5372016-10-28 07:55:33 -07001637AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1638 const {
1639 AudioProcessingStatistics stats;
1640 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001641 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001642 rtc::CritScope cs_capture(&crit_capture_);
1643 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1644 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1645 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1646 // Instant value will also be used for min, max and average.
1647 stats.echo_return_loss.Set(erl, erl, erl, erl);
1648 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1649 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1650 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001651 stats.a_nlp.Set(metrics.a_nlp);
1652 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1653 stats.echo_return_loss.Set(metrics.echo_return_loss);
1654 stats.echo_return_loss_enhancement.Set(
1655 metrics.echo_return_loss_enhancement);
1656 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1657 }
ivoc9c192b22017-03-16 04:22:14 -07001658 {
1659 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001660 RTC_DCHECK(private_submodules_->echo_detector);
1661 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1662 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001663 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001664 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001665 }
ivoc3e9a5372016-10-28 07:55:33 -07001666 public_submodules_->echo_cancellation->GetDelayMetrics(
1667 &stats.delay_median, &stats.delay_standard_deviation,
1668 &stats.fraction_poor_delays);
1669 return stats;
1670}
1671
Ivo Creusen56d46092017-11-24 17:29:59 +01001672AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001673 bool has_remote_tracks) const {
1674 AudioProcessingStats stats;
1675 if (has_remote_tracks) {
1676 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001677 if (private_submodules_->echo_controller) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001678 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001679 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1680 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001681 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001682 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001683 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001684 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1685 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001686 if (metrics.divergent_filter_fraction != -1.0f) {
1687 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001688 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001689 }
1690 if (metrics.echo_return_loss.instant != -100) {
1691 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001692 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001693 }
1694 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001695 stats.echo_return_loss_enhancement = absl::optional<double>(
1696 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001697 }
1698 }
1699 if (config_.residual_echo_detector.enabled) {
1700 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001701 RTC_DCHECK(private_submodules_->echo_detector);
1702 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1703 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001704 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001705 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001706 }
1707 int delay_median, delay_std;
1708 float fraction_poor_delays;
1709 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1710 &delay_median, &delay_std, &fraction_poor_delays) ==
1711 Error::kNoError) {
1712 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001713 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001714 }
1715 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001716 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001717 }
1718 }
1719 }
1720 return stats;
1721}
1722
niklase@google.com470e71d2011-07-07 08:21:25 +00001723EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001724 return public_submodules_->echo_cancellation_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001725}
1726
1727EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001728 return public_submodules_->echo_control_mobile_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001729}
1730
1731GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001732 if (constants_.use_experimental_agc) {
1733 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001734 }
peahbfa97112016-03-10 21:09:04 -08001735 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001736}
1737
1738HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001739 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001740}
1741
1742LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001743 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001744}
1745
1746NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001747 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001748}
1749
1750VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001751 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001752}
1753
peah8271d042016-11-22 07:24:52 -08001754void AudioProcessingImpl::MutateConfig(
1755 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1756 rtc::CritScope cs_render(&crit_render_);
1757 rtc::CritScope cs_capture(&crit_capture_);
1758 mutator(&config_);
1759 ApplyConfig(config_);
1760}
1761
1762AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1763 rtc::CritScope cs_render(&crit_render_);
1764 rtc::CritScope cs_capture(&crit_capture_);
1765 return config_;
1766}
1767
peah2ace3f92016-09-10 04:42:27 -07001768bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1769 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001770 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001771 public_submodules_->echo_cancellation->is_enabled(),
1772 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001773 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001774 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001775 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001776 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001777 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001778 public_submodules_->voice_detection->is_enabled(),
1779 public_submodules_->level_estimator->is_enabled(),
1780 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001781}
1782
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001783
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001784void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001785 if (capture_.transient_suppressor_enabled) {
1786 if (!public_submodules_->transient_suppressor.get()) {
1787 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001788 }
peahdf3efa82015-11-28 12:35:15 -08001789 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001790 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1791 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001792 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001793}
1794
peah8271d042016-11-22 07:24:52 -08001795void AudioProcessingImpl::InitializeLowCutFilter() {
1796 if (config_.high_pass_filter.enabled) {
1797 private_submodules_->low_cut_filter.reset(
1798 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1799 } else {
1800 private_submodules_->low_cut_filter.reset();
1801 }
1802}
alessiob3ec96df2017-05-22 06:57:06 -07001803
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001804void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001805 if (echo_control_factory_) {
1806 private_submodules_->echo_controller =
1807 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001808 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001809 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001810 }
1811}
peah8271d042016-11-22 07:24:52 -08001812
alessiob3ec96df2017-05-22 06:57:06 -07001813void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001814 if (config_.gain_controller2.enabled) {
1815 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001816 }
1817}
1818
Alex Loikob5c9a792018-04-16 16:31:22 +02001819void AudioProcessingImpl::InitializePreAmplifier() {
1820 if (config_.pre_amplifier.enabled) {
1821 private_submodules_->pre_amplifier.reset(
1822 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1823 } else {
1824 private_submodules_->pre_amplifier.reset();
1825 }
1826}
1827
ivoc9f4a4a02016-10-28 05:39:16 -07001828void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001829 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001830 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001831 proc_sample_rate_hz(), 1,
1832 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001833}
1834
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001835void AudioProcessingImpl::InitializeAnalyzer() {
1836 if (private_submodules_->capture_analyzer) {
1837 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1838 num_proc_channels());
1839 }
1840}
1841
Sam Zackrisson0beac582017-09-25 12:04:02 +02001842void AudioProcessingImpl::InitializePostProcessor() {
1843 if (private_submodules_->capture_post_processor) {
1844 private_submodules_->capture_post_processor->Initialize(
1845 proc_sample_rate_hz(), num_proc_channels());
1846 }
1847}
1848
Alex Loiko5825aa62017-12-18 16:02:40 +01001849void AudioProcessingImpl::InitializePreProcessor() {
1850 if (private_submodules_->render_pre_processor) {
1851 private_submodules_->render_pre_processor->Initialize(
1852 formats_.render_processing_format.sample_rate_hz(),
1853 formats_.render_processing_format.num_channels());
1854 }
1855}
1856
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001857void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001858 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001859
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001860 if (public_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001861 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1862 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001863 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001864 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001865 capture_.stream_delay_jumps = 0;
1866 }
1867 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001868 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001869 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001870 }
1871
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001872 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001873 const int diff_stream_delay_ms =
1874 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1875 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1876 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001877 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1878 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001879 if (capture_.stream_delay_jumps == -1) {
1880 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001881 }
peahdf3efa82015-11-28 12:35:15 -08001882 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001883 }
peahdf3efa82015-11-28 12:35:15 -08001884 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001885
1886 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001887 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001888 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001889 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001890 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001891 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1892 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001893 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001894 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001895 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001896 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001897 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1898 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1899 100);
peahdf3efa82015-11-28 12:35:15 -08001900 if (capture_.aec_system_delay_jumps == -1) {
1901 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001902 }
peahdf3efa82015-11-28 12:35:15 -08001903 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001904 }
peahdf3efa82015-11-28 12:35:15 -08001905 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001906 }
1907}
1908
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001909void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001910 // Run in a single-threaded manner.
1911 rtc::CritScope cs_render(&crit_render_);
1912 rtc::CritScope cs_capture(&crit_capture_);
1913
1914 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001915 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001916 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001917 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001918 }
peahdf3efa82015-11-28 12:35:15 -08001919 capture_.stream_delay_jumps = -1;
1920 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001921
peahdf3efa82015-11-28 12:35:15 -08001922 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001923 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1924 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001925 }
peahdf3efa82015-11-28 12:35:15 -08001926 capture_.aec_system_delay_jumps = -1;
1927 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001928}
1929
aleloi868f32f2017-05-23 07:20:05 -07001930void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1931 if (!aec_dump_) {
1932 return;
1933 }
1934 std::string experiments_description =
1935 public_submodules_->echo_cancellation->GetExperimentsDescription();
1936 // TODO(peah): Add semicolon-separated concatenations of experiment
1937 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001938 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1939 experiments_description += "AgcClippingLevelExperiment;";
1940 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001941 if (capture_nonlocked_.echo_controller_enabled) {
1942 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001943 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001944 if (config_.gain_controller2.enabled) {
1945 experiments_description += "GainController2;";
1946 }
aleloi868f32f2017-05-23 07:20:05 -07001947
1948 InternalAPMConfig apm_config;
1949
1950 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1951 apm_config.aec_delay_agnostic_enabled =
1952 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1953 apm_config.aec_drift_compensation_enabled =
1954 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1955 apm_config.aec_extended_filter_enabled =
1956 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1957 apm_config.aec_suppression_level = static_cast<int>(
1958 public_submodules_->echo_cancellation->suppression_level());
1959
1960 apm_config.aecm_enabled =
1961 public_submodules_->echo_control_mobile->is_enabled();
1962 apm_config.aecm_comfort_noise_enabled =
1963 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1964 apm_config.aecm_routing_mode =
1965 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1966
1967 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1968 apm_config.agc_mode =
1969 static_cast<int>(public_submodules_->gain_control->mode());
1970 apm_config.agc_limiter_enabled =
1971 public_submodules_->gain_control->is_limiter_enabled();
1972 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1973
1974 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1975
1976 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1977 apm_config.ns_level =
1978 static_cast<int>(public_submodules_->noise_suppression->level());
1979
1980 apm_config.transient_suppression_enabled =
1981 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001982 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001983 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1984 apm_config.pre_amplifier_fixed_gain_factor =
1985 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001986
1987 if (!forced && apm_config == apm_config_for_aec_dump_) {
1988 return;
1989 }
1990 aec_dump_->WriteConfig(apm_config);
1991 apm_config_for_aec_dump_ = apm_config;
1992}
1993
1994void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1995 const float* const* src) {
1996 RTC_DCHECK(aec_dump_);
1997 WriteAecDumpConfigMessage(false);
1998
1999 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2000 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2001 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002002 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002003 RecordAudioProcessingState();
2004}
2005
2006void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2007 const AudioFrame& capture_frame) {
2008 RTC_DCHECK(aec_dump_);
2009 WriteAecDumpConfigMessage(false);
2010
2011 aec_dump_->AddCaptureStreamInput(capture_frame);
2012 RecordAudioProcessingState();
2013}
2014
2015void AudioProcessingImpl::RecordProcessedCaptureStream(
2016 const float* const* processed_capture_stream) {
2017 RTC_DCHECK(aec_dump_);
2018
2019 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2020 const size_t num_channels =
2021 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002022 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2023 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002024 aec_dump_->WriteCaptureStreamMessage();
2025}
2026
2027void AudioProcessingImpl::RecordProcessedCaptureStream(
2028 const AudioFrame& processed_capture_frame) {
2029 RTC_DCHECK(aec_dump_);
2030
2031 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2032 aec_dump_->WriteCaptureStreamMessage();
2033}
2034
2035void AudioProcessingImpl::RecordAudioProcessingState() {
2036 RTC_DCHECK(aec_dump_);
2037 AecDump::AudioProcessingState audio_proc_state;
2038 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2039 audio_proc_state.drift =
2040 public_submodules_->echo_cancellation->stream_drift_samples();
2041 audio_proc_state.level = gain_control()->stream_analog_level();
2042 audio_proc_state.keypress = capture_.key_pressed;
2043 aec_dump_->AddAudioProcessingState(audio_proc_state);
2044}
2045
kwiberg83ffe452016-08-29 14:46:07 -07002046AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002047 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002048 : aec_system_delay_jumps(-1),
2049 delay_offset_ms(0),
2050 was_stream_delay_set(false),
2051 last_stream_delay_ms(0),
2052 last_aec_system_delay_ms(0),
2053 stream_delay_jumps(-1),
2054 output_will_be_muted(false),
2055 key_pressed(false),
2056 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002057 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002058 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002059 echo_path_gain_change(false),
2060 prev_analog_mic_level(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002061
2062AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2063
2064AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2065
2066AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2067
niklase@google.com470e71d2011-07-07 08:21:25 +00002068} // namespace webrtc