blob: 398b5741743b7a9cf43e59e4d1cede43681ab9c5 [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 Loiko64cb83b2018-07-02 13:38:19 +0200368 false,
369 false,
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700370 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000371#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200372 config.Get<ExperimentalAgc>().enabled,
373 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loiko9489c3a2018-08-09 15:04:24 +0200374 config.Get<ExperimentalAgc>().digital_adaptive_disabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000375#endif
andrew1c7075f2015-06-24 18:14:14 -0700376#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200377 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700378#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200379 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700380#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200381 capture_nonlocked_() {
peahdf3efa82015-11-28 12:35:15 -0800382 {
383 rtc::CritScope cs_render(&crit_render_);
384 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000385
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200386 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000387 capture_nonlocked_.echo_controller_enabled =
388 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200389
peahb624d8c2016-03-05 03:01:14 -0800390 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700391 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800392 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700393 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
Sam Zackrisson74ed7342018-08-16 10:54:07 +0200394 public_submodules_->echo_cancellation_proxy.reset(new EchoCancellationProxy(
395 this, public_submodules_->echo_cancellation.get()));
396 public_submodules_->echo_control_mobile_proxy.reset(
397 new EchoControlMobileProxy(
398 this, public_submodules_->echo_control_mobile.get()));
peahbfa97112016-03-10 21:09:04 -0800399 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200400 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800401 public_submodules_->level_estimator.reset(
402 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800403 public_submodules_->noise_suppression.reset(
404 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800405 public_submodules_->voice_detection.reset(
406 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800407 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800408 new GainControlForExperimentalAgc(
409 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100410
411 // If no echo detector is injected, use the ResidualEchoDetector.
412 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200413 private_submodules_->echo_detector =
414 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100415 }
peahca4cac72016-06-29 15:26:12 -0700416
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200417 // TODO(alessiob): Move the injected gain controller once injection is
418 // implemented.
419 private_submodules_->gain_controller2.reset(new GainController2());
420
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200421 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
422 << !!private_submodules_->capture_analyzer
423 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100424 << !!private_submodules_->capture_post_processor
425 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100426 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800427 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000428
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000429 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000430}
431
432AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800433 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800434 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800435 private_submodules_->agc_manager.reset();
436 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800437 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000438}
439
niklase@google.com470e71d2011-07-07 08:21:25 +0000440int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800441 // Run in a single-threaded manner during initialization.
442 rtc::CritScope cs_render(&crit_render_);
443 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000444 return InitializeLocked();
445}
446
peahde65ddc2016-09-16 15:02:15 -0700447int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
448 int capture_output_sample_rate_hz,
449 int render_input_sample_rate_hz,
450 ChannelLayout capture_input_layout,
451 ChannelLayout capture_output_layout,
452 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700453 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700454 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
455 LayoutHasKeyboard(capture_input_layout)},
456 {capture_output_sample_rate_hz,
457 ChannelsFromLayout(capture_output_layout),
458 LayoutHasKeyboard(capture_output_layout)},
459 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
460 LayoutHasKeyboard(render_input_layout)},
461 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
462 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700463
464 return Initialize(processing_config);
465}
466
467int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800468 // Run in a single-threaded manner during initialization.
469 rtc::CritScope cs_render(&crit_render_);
470 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700471 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000472}
473
peahdf3efa82015-11-28 12:35:15 -0800474int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800475 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700476 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800477}
478
peahdf3efa82015-11-28 12:35:15 -0800479int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700480 const ProcessingConfig& processing_config,
481 bool force_initialization) {
482 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800483}
484
peah192164e2015-11-17 02:16:45 -0800485// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800486// their current values (needs to be called while holding the crit_render_lock).
487int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700488 const ProcessingConfig& processing_config,
489 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800490 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700491 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800492 return kNoError;
493 }
peahdf3efa82015-11-28 12:35:15 -0800494
495 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800496 return InitializeLocked(processing_config);
497}
498
niklase@google.com470e71d2011-07-07 08:21:25 +0000499int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200500 UpdateActiveSubmoduleStates();
501
peahde65ddc2016-09-16 15:02:15 -0700502 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800503 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700504 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800505 : formats_.api_format.reverse_output_stream().num_frames();
506 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
507 render_.render_audio.reset(new AudioBuffer(
508 formats_.api_format.reverse_input_stream().num_frames(),
509 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700510 formats_.render_processing_format.num_frames(),
511 formats_.render_processing_format.num_channels(),
512 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700513 if (formats_.api_format.reverse_input_stream() !=
514 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800515 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800516 formats_.api_format.reverse_input_stream().num_channels(),
517 formats_.api_format.reverse_input_stream().num_frames(),
518 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800519 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700520 } else {
peahdf3efa82015-11-28 12:35:15 -0800521 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700522 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700523 } else {
peahdf3efa82015-11-28 12:35:15 -0800524 render_.render_audio.reset(nullptr);
525 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700526 }
peahce4d9152017-05-19 01:28:05 -0700527
peahdf3efa82015-11-28 12:35:15 -0800528 capture_.capture_audio.reset(
529 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
530 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700531 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200532 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800533 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000534
peahde65ddc2016-09-16 15:02:15 -0700535 public_submodules_->echo_cancellation->Initialize(
536 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
537 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700538 AllocateRenderQueue();
539
ivoc3e9a5372016-10-28 07:55:33 -0700540 int success = public_submodules_->echo_cancellation->enable_metrics(true);
541 RTC_DCHECK_EQ(0, success);
542 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
543 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700544 public_submodules_->echo_control_mobile->Initialize(
545 proc_split_sample_rate_hz(), num_reverse_channels(),
546 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700547
548 public_submodules_->gain_control->Initialize(num_proc_channels(),
549 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700550 if (constants_.use_experimental_agc) {
551 if (!private_submodules_->agc_manager.get()) {
552 private_submodules_->agc_manager.reset(new AgcManagerDirect(
553 public_submodules_->gain_control.get(),
554 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200555 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
556 constants_.use_experimental_agc_agc2_level_estimation,
557 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700558 }
559 private_submodules_->agc_manager->Initialize();
560 private_submodules_->agc_manager->SetCaptureMuted(
561 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700562 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700563 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200564 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800565 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700566 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
567 proc_sample_rate_hz());
568 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
569 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700570 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200571 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700572 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200573 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200574 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100575 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800576
aleloi868f32f2017-05-23 07:20:05 -0700577 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200578 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700579 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000580 return kNoError;
581}
582
Michael Graczyk86c6d332015-07-23 11:41:39 -0700583int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200584 UpdateActiveSubmoduleStates();
585
Michael Graczyk86c6d332015-07-23 11:41:39 -0700586 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700587 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
588 return kBadSampleRateError;
589 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000590 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700591
Peter Kasting69558702016-01-12 16:26:35 -0800592 const size_t num_in_channels = config.input_stream().num_channels();
593 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700594
595 // Need at least one input channel.
596 // Need either one output channel or as many outputs as there are inputs.
597 if (num_in_channels == 0 ||
598 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700599 return kBadNumberChannelsError;
600 }
601
peahdf3efa82015-11-28 12:35:15 -0800602 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000603
peahde65ddc2016-09-16 15:02:15 -0700604 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700605 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700606 formats_.api_format.output_stream().sample_rate_hz()),
607 submodule_states_.CaptureMultiBandSubModulesActive() ||
608 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000609
peahde65ddc2016-09-16 15:02:15 -0700610 capture_nonlocked_.capture_processing_format =
611 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700612
peah2ce640f2017-04-07 03:57:48 -0700613 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200614 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700615 render_processing_rate = FindNativeProcessRateToUse(
616 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
617 formats_.api_format.reverse_output_stream().sample_rate_hz()),
618 submodule_states_.CaptureMultiBandSubModulesActive() ||
619 submodule_states_.RenderMultiBandSubModulesActive());
620 } else {
621 render_processing_rate = capture_processing_rate;
622 }
623
aluebseb3603b2016-04-20 15:27:58 -0700624 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
625 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700626 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200627 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700628 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
629 ? kSampleRate32kHz
630 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700631 }
peah2ce640f2017-04-07 03:57:48 -0700632
peahde65ddc2016-09-16 15:02:15 -0700633 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700634 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700635 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
636 kSampleRate8kHz) {
637 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000638 } else {
peahde65ddc2016-09-16 15:02:15 -0700639 render_processing_rate =
640 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000641 }
642
peahde65ddc2016-09-16 15:02:15 -0700643 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000644 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700645 if (submodule_states_.RenderMultiBandSubModulesActive()) {
646 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
647 } else {
648 formats_.render_processing_format = StreamConfig(
649 formats_.api_format.reverse_input_stream().sample_rate_hz(),
650 formats_.api_format.reverse_input_stream().num_channels());
651 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000652
peahde65ddc2016-09-16 15:02:15 -0700653 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
654 kSampleRate32kHz ||
655 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
656 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800657 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000658 } else {
peahdf3efa82015-11-28 12:35:15 -0800659 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700660 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000661 }
662
663 return InitializeLocked();
664}
665
peah88ac8532016-09-12 16:47:25 -0700666void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700667 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700668
peah88ac8532016-09-12 16:47:25 -0700669 // Run in a single-threaded manner when applying the settings.
670 rtc::CritScope cs_render(&crit_render_);
671 rtc::CritScope cs_capture(&crit_capture_);
672
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200673 static_cast<EchoCancellation*>(public_submodules_->echo_cancellation.get())
674 ->Enable(config_.echo_canceller.enabled &&
675 !config_.echo_canceller.mobile_mode);
676 static_cast<EchoControlMobile*>(public_submodules_->echo_control_mobile.get())
677 ->Enable(config_.echo_canceller.enabled &&
678 config_.echo_canceller.mobile_mode);
679
peah8271d042016-11-22 07:24:52 -0800680 InitializeLowCutFilter();
681
Mirko Bonadei675513b2017-11-09 11:09:25 +0100682 RTC_LOG(LS_INFO) << "Highpass filter activated: "
683 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800684
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100685 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700686 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100687 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
688 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100689 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100690 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700691 config_.gain_controller2 = AudioProcessing::Config::GainController2();
692 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200693 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200694 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200695 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100696 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
697 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200698 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
699 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700700}
701
702void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800703 // Run in a single-threaded manner when setting the extra options.
704 rtc::CritScope cs_render(&crit_render_);
705 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000706
peahb624d8c2016-03-05 03:01:14 -0800707 public_submodules_->echo_cancellation->SetExtraOptions(config);
708
peahdf3efa82015-11-28 12:35:15 -0800709 if (capture_.transient_suppressor_enabled !=
710 config.Get<ExperimentalNs>().enabled) {
711 capture_.transient_suppressor_enabled =
712 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000713 InitializeTransient();
714 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000715}
716
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000717int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800718 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700719 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000720}
721
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000722int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800723 // Used as callback from submodules, hence locking is not allowed.
724 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
Peter Kasting69558702016-01-12 16:26:35 -0800727size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800728 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700729 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000730}
731
Peter Kasting69558702016-01-12 16:26:35 -0800732size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800733 // Used as callback from submodules, hence locking is not allowed.
734 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000735}
736
Peter Kasting69558702016-01-12 16:26:35 -0800737size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800738 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200739 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800740}
741
Peter Kasting69558702016-01-12 16:26:35 -0800742size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800743 // Used as callback from submodules, hence locking is not allowed.
744 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000745}
746
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000747void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800748 rtc::CritScope cs(&crit_capture_);
749 capture_.output_will_be_muted = muted;
750 if (private_submodules_->agc_manager.get()) {
751 private_submodules_->agc_manager->SetCaptureMuted(
752 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000753 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000754}
755
Alessio Bazzicac054e782018-04-16 12:10:09 +0200756void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200757 switch (setting.type()) {
758 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
759 render_runtime_settings_enqueuer_.Enqueue(setting);
760 return;
761 case RuntimeSetting::Type::kNotSpecified:
762 RTC_NOTREACHED();
763 return;
764 case RuntimeSetting::Type::kCapturePreGain:
765 capture_runtime_settings_enqueuer_.Enqueue(setting);
766 return;
767 }
768 // The language allows the enum to have a non-enumerator
769 // value. Check that this doesn't happen.
770 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200771}
772
773AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
774 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200775 : runtime_settings_(*runtime_settings) {
776 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200777}
778
779AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
780 default;
781
782void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
783 RuntimeSetting setting) {
784 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200785 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200786 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200787 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200788 RTC_LOG(LS_ERROR)
789 << "The runtime settings queue is full. Oldest setting discarded.";
790 }
791 if (remaining_attempts == 0)
792 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
793}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000794
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000795int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700796 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000797 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000798 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000799 int output_sample_rate_hz,
800 ChannelLayout output_layout,
801 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800802 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800803 StreamConfig input_stream;
804 StreamConfig output_stream;
805 {
806 // Access the formats_.api_format.input_stream beneath the capture lock.
807 // The lock must be released as it is later required in the call
808 // to ProcessStream(,,,);
809 rtc::CritScope cs(&crit_capture_);
810 input_stream = formats_.api_format.input_stream();
811 output_stream = formats_.api_format.output_stream();
812 }
813
Michael Graczyk86c6d332015-07-23 11:41:39 -0700814 input_stream.set_sample_rate_hz(input_sample_rate_hz);
815 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
816 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700817 output_stream.set_sample_rate_hz(output_sample_rate_hz);
818 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
819 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
820
821 if (samples_per_channel != input_stream.num_frames()) {
822 return kBadDataLengthError;
823 }
824 return ProcessStream(src, input_stream, output_stream, dest);
825}
826
827int AudioProcessingImpl::ProcessStream(const float* const* src,
828 const StreamConfig& input_config,
829 const StreamConfig& output_config,
830 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800831 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800832 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700833 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800834 {
835 // Acquire the capture lock in order to safely call the function
836 // that retrieves the render side data. This function accesses apm
837 // getters that need the capture lock held when being called.
838 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700839 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800840
841 if (!src || !dest) {
842 return kNullPointerError;
843 }
844
845 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700846 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000847 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000848
Michael Graczyk86c6d332015-07-23 11:41:39 -0700849 processing_config.input_stream() = input_config;
850 processing_config.output_stream() = output_config;
851
peahdf3efa82015-11-28 12:35:15 -0800852 {
853 // Do conditional reinitialization.
854 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700855 RETURN_ON_ERR(
856 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800857 }
858 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700859 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
860 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000861
aleloi868f32f2017-05-23 07:20:05 -0700862 if (aec_dump_) {
863 RecordUnprocessedCaptureStream(src);
864 }
865
peahdf3efa82015-11-28 12:35:15 -0800866 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700867 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800868 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000869
aleloi868f32f2017-05-23 07:20:05 -0700870 if (aec_dump_) {
871 RecordProcessedCaptureStream(dest);
872 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000873 return kNoError;
874}
875
Alex Loiko73ec0192018-05-15 10:52:28 +0200876void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200877 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200878 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200879 if (aec_dump_) {
880 aec_dump_->WriteRuntimeSetting(setting);
881 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200882 switch (setting.type()) {
883 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200884 if (config_.pre_amplifier.enabled) {
885 float value;
886 setting.GetFloat(&value);
887 private_submodules_->pre_amplifier->SetGainFactor(value);
888 }
889 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200890 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200891 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
892 RTC_NOTREACHED();
893 break;
894 case RuntimeSetting::Type::kNotSpecified:
895 RTC_NOTREACHED();
896 break;
897 }
898 }
899}
900
901void AudioProcessingImpl::HandleRenderRuntimeSettings() {
902 RuntimeSetting setting;
903 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200904 if (aec_dump_) {
905 aec_dump_->WriteRuntimeSetting(setting);
906 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200907 switch (setting.type()) {
908 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
909 if (private_submodules_->render_pre_processor) {
910 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
911 }
912 break;
913 case RuntimeSetting::Type::kCapturePreGain:
914 RTC_NOTREACHED();
915 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200916 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200917 RTC_NOTREACHED();
918 break;
919 }
920 }
921}
922
peah9e6a2902017-05-15 07:19:21 -0700923void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700924 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
925 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700926 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700927
kwibergaf476c72016-11-28 15:21:39 -0800928 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700929
930 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700931 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700932 // The data queue is full and needs to be emptied.
933 EmptyQueuedRenderAudio();
934
935 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700936 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700937 RTC_DCHECK(result);
938 }
939
940 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
941 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700942 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700943
944 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700945 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700946 // The data queue is full and needs to be emptied.
947 EmptyQueuedRenderAudio();
948
949 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700950 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700951 RTC_DCHECK(result);
952 }
peah701d6282016-10-25 05:42:20 -0700953
954 if (!constants_.use_experimental_agc) {
955 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
956 // Insert the samples into the queue.
957 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
958 // The data queue is full and needs to be emptied.
959 EmptyQueuedRenderAudio();
960
961 // Retry the insert (should always work).
962 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
963 RTC_DCHECK(result);
964 }
965 }
peah9e6a2902017-05-15 07:19:21 -0700966}
ivoc9f4a4a02016-10-28 05:39:16 -0700967
peah9e6a2902017-05-15 07:19:21 -0700968void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700969 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
970
971 // Insert the samples into the queue.
972 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
973 // The data queue is full and needs to be emptied.
974 EmptyQueuedRenderAudio();
975
976 // Retry the insert (should always work).
977 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
978 RTC_DCHECK(result);
979 }
peah764e3642016-10-22 05:04:30 -0700980}
981
982void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700983 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700984 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700985 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700986 EchoCancellationImpl::NumCancellersRequired(
987 num_output_channels(), num_reverse_channels()));
988
peah701d6282016-10-25 05:42:20 -0700989 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700990 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700991 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700992 EchoControlMobileImpl::NumCancellersRequired(
993 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700994
peah701d6282016-10-25 05:42:20 -0700995 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700996 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700997
ivoc9f4a4a02016-10-28 05:39:16 -0700998 const size_t new_red_render_queue_element_max_size =
999 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1000
peaha0624602016-10-25 04:45:24 -07001001 // Reallocate the queues if the queue item sizes are too small to fit the
1002 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001003 if (aec_render_queue_element_max_size_ <
1004 new_aec_render_queue_element_max_size) {
1005 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001006
peaha0624602016-10-25 04:45:24 -07001007 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001008 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001009
peah701d6282016-10-25 05:42:20 -07001010 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001011 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1012 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001013 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001014 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001015
peah701d6282016-10-25 05:42:20 -07001016 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1017 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001018 } else {
peah701d6282016-10-25 05:42:20 -07001019 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001020 }
1021
peah701d6282016-10-25 05:42:20 -07001022 if (aecm_render_queue_element_max_size_ <
1023 new_aecm_render_queue_element_max_size) {
1024 aecm_render_queue_element_max_size_ =
1025 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001026
1027 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001028 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001029
peah701d6282016-10-25 05:42:20 -07001030 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001031 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1032 kMaxNumFramesToBuffer, template_queue_element,
1033 RenderQueueItemVerifier<int16_t>(
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_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1037 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001038 } else {
peah701d6282016-10-25 05:42:20 -07001039 aecm_render_signal_queue_->Clear();
1040 }
1041
1042 if (agc_render_queue_element_max_size_ <
1043 new_agc_render_queue_element_max_size) {
1044 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1045
1046 std::vector<int16_t> template_queue_element(
1047 agc_render_queue_element_max_size_);
1048
1049 agc_render_signal_queue_.reset(
1050 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1051 kMaxNumFramesToBuffer, template_queue_element,
1052 RenderQueueItemVerifier<int16_t>(
1053 agc_render_queue_element_max_size_)));
1054
1055 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1056 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1057 } else {
1058 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001059 }
ivoc9f4a4a02016-10-28 05:39:16 -07001060
1061 if (red_render_queue_element_max_size_ <
1062 new_red_render_queue_element_max_size) {
1063 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1064
1065 std::vector<float> template_queue_element(
1066 red_render_queue_element_max_size_);
1067
1068 red_render_signal_queue_.reset(
1069 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1070 kMaxNumFramesToBuffer, template_queue_element,
1071 RenderQueueItemVerifier<float>(
1072 red_render_queue_element_max_size_)));
1073
1074 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1075 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1076 } else {
1077 red_render_signal_queue_->Clear();
1078 }
peah764e3642016-10-22 05:04:30 -07001079}
1080
1081void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1082 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001083 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001084 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001085 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001086 }
1087
peah701d6282016-10-25 05:42:20 -07001088 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001089 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001090 aecm_capture_queue_buffer_);
1091 }
1092
1093 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1094 public_submodules_->gain_control->ProcessRenderAudio(
1095 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001096 }
ivoc9f4a4a02016-10-28 05:39:16 -07001097
1098 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001099 RTC_DCHECK(private_submodules_->echo_detector);
1100 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001101 red_capture_queue_buffer_);
1102 }
peah764e3642016-10-22 05:04:30 -07001103}
1104
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001105int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001106 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001107 {
1108 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001109 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001110 // getters that need the capture lock held when being called.
1111 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001112 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001113 // as well.
1114 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001115 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001116 }
peahfa6228e2015-11-16 16:27:42 -08001117
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001118 if (!frame) {
1119 return kNullPointerError;
1120 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001121 // Must be a native rate.
1122 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1123 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001124 frame->sample_rate_hz_ != kSampleRate32kHz &&
1125 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001126 return kBadSampleRateError;
1127 }
peah192164e2015-11-17 02:16:45 -08001128
peahdf3efa82015-11-28 12:35:15 -08001129 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001130 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001131 {
1132 // Aquire lock for the access of api_format.
1133 // The lock is released immediately due to the conditional
1134 // reinitialization.
1135 rtc::CritScope cs_capture(&crit_capture_);
1136 // TODO(ajm): The input and output rates and channels are currently
1137 // constrained to be identical in the int16 interface.
1138 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001139
1140 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001141 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001142 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1143 processing_config.input_stream().set_num_channels(frame->num_channels_);
1144 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1145 processing_config.output_stream().set_num_channels(frame->num_channels_);
1146
peahdf3efa82015-11-28 12:35:15 -08001147 {
1148 // Do conditional reinitialization.
1149 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001150 RETURN_ON_ERR(
1151 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001152 }
1153 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001154 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001155 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001156 return kBadDataLengthError;
1157 }
1158
aleloi868f32f2017-05-23 07:20:05 -07001159 if (aec_dump_) {
1160 RecordUnprocessedCaptureStream(*frame);
1161 }
1162
peahdf3efa82015-11-28 12:35:15 -08001163 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001164 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001165 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001166 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1167 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001168
aleloi868f32f2017-05-23 07:20:05 -07001169 if (aec_dump_) {
1170 RecordProcessedCaptureStream(*frame);
1171 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001172
1173 return kNoError;
1174}
1175
peahde65ddc2016-09-16 15:02:15 -07001176int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001177 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001178
peahb58a1582016-03-15 09:34:24 -07001179 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001180 // TODO(peah): Simplify once the public API Enable functions for these
1181 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001182 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1183 public_submodules_->echo_control_mobile->is_enabled()));
1184
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001185 MaybeUpdateHistograms();
1186
peahde65ddc2016-09-16 15:02:15 -07001187 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001188
Alex Loikob5c9a792018-04-16 16:31:22 +02001189 if (private_submodules_->pre_amplifier) {
1190 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1191 capture_buffer->channels_f(), capture_buffer->num_channels(),
1192 capture_buffer->num_frames()));
1193 }
1194
peah1b08dc32016-12-20 13:45:58 -08001195 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001196 capture_buffer->channels_const()[0],
1197 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001198 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1199 if (log_rms) {
1200 capture_rms_interval_counter_ = 0;
1201 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001202 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1203 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1204 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1205 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001206 }
1207
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001208 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001209 // Detect and flag any change in the analog gain.
1210 int analog_mic_level = gain_control()->stream_analog_level();
1211 capture_.echo_path_gain_change =
1212 capture_.prev_analog_mic_level != analog_mic_level &&
1213 capture_.prev_analog_mic_level != -1;
1214 capture_.prev_analog_mic_level = analog_mic_level;
1215
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001216 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001217 }
1218
peahbe615622016-02-13 16:40:47 -08001219 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001220 public_submodules_->gain_control->is_enabled()) {
1221 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001222 capture_buffer->channels()[0], capture_buffer->num_channels(),
1223 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001224 }
1225
peah2ace3f92016-09-10 04:42:27 -07001226 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1227 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001228 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1229 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001230 }
1231
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001232 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001233 // Force down-mixing of the number of channels after the detection of
1234 // capture signal saturation.
1235 // TODO(peah): Look into ensuring that this kind of tampering with the
1236 // AudioBuffer functionality should not be needed.
1237 capture_buffer->set_num_channels(1);
1238 }
1239
peahe0eae3c2016-12-14 01:16:23 -08001240 // TODO(peah): Move the AEC3 low-cut filter to this place.
1241 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001242 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001243 private_submodules_->low_cut_filter->Process(capture_buffer);
1244 }
peahde65ddc2016-09-16 15:02:15 -07001245 RETURN_ON_ERR(
1246 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1247 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001248
1249 // Ensure that the stream delay was set before the call to the
1250 // AEC ProcessCaptureAudio function.
1251 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001252 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001253 return AudioProcessing::kStreamParameterNotSetError;
1254 }
1255
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001256 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001257 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1258
Per Åhgrend0fa8202018-04-18 09:35:13 +02001259 if (was_stream_delay_set()) {
1260 private_submodules_->echo_controller->SetAudioBufferDelay(
1261 stream_delay_ms());
1262 }
1263
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001264 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001265 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001266 } else {
1267 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1268 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001269 }
1270
peahdf3efa82015-11-28 12:35:15 -08001271 if (public_submodules_->echo_control_mobile->is_enabled() &&
1272 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001273 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001274 }
peahde65ddc2016-09-16 15:02:15 -07001275 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001276
1277 // Ensure that the stream delay was set before the call to the
1278 // AECM ProcessCaptureAudio function.
1279 if (public_submodules_->echo_control_mobile->is_enabled() &&
1280 !was_stream_delay_set()) {
1281 return AudioProcessing::kStreamParameterNotSetError;
1282 }
1283
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001284 if (!(private_submodules_->echo_controller ||
1285 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001286 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1287 capture_buffer, stream_delay_ms()));
1288 }
ivoc9f4a4a02016-10-28 05:39:16 -07001289
peahde65ddc2016-09-16 15:02:15 -07001290 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001291
peahbe615622016-02-13 16:40:47 -08001292 if (constants_.use_experimental_agc &&
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001293 public_submodules_->gain_control->is_enabled()) {
peahdf3efa82015-11-28 12:35:15 -08001294 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001295 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1296 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001297 }
peahb8fbb542016-03-15 02:28:08 -07001298 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001299 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001300
peah2ace3f92016-09-10 04:42:27 -07001301 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1302 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001303 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1304 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001305 }
1306
peah9e6a2902017-05-15 07:19:21 -07001307 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001308 RTC_DCHECK(private_submodules_->echo_detector);
1309 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001310 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1311 capture_buffer->num_frames()));
1312 }
1313
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001314 // TODO(aluebs): Investigate if the transient suppression placement should be
1315 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001316 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001317 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001318 private_submodules_->agc_manager.get()
1319 ? private_submodules_->agc_manager->voice_probability()
1320 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001321
peahdf3efa82015-11-28 12:35:15 -08001322 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001323 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1324 capture_buffer->num_channels(),
1325 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1326 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1327 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001328 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001329 }
1330
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001331 // Experimental APM sub-module that analyzes |capture_buffer|.
1332 if (private_submodules_->capture_analyzer) {
1333 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1334 }
1335
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001336 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001337 private_submodules_->gain_controller2->NotifyAnalogLevel(
1338 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001339 private_submodules_->gain_controller2->Process(capture_buffer);
1340 }
1341
Sam Zackrisson0beac582017-09-25 12:04:02 +02001342 if (private_submodules_->capture_post_processor) {
1343 private_submodules_->capture_post_processor->Process(capture_buffer);
1344 }
1345
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001346 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001347 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001348
peah1b08dc32016-12-20 13:45:58 -08001349 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1350 capture_buffer->channels_const()[0],
1351 capture_nonlocked_.capture_processing_format.num_frames()));
1352 if (log_rms) {
1353 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1354 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1355 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1356 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1357 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1358 }
1359
peahdf3efa82015-11-28 12:35:15 -08001360 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001361 return kNoError;
1362}
1363
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001364int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001365 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001366 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001367 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001368 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001369 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001370 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001371 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001372 };
1373 if (samples_per_channel != reverse_config.num_frames()) {
1374 return kBadDataLengthError;
1375 }
peahdf3efa82015-11-28 12:35:15 -08001376 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001377}
1378
peahde65ddc2016-09-16 15:02:15 -07001379int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1380 const StreamConfig& input_config,
1381 const StreamConfig& output_config,
1382 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001383 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001384 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001385 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001386 if (submodule_states_.RenderMultiBandProcessingActive() ||
1387 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001388 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1389 dest);
peah2ace3f92016-09-10 04:42:27 -07001390 } else if (formats_.api_format.reverse_input_stream() !=
1391 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001392 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1393 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001394 } else {
peahde65ddc2016-09-16 15:02:15 -07001395 CopyAudioIfNeeded(src, input_config.num_frames(),
1396 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001397 }
1398
1399 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001400}
1401
peahdf3efa82015-11-28 12:35:15 -08001402int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001403 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001404 const StreamConfig& input_config,
1405 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001406 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001407 return kNullPointerError;
1408 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001409
peahde65ddc2016-09-16 15:02:15 -07001410 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001411 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001412 }
1413
peahdf3efa82015-11-28 12:35:15 -08001414 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001415 processing_config.reverse_input_stream() = input_config;
1416 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001417
peahdf3efa82015-11-28 12:35:15 -08001418 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001419 RTC_DCHECK_EQ(input_config.num_frames(),
1420 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001421
aleloi868f32f2017-05-23 07:20:05 -07001422 if (aec_dump_) {
1423 const size_t channel_size =
1424 formats_.api_format.reverse_input_stream().num_frames();
1425 const size_t num_channels =
1426 formats_.api_format.reverse_input_stream().num_channels();
1427 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001428 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001429 }
peahdf3efa82015-11-28 12:35:15 -08001430 render_.render_audio->CopyFrom(src,
1431 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001432 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001433}
1434
1435int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001436 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001437 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001438 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001439 return kNullPointerError;
1440 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001441 // Must be a native rate.
1442 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1443 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001444 frame->sample_rate_hz_ != kSampleRate32kHz &&
1445 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001446 return kBadSampleRateError;
1447 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001448
Michael Graczyk86c6d332015-07-23 11:41:39 -07001449 if (frame->num_channels_ <= 0) {
1450 return kBadNumberChannelsError;
1451 }
1452
peahdf3efa82015-11-28 12:35:15 -08001453 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001454 processing_config.reverse_input_stream().set_sample_rate_hz(
1455 frame->sample_rate_hz_);
1456 processing_config.reverse_input_stream().set_num_channels(
1457 frame->num_channels_);
1458 processing_config.reverse_output_stream().set_sample_rate_hz(
1459 frame->sample_rate_hz_);
1460 processing_config.reverse_output_stream().set_num_channels(
1461 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001462
peahdf3efa82015-11-28 12:35:15 -08001463 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001464 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001465 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001466 return kBadDataLengthError;
1467 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001468
aleloi868f32f2017-05-23 07:20:05 -07001469 if (aec_dump_) {
1470 aec_dump_->WriteRenderStreamMessage(*frame);
1471 }
1472
peahdf3efa82015-11-28 12:35:15 -08001473 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001474 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001475 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001476 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1477 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001478 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001479}
niklase@google.com470e71d2011-07-07 08:21:25 +00001480
peahde65ddc2016-09-16 15:02:15 -07001481int AudioProcessingImpl::ProcessRenderStreamLocked() {
1482 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001483
Alex Loiko73ec0192018-05-15 10:52:28 +02001484 HandleRenderRuntimeSettings();
1485
Alex Loiko5825aa62017-12-18 16:02:40 +01001486 if (private_submodules_->render_pre_processor) {
1487 private_submodules_->render_pre_processor->Process(render_buffer);
1488 }
1489
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001490 QueueNonbandedRenderAudio(render_buffer);
1491
peah2ace3f92016-09-10 04:42:27 -07001492 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001493 SampleRateSupportsMultiBand(
1494 formats_.render_processing_format.sample_rate_hz())) {
1495 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001496 }
1497
peahce4d9152017-05-19 01:28:05 -07001498 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1499 QueueBandedRenderAudio(render_buffer);
1500 }
1501
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001502 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001503 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001504 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001505 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001506
peah2ace3f92016-09-10 04:42:27 -07001507 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001508 SampleRateSupportsMultiBand(
1509 formats_.render_processing_format.sample_rate_hz())) {
1510 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001511 }
1512
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001513 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001514}
1515
1516int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001517 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001518 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001519 capture_.was_stream_delay_set = true;
1520 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001521
niklase@google.com470e71d2011-07-07 08:21:25 +00001522 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001523 delay = 0;
1524 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001525 }
1526
1527 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1528 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001529 delay = 500;
1530 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001531 }
1532
peahdf3efa82015-11-28 12:35:15 -08001533 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001534 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001535}
1536
1537int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001538 // Used as callback from submodules, hence locking is not allowed.
1539 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001540}
1541
1542bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001543 // Used as callback from submodules, hence locking is not allowed.
1544 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001545}
1546
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001547void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001548 rtc::CritScope cs(&crit_capture_);
1549 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001550}
1551
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001552void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001553 rtc::CritScope cs(&crit_capture_);
1554 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001555}
1556
1557int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001558 rtc::CritScope cs(&crit_capture_);
1559 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001560}
1561
aleloi868f32f2017-05-23 07:20:05 -07001562void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1563 RTC_DCHECK(aec_dump);
1564 rtc::CritScope cs_render(&crit_render_);
1565 rtc::CritScope cs_capture(&crit_capture_);
1566
1567 // The previously attached AecDump will be destroyed with the
1568 // 'aec_dump' parameter, which is after locks are released.
1569 aec_dump_.swap(aec_dump);
1570 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001571 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001572}
1573
1574void AudioProcessingImpl::DetachAecDump() {
1575 // The d-tor of a task-queue based AecDump blocks until all pending
1576 // tasks are done. This construction avoids blocking while holding
1577 // the render and capture locks.
1578 std::unique_ptr<AecDump> aec_dump = nullptr;
1579 {
1580 rtc::CritScope cs_render(&crit_render_);
1581 rtc::CritScope cs_capture(&crit_capture_);
1582 aec_dump = std::move(aec_dump_);
1583 }
1584}
1585
Sam Zackrisson4d364492018-03-02 16:03:21 +01001586void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1587 std::unique_ptr<AudioGenerator> audio_generator) {
1588 // TODO(bugs.webrtc.org/8882) Stub.
1589 // Reset internal audio generator with audio_generator.
1590}
1591
1592void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1593 // TODO(bugs.webrtc.org/8882) Stub.
1594 // Delete audio generator, if one is attached.
1595}
1596
ivoc4e477a12017-01-15 08:29:46 -08001597AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1598 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1599 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1600 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1601 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1602}
1603
1604AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1605 const AudioProcessingStatistics& other) = default;
1606
1607AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1608 default;
1609
ivoc3e9a5372016-10-28 07:55:33 -07001610// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1611AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1612 const {
1613 return AudioProcessingStatistics();
1614}
1615
Ivo Creusenae026092017-11-20 13:07:16 +01001616// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001617AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001618 bool has_remote_tracks) const {
1619 return AudioProcessingStats();
1620}
1621
ivoc3e9a5372016-10-28 07:55:33 -07001622AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1623 const {
1624 AudioProcessingStatistics stats;
1625 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001626 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001627 rtc::CritScope cs_capture(&crit_capture_);
1628 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1629 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1630 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1631 // Instant value will also be used for min, max and average.
1632 stats.echo_return_loss.Set(erl, erl, erl, erl);
1633 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1634 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1635 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001636 stats.a_nlp.Set(metrics.a_nlp);
1637 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1638 stats.echo_return_loss.Set(metrics.echo_return_loss);
1639 stats.echo_return_loss_enhancement.Set(
1640 metrics.echo_return_loss_enhancement);
1641 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1642 }
ivoc9c192b22017-03-16 04:22:14 -07001643 {
1644 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001645 RTC_DCHECK(private_submodules_->echo_detector);
1646 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1647 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001648 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001649 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001650 }
ivoc3e9a5372016-10-28 07:55:33 -07001651 public_submodules_->echo_cancellation->GetDelayMetrics(
1652 &stats.delay_median, &stats.delay_standard_deviation,
1653 &stats.fraction_poor_delays);
1654 return stats;
1655}
1656
Ivo Creusen56d46092017-11-24 17:29:59 +01001657AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001658 bool has_remote_tracks) const {
1659 AudioProcessingStats stats;
1660 if (has_remote_tracks) {
1661 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001662 if (private_submodules_->echo_controller) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001663 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001664 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1665 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001666 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001667 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001668 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001669 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1670 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001671 if (metrics.divergent_filter_fraction != -1.0f) {
1672 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001673 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001674 }
1675 if (metrics.echo_return_loss.instant != -100) {
1676 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001677 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001678 }
1679 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001680 stats.echo_return_loss_enhancement = absl::optional<double>(
1681 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001682 }
1683 }
1684 if (config_.residual_echo_detector.enabled) {
1685 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001686 RTC_DCHECK(private_submodules_->echo_detector);
1687 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1688 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001689 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001690 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001691 }
1692 int delay_median, delay_std;
1693 float fraction_poor_delays;
1694 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1695 &delay_median, &delay_std, &fraction_poor_delays) ==
1696 Error::kNoError) {
1697 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001698 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001699 }
1700 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001701 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001702 }
1703 }
1704 }
1705 return stats;
1706}
1707
niklase@google.com470e71d2011-07-07 08:21:25 +00001708EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001709 return public_submodules_->echo_cancellation_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001710}
1711
1712EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001713 return public_submodules_->echo_control_mobile_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001714}
1715
1716GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001717 if (constants_.use_experimental_agc) {
1718 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001719 }
peahbfa97112016-03-10 21:09:04 -08001720 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001721}
1722
1723HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001724 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001725}
1726
1727LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001728 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001729}
1730
1731NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001732 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001733}
1734
1735VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001736 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001737}
1738
peah8271d042016-11-22 07:24:52 -08001739void AudioProcessingImpl::MutateConfig(
1740 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1741 rtc::CritScope cs_render(&crit_render_);
1742 rtc::CritScope cs_capture(&crit_capture_);
1743 mutator(&config_);
1744 ApplyConfig(config_);
1745}
1746
1747AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1748 rtc::CritScope cs_render(&crit_render_);
1749 rtc::CritScope cs_capture(&crit_capture_);
1750 return config_;
1751}
1752
peah2ace3f92016-09-10 04:42:27 -07001753bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1754 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001755 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001756 public_submodules_->echo_cancellation->is_enabled(),
1757 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001758 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001759 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001760 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001761 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001762 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001763 public_submodules_->voice_detection->is_enabled(),
1764 public_submodules_->level_estimator->is_enabled(),
1765 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001766}
1767
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001768
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001769void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001770 if (capture_.transient_suppressor_enabled) {
1771 if (!public_submodules_->transient_suppressor.get()) {
1772 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001773 }
peahdf3efa82015-11-28 12:35:15 -08001774 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001775 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1776 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001777 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001778}
1779
peah8271d042016-11-22 07:24:52 -08001780void AudioProcessingImpl::InitializeLowCutFilter() {
1781 if (config_.high_pass_filter.enabled) {
1782 private_submodules_->low_cut_filter.reset(
1783 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1784 } else {
1785 private_submodules_->low_cut_filter.reset();
1786 }
1787}
alessiob3ec96df2017-05-22 06:57:06 -07001788
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001789void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001790 if (echo_control_factory_) {
1791 private_submodules_->echo_controller =
1792 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001793 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001794 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001795 }
1796}
peah8271d042016-11-22 07:24:52 -08001797
alessiob3ec96df2017-05-22 06:57:06 -07001798void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001799 if (config_.gain_controller2.enabled) {
1800 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001801 }
1802}
1803
Alex Loikob5c9a792018-04-16 16:31:22 +02001804void AudioProcessingImpl::InitializePreAmplifier() {
1805 if (config_.pre_amplifier.enabled) {
1806 private_submodules_->pre_amplifier.reset(
1807 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1808 } else {
1809 private_submodules_->pre_amplifier.reset();
1810 }
1811}
1812
ivoc9f4a4a02016-10-28 05:39:16 -07001813void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001814 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001815 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001816 proc_sample_rate_hz(), 1,
1817 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001818}
1819
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001820void AudioProcessingImpl::InitializeAnalyzer() {
1821 if (private_submodules_->capture_analyzer) {
1822 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1823 num_proc_channels());
1824 }
1825}
1826
Sam Zackrisson0beac582017-09-25 12:04:02 +02001827void AudioProcessingImpl::InitializePostProcessor() {
1828 if (private_submodules_->capture_post_processor) {
1829 private_submodules_->capture_post_processor->Initialize(
1830 proc_sample_rate_hz(), num_proc_channels());
1831 }
1832}
1833
Alex Loiko5825aa62017-12-18 16:02:40 +01001834void AudioProcessingImpl::InitializePreProcessor() {
1835 if (private_submodules_->render_pre_processor) {
1836 private_submodules_->render_pre_processor->Initialize(
1837 formats_.render_processing_format.sample_rate_hz(),
1838 formats_.render_processing_format.num_channels());
1839 }
1840}
1841
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001842void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001843 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001844
1845 if (echo_cancellation()->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001846 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1847 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001848 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001849 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001850 capture_.stream_delay_jumps = 0;
1851 }
1852 if (capture_.aec_system_delay_jumps == -1 &&
1853 echo_cancellation()->stream_has_echo()) {
1854 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001855 }
1856
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001857 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001858 const int diff_stream_delay_ms =
1859 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1860 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1861 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001862 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1863 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001864 if (capture_.stream_delay_jumps == -1) {
1865 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001866 }
peahdf3efa82015-11-28 12:35:15 -08001867 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001868 }
peahdf3efa82015-11-28 12:35:15 -08001869 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001870
1871 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001872 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001873 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001874 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001875 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001876 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1877 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001878 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001879 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001880 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001881 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001882 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1883 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1884 100);
peahdf3efa82015-11-28 12:35:15 -08001885 if (capture_.aec_system_delay_jumps == -1) {
1886 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001887 }
peahdf3efa82015-11-28 12:35:15 -08001888 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001889 }
peahdf3efa82015-11-28 12:35:15 -08001890 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001891 }
1892}
1893
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001894void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001895 // Run in a single-threaded manner.
1896 rtc::CritScope cs_render(&crit_render_);
1897 rtc::CritScope cs_capture(&crit_capture_);
1898
1899 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001900 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001901 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001902 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001903 }
peahdf3efa82015-11-28 12:35:15 -08001904 capture_.stream_delay_jumps = -1;
1905 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001906
peahdf3efa82015-11-28 12:35:15 -08001907 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001908 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1909 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001910 }
peahdf3efa82015-11-28 12:35:15 -08001911 capture_.aec_system_delay_jumps = -1;
1912 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001913}
1914
aleloi868f32f2017-05-23 07:20:05 -07001915void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1916 if (!aec_dump_) {
1917 return;
1918 }
1919 std::string experiments_description =
1920 public_submodules_->echo_cancellation->GetExperimentsDescription();
1921 // TODO(peah): Add semicolon-separated concatenations of experiment
1922 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001923 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1924 experiments_description += "AgcClippingLevelExperiment;";
1925 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001926 if (capture_nonlocked_.echo_controller_enabled) {
1927 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001928 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001929 if (config_.gain_controller2.enabled) {
1930 experiments_description += "GainController2;";
1931 }
aleloi868f32f2017-05-23 07:20:05 -07001932
1933 InternalAPMConfig apm_config;
1934
1935 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1936 apm_config.aec_delay_agnostic_enabled =
1937 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1938 apm_config.aec_drift_compensation_enabled =
1939 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1940 apm_config.aec_extended_filter_enabled =
1941 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1942 apm_config.aec_suppression_level = static_cast<int>(
1943 public_submodules_->echo_cancellation->suppression_level());
1944
1945 apm_config.aecm_enabled =
1946 public_submodules_->echo_control_mobile->is_enabled();
1947 apm_config.aecm_comfort_noise_enabled =
1948 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1949 apm_config.aecm_routing_mode =
1950 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1951
1952 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1953 apm_config.agc_mode =
1954 static_cast<int>(public_submodules_->gain_control->mode());
1955 apm_config.agc_limiter_enabled =
1956 public_submodules_->gain_control->is_limiter_enabled();
1957 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1958
1959 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1960
1961 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1962 apm_config.ns_level =
1963 static_cast<int>(public_submodules_->noise_suppression->level());
1964
1965 apm_config.transient_suppression_enabled =
1966 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001967 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001968 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1969 apm_config.pre_amplifier_fixed_gain_factor =
1970 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001971
1972 if (!forced && apm_config == apm_config_for_aec_dump_) {
1973 return;
1974 }
1975 aec_dump_->WriteConfig(apm_config);
1976 apm_config_for_aec_dump_ = apm_config;
1977}
1978
1979void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1980 const float* const* src) {
1981 RTC_DCHECK(aec_dump_);
1982 WriteAecDumpConfigMessage(false);
1983
1984 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1985 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1986 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001987 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001988 RecordAudioProcessingState();
1989}
1990
1991void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1992 const AudioFrame& capture_frame) {
1993 RTC_DCHECK(aec_dump_);
1994 WriteAecDumpConfigMessage(false);
1995
1996 aec_dump_->AddCaptureStreamInput(capture_frame);
1997 RecordAudioProcessingState();
1998}
1999
2000void AudioProcessingImpl::RecordProcessedCaptureStream(
2001 const float* const* processed_capture_stream) {
2002 RTC_DCHECK(aec_dump_);
2003
2004 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2005 const size_t num_channels =
2006 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002007 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2008 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002009 aec_dump_->WriteCaptureStreamMessage();
2010}
2011
2012void AudioProcessingImpl::RecordProcessedCaptureStream(
2013 const AudioFrame& processed_capture_frame) {
2014 RTC_DCHECK(aec_dump_);
2015
2016 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2017 aec_dump_->WriteCaptureStreamMessage();
2018}
2019
2020void AudioProcessingImpl::RecordAudioProcessingState() {
2021 RTC_DCHECK(aec_dump_);
2022 AecDump::AudioProcessingState audio_proc_state;
2023 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2024 audio_proc_state.drift =
2025 public_submodules_->echo_cancellation->stream_drift_samples();
2026 audio_proc_state.level = gain_control()->stream_analog_level();
2027 audio_proc_state.keypress = capture_.key_pressed;
2028 aec_dump_->AddAudioProcessingState(audio_proc_state);
2029}
2030
kwiberg83ffe452016-08-29 14:46:07 -07002031AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002032 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002033 : aec_system_delay_jumps(-1),
2034 delay_offset_ms(0),
2035 was_stream_delay_set(false),
2036 last_stream_delay_ms(0),
2037 last_aec_system_delay_ms(0),
2038 stream_delay_jumps(-1),
2039 output_will_be_muted(false),
2040 key_pressed(false),
2041 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002042 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002043 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002044 echo_path_gain_change(false),
2045 prev_analog_mic_level(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002046
2047AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2048
2049AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2050
2051AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2052
niklase@google.com470e71d2011-07-07 08:21:25 +00002053} // namespace webrtc