blob: 9015319057c70c0c5300ce1603409b47cedfbf88 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/common.h"
26#include "modules/audio_processing/echo_cancellation_impl.h"
27#include "modules/audio_processing/echo_control_mobile_impl.h"
28#include "modules/audio_processing/gain_control_for_experimental_agc.h"
29#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010030#include "modules/audio_processing/gain_controller2.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020031#include "modules/audio_processing/level_estimator_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010032#include "modules/audio_processing/logging/apm_data_dumper.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020033#include "modules/audio_processing/low_cut_filter.h"
34#include "modules/audio_processing/noise_suppression_impl.h"
35#include "modules/audio_processing/residual_echo_detector.h"
36#include "modules/audio_processing/transient/transient_suppressor.h"
37#include "modules/audio_processing/voice_detection_impl.h"
38#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/checks.h"
40#include "rtc_base/logging.h"
41#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020042#include "rtc_base/refcountedobject.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020043#include "rtc_base/system/arch.h"
Minyue Li656d6092018-08-10 15:38:52 +020044#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/trace_event.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000047
Michael Graczyk86c6d332015-07-23 11:41:39 -070048#define RETURN_ON_ERR(expr) \
49 do { \
50 int err = (expr); \
51 if (err != kNoError) { \
52 return err; \
53 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000054 } while (0)
55
niklase@google.com470e71d2011-07-07 08:21:25 +000056namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070057
kwibergd59d3bb2016-09-13 07:49:33 -070058constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020059constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070060
Michael Graczyk86c6d332015-07-23 11:41:39 -070061namespace {
62
63static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
64 switch (layout) {
65 case AudioProcessing::kMono:
66 case AudioProcessing::kStereo:
67 return false;
68 case AudioProcessing::kMonoAndKeyboard:
69 case AudioProcessing::kStereoAndKeyboard:
70 return true;
71 }
72
kwiberg9e2be5f2016-09-14 05:23:22 -070073 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070074 return false;
75}
aluebsdf6416a2016-03-16 18:26:35 -070076
peah2ace3f92016-09-10 04:42:27 -070077bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070078 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
79 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
80}
81
peah2ace3f92016-09-10 04:42:27 -070082int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
83#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070084 constexpr int kMaxSplittingNativeProcessRate =
85 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070086#else
kwibergd59d3bb2016-09-13 07:49:33 -070087 constexpr int kMaxSplittingNativeProcessRate =
88 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070089#endif
kwibergd59d3bb2016-09-13 07:49:33 -070090 static_assert(
91 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
92 "");
peah2ace3f92016-09-10 04:42:27 -070093 const int uppermost_native_rate = band_splitting_required
94 ? kMaxSplittingNativeProcessRate
95 : AudioProcessing::kSampleRate48kHz;
96
97 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
98 if (rate >= uppermost_native_rate) {
99 return uppermost_native_rate;
100 }
101 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700102 return rate;
103 }
104 }
peah2ace3f92016-09-10 04:42:27 -0700105 RTC_NOTREACHED();
106 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700107}
108
peah9e6a2902017-05-15 07:19:21 -0700109// Maximum lengths that frame of samples being passed from the render side to
110// the capture side can have (does not apply to AEC3).
111static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
112static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
113
peah764e3642016-10-22 05:04:30 -0700114// Maximum number of frames to buffer in the render queue.
115// TODO(peah): Decrease this once we properly handle hugely unbalanced
116// reverse and forward call numbers.
117static const size_t kMaxNumFramesToBuffer = 100;
118
peah8271d042016-11-22 07:24:52 -0800119class HighPassFilterImpl : public HighPassFilter {
120 public:
121 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
122 ~HighPassFilterImpl() override = default;
123
124 // HighPassFilter implementation.
125 int Enable(bool enable) override {
126 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
127 config->high_pass_filter.enabled = enable;
128 });
129
130 return AudioProcessing::kNoError;
131 }
132
133 bool is_enabled() const override {
134 return apm_->GetConfig().high_pass_filter.enabled;
135 }
136
137 private:
138 AudioProcessingImpl* apm_;
139 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
140};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700141} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000142
143// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000144static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000145
Sam Zackrisson0beac582017-09-25 12:04:02 +0200146AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100147 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200148 bool render_pre_processor_enabled,
149 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100150 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200151 render_pre_processor_enabled_(render_pre_processor_enabled),
152 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700153
154bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200155 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700156 bool echo_canceller_enabled,
157 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700158 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700159 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700160 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700161 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200162 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200163 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700164 bool voice_activity_detector_enabled,
165 bool level_estimator_enabled,
166 bool transient_suppressor_enabled) {
167 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200168 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700169 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
170 changed |=
171 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700172 changed |=
173 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700174 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
175 changed |=
peah2ace3f92016-09-10 04:42:27 -0700176 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700177 changed |=
178 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200179 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200180 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700181 changed |= (level_estimator_enabled != level_estimator_enabled_);
182 changed |=
183 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
184 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
185 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200186 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700187 echo_canceller_enabled_ = echo_canceller_enabled;
188 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700189 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700190 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700191 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700192 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200193 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200194 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700195 level_estimator_enabled_ = level_estimator_enabled;
196 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
197 transient_suppressor_enabled_ = transient_suppressor_enabled;
198 }
199
200 changed |= first_update_;
201 first_update_ = false;
202 return changed;
203}
204
205bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
206 const {
peah52775842017-05-16 06:14:09 -0700207 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700208}
209
210bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
211 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200212 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700213 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200214 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700215}
216
peah23ac8b42017-05-23 05:33:56 -0700217bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
218 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200219 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
220 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700221}
222
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200223bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
224 return capture_analyzer_enabled_;
225}
226
peah2ace3f92016-09-10 04:42:27 -0700227bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
228 const {
229 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800230 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200231 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700232}
233
Alex Loiko5825aa62017-12-18 16:02:40 +0100234bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
235 const {
236 return render_pre_processor_enabled_;
237}
238
peah2ace3f92016-09-10 04:42:27 -0700239bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
240 const {
peah2ace3f92016-09-10 04:42:27 -0700241 return false;
peah2ace3f92016-09-10 04:42:27 -0700242}
243
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200244bool AudioProcessingImpl::ApmSubmoduleStates::LowCutFilteringRequired() const {
245 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
246 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
247}
248
solenberg5e465c32015-12-08 13:22:33 -0800249struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800250 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800251 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800252 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800253 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800254 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800255 std::unique_ptr<LevelEstimatorImpl> level_estimator;
256 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
257 std::unique_ptr<VoiceDetectionImpl> voice_detection;
258 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800259 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800260
261 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800262 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800263};
264
265struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200266 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100267 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200268 rtc::scoped_refptr<EchoDetector> echo_detector,
269 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200270 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100271 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200272 render_pre_processor(std::move(render_pre_processor)),
273 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800274 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800275 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700276 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800277 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200278 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200279 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100280 std::unique_ptr<CustomProcessing> capture_post_processor;
281 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200282 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200283 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
solenberg5e465c32015-12-08 13:22:33 -0800284};
285
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100286AudioProcessingBuilder::AudioProcessingBuilder() = default;
287AudioProcessingBuilder::~AudioProcessingBuilder() = default;
288
289AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
290 std::unique_ptr<CustomProcessing> capture_post_processing) {
291 capture_post_processing_ = std::move(capture_post_processing);
292 return *this;
293}
294
295AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
296 std::unique_ptr<CustomProcessing> render_pre_processing) {
297 render_pre_processing_ = std::move(render_pre_processing);
298 return *this;
299}
300
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200301AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
302 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
303 capture_analyzer_ = std::move(capture_analyzer);
304 return *this;
305}
306
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100307AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
308 std::unique_ptr<EchoControlFactory> echo_control_factory) {
309 echo_control_factory_ = std::move(echo_control_factory);
310 return *this;
311}
312
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100313AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200314 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100315 echo_detector_ = std::move(echo_detector);
316 return *this;
317}
318
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100319AudioProcessing* AudioProcessingBuilder::Create() {
320 webrtc::Config config;
321 return Create(config);
322}
323
324AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100325 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
326 config, std::move(capture_post_processing_),
327 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200328 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100329 if (apm->Initialize() != AudioProcessing::kNoError) {
330 delete apm;
331 apm = nullptr;
332 }
333 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100334}
335
peah88ac8532016-09-12 16:47:25 -0700336AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200337 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
338}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000339
Per Åhgren13735822018-02-12 21:42:56 +0100340int AudioProcessingImpl::instance_count_ = 0;
341
Sam Zackrisson0beac582017-09-25 12:04:02 +0200342AudioProcessingImpl::AudioProcessingImpl(
343 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100344 std::unique_ptr<CustomProcessing> capture_post_processor,
345 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200346 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200347 rtc::scoped_refptr<EchoDetector> echo_detector,
348 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100349 : data_dumper_(
350 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200351 capture_runtime_settings_(kRuntimeSettingQueueSize),
352 render_runtime_settings_(kRuntimeSettingQueueSize),
353 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
354 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100355 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200356 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200357 submodule_states_(!!capture_post_processor,
358 !!render_pre_processor,
359 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800360 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200361 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200362 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100363 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200364 std::move(echo_detector),
365 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800366 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800367 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000368#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200369 /* enabled= */ false,
370 /* enabled_agc2_level_estimator= */ false,
371 /* digital_adaptive_disabled= */ false,
372 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000373#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200374 config.Get<ExperimentalAgc>().enabled,
375 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200376 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
377 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000378#endif
andrew1c7075f2015-06-24 18:14:14 -0700379#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200380 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700381#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200382 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700383#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200384 capture_nonlocked_() {
peahdf3efa82015-11-28 12:35:15 -0800385 {
386 rtc::CritScope cs_render(&crit_render_);
387 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000388
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200389 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000390 capture_nonlocked_.echo_controller_enabled =
391 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200392
peahb624d8c2016-03-05 03:01:14 -0800393 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700394 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800395 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700396 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800397 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200398 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800399 public_submodules_->level_estimator.reset(
400 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800401 public_submodules_->noise_suppression.reset(
402 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800403 public_submodules_->voice_detection.reset(
404 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800405 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800406 new GainControlForExperimentalAgc(
407 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100408
409 // If no echo detector is injected, use the ResidualEchoDetector.
410 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200411 private_submodules_->echo_detector =
412 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100413 }
peahca4cac72016-06-29 15:26:12 -0700414
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200415 // TODO(alessiob): Move the injected gain controller once injection is
416 // implemented.
417 private_submodules_->gain_controller2.reset(new GainController2());
418
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200419 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
420 << !!private_submodules_->capture_analyzer
421 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100422 << !!private_submodules_->capture_post_processor
423 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100424 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800425 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000426
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000427 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000428}
429
430AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800431 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800432 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800433 private_submodules_->agc_manager.reset();
434 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800435 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000436}
437
niklase@google.com470e71d2011-07-07 08:21:25 +0000438int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800439 // Run in a single-threaded manner during initialization.
440 rtc::CritScope cs_render(&crit_render_);
441 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000442 return InitializeLocked();
443}
444
peahde65ddc2016-09-16 15:02:15 -0700445int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
446 int capture_output_sample_rate_hz,
447 int render_input_sample_rate_hz,
448 ChannelLayout capture_input_layout,
449 ChannelLayout capture_output_layout,
450 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700451 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700452 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
453 LayoutHasKeyboard(capture_input_layout)},
454 {capture_output_sample_rate_hz,
455 ChannelsFromLayout(capture_output_layout),
456 LayoutHasKeyboard(capture_output_layout)},
457 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
458 LayoutHasKeyboard(render_input_layout)},
459 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
460 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700461
462 return Initialize(processing_config);
463}
464
465int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800466 // Run in a single-threaded manner during initialization.
467 rtc::CritScope cs_render(&crit_render_);
468 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700469 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000470}
471
peahdf3efa82015-11-28 12:35:15 -0800472int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800473 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700474 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800475}
476
peahdf3efa82015-11-28 12:35:15 -0800477int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700478 const ProcessingConfig& processing_config,
479 bool force_initialization) {
480 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800481}
482
peah192164e2015-11-17 02:16:45 -0800483// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800484// their current values (needs to be called while holding the crit_render_lock).
485int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700486 const ProcessingConfig& processing_config,
487 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800488 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700489 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800490 return kNoError;
491 }
peahdf3efa82015-11-28 12:35:15 -0800492
493 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800494 return InitializeLocked(processing_config);
495}
496
niklase@google.com470e71d2011-07-07 08:21:25 +0000497int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200498 UpdateActiveSubmoduleStates();
499
peahde65ddc2016-09-16 15:02:15 -0700500 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800501 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700502 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800503 : formats_.api_format.reverse_output_stream().num_frames();
504 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
505 render_.render_audio.reset(new AudioBuffer(
506 formats_.api_format.reverse_input_stream().num_frames(),
507 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700508 formats_.render_processing_format.num_frames(),
509 formats_.render_processing_format.num_channels(),
510 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700511 if (formats_.api_format.reverse_input_stream() !=
512 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800513 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800514 formats_.api_format.reverse_input_stream().num_channels(),
515 formats_.api_format.reverse_input_stream().num_frames(),
516 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800517 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700518 } else {
peahdf3efa82015-11-28 12:35:15 -0800519 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700520 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700521 } else {
peahdf3efa82015-11-28 12:35:15 -0800522 render_.render_audio.reset(nullptr);
523 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700524 }
peahce4d9152017-05-19 01:28:05 -0700525
peahdf3efa82015-11-28 12:35:15 -0800526 capture_.capture_audio.reset(
527 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
528 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700529 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200530 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800531 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000532
peahde65ddc2016-09-16 15:02:15 -0700533 public_submodules_->echo_cancellation->Initialize(
534 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
535 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700536 AllocateRenderQueue();
537
ivoc3e9a5372016-10-28 07:55:33 -0700538 int success = public_submodules_->echo_cancellation->enable_metrics(true);
539 RTC_DCHECK_EQ(0, success);
540 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
541 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700542 public_submodules_->echo_control_mobile->Initialize(
543 proc_split_sample_rate_hz(), num_reverse_channels(),
544 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700545
546 public_submodules_->gain_control->Initialize(num_proc_channels(),
547 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700548 if (constants_.use_experimental_agc) {
549 if (!private_submodules_->agc_manager.get()) {
550 private_submodules_->agc_manager.reset(new AgcManagerDirect(
551 public_submodules_->gain_control.get(),
552 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200553 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
554 constants_.use_experimental_agc_agc2_level_estimation,
555 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700556 }
557 private_submodules_->agc_manager->Initialize();
558 private_submodules_->agc_manager->SetCaptureMuted(
559 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700560 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700561 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200562 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800563 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700564 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
565 proc_sample_rate_hz());
566 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
567 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700568 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200569 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700570 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200571 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200572 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100573 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800574
aleloi868f32f2017-05-23 07:20:05 -0700575 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200576 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700577 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000578 return kNoError;
579}
580
Michael Graczyk86c6d332015-07-23 11:41:39 -0700581int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200582 UpdateActiveSubmoduleStates();
583
Michael Graczyk86c6d332015-07-23 11:41:39 -0700584 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700585 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
586 return kBadSampleRateError;
587 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000588 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700589
Peter Kasting69558702016-01-12 16:26:35 -0800590 const size_t num_in_channels = config.input_stream().num_channels();
591 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700592
593 // Need at least one input channel.
594 // Need either one output channel or as many outputs as there are inputs.
595 if (num_in_channels == 0 ||
596 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700597 return kBadNumberChannelsError;
598 }
599
peahdf3efa82015-11-28 12:35:15 -0800600 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000601
peahde65ddc2016-09-16 15:02:15 -0700602 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700603 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700604 formats_.api_format.output_stream().sample_rate_hz()),
605 submodule_states_.CaptureMultiBandSubModulesActive() ||
606 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000607
peahde65ddc2016-09-16 15:02:15 -0700608 capture_nonlocked_.capture_processing_format =
609 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700610
peah2ce640f2017-04-07 03:57:48 -0700611 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200612 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700613 render_processing_rate = FindNativeProcessRateToUse(
614 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
615 formats_.api_format.reverse_output_stream().sample_rate_hz()),
616 submodule_states_.CaptureMultiBandSubModulesActive() ||
617 submodule_states_.RenderMultiBandSubModulesActive());
618 } else {
619 render_processing_rate = capture_processing_rate;
620 }
621
aluebseb3603b2016-04-20 15:27:58 -0700622 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
623 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700624 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200625 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700626 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
627 ? kSampleRate32kHz
628 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700629 }
peah2ce640f2017-04-07 03:57:48 -0700630
peahde65ddc2016-09-16 15:02:15 -0700631 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700632 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700633 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
634 kSampleRate8kHz) {
635 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000636 } else {
peahde65ddc2016-09-16 15:02:15 -0700637 render_processing_rate =
638 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000639 }
640
peahde65ddc2016-09-16 15:02:15 -0700641 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000642 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700643 if (submodule_states_.RenderMultiBandSubModulesActive()) {
644 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
645 } else {
646 formats_.render_processing_format = StreamConfig(
647 formats_.api_format.reverse_input_stream().sample_rate_hz(),
648 formats_.api_format.reverse_input_stream().num_channels());
649 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000650
peahde65ddc2016-09-16 15:02:15 -0700651 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
652 kSampleRate32kHz ||
653 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
654 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800655 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000656 } else {
peahdf3efa82015-11-28 12:35:15 -0800657 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700658 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000659 }
660
661 return InitializeLocked();
662}
663
peah88ac8532016-09-12 16:47:25 -0700664void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700665 // Run in a single-threaded manner when applying the settings.
666 rtc::CritScope cs_render(&crit_render_);
667 rtc::CritScope cs_capture(&crit_capture_);
668
Yves Gerey499bc6c2018-10-10 18:29:07 +0200669 config_ = config;
670
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200671 public_submodules_->echo_cancellation->Enable(
672 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200673 public_submodules_->echo_control_mobile->Enable(
674 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200675
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200676 public_submodules_->echo_cancellation->set_suppression_level(
677 config.echo_canceller.legacy_moderate_suppression_level
sazabe490b22018-10-03 17:03:13 +0200678 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
679 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200680
peah8271d042016-11-22 07:24:52 -0800681 InitializeLowCutFilter();
682
Mirko Bonadei675513b2017-11-09 11:09:25 +0100683 RTC_LOG(LS_INFO) << "Highpass filter activated: "
684 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800685
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100686 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700687 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100688 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
689 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100690 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100691 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700692 config_.gain_controller2 = AudioProcessing::Config::GainController2();
693 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200694 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200695 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200696 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100697 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
698 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200699 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
700 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700701}
702
703void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800704 // Run in a single-threaded manner when setting the extra options.
705 rtc::CritScope cs_render(&crit_render_);
706 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000707
peahb624d8c2016-03-05 03:01:14 -0800708 public_submodules_->echo_cancellation->SetExtraOptions(config);
709
peahdf3efa82015-11-28 12:35:15 -0800710 if (capture_.transient_suppressor_enabled !=
711 config.Get<ExperimentalNs>().enabled) {
712 capture_.transient_suppressor_enabled =
713 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000714 InitializeTransient();
715 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000716}
717
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000718int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800719 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700720 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000721}
722
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000723int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800724 // Used as callback from submodules, hence locking is not allowed.
725 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000726}
727
Peter Kasting69558702016-01-12 16:26:35 -0800728size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800729 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700730 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000731}
732
Peter Kasting69558702016-01-12 16:26:35 -0800733size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800734 // Used as callback from submodules, hence locking is not allowed.
735 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000736}
737
Peter Kasting69558702016-01-12 16:26:35 -0800738size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800739 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200740 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800741}
742
Peter Kasting69558702016-01-12 16:26:35 -0800743size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800744 // Used as callback from submodules, hence locking is not allowed.
745 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000746}
747
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000748void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800749 rtc::CritScope cs(&crit_capture_);
750 capture_.output_will_be_muted = muted;
751 if (private_submodules_->agc_manager.get()) {
752 private_submodules_->agc_manager->SetCaptureMuted(
753 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000754 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000755}
756
Alessio Bazzicac054e782018-04-16 12:10:09 +0200757void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200758 switch (setting.type()) {
759 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
760 render_runtime_settings_enqueuer_.Enqueue(setting);
761 return;
762 case RuntimeSetting::Type::kNotSpecified:
763 RTC_NOTREACHED();
764 return;
765 case RuntimeSetting::Type::kCapturePreGain:
766 capture_runtime_settings_enqueuer_.Enqueue(setting);
767 return;
768 }
769 // The language allows the enum to have a non-enumerator
770 // value. Check that this doesn't happen.
771 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200772}
773
774AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
775 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200776 : runtime_settings_(*runtime_settings) {
777 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200778}
779
780AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
781 default;
782
783void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
784 RuntimeSetting setting) {
785 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200786 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200787 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200788 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200789 RTC_LOG(LS_ERROR)
790 << "The runtime settings queue is full. Oldest setting discarded.";
791 }
792 if (remaining_attempts == 0)
793 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
794}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000795
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000796int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700797 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000798 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000799 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000800 int output_sample_rate_hz,
801 ChannelLayout output_layout,
802 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800803 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800804 StreamConfig input_stream;
805 StreamConfig output_stream;
806 {
807 // Access the formats_.api_format.input_stream beneath the capture lock.
808 // The lock must be released as it is later required in the call
809 // to ProcessStream(,,,);
810 rtc::CritScope cs(&crit_capture_);
811 input_stream = formats_.api_format.input_stream();
812 output_stream = formats_.api_format.output_stream();
813 }
814
Michael Graczyk86c6d332015-07-23 11:41:39 -0700815 input_stream.set_sample_rate_hz(input_sample_rate_hz);
816 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
817 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700818 output_stream.set_sample_rate_hz(output_sample_rate_hz);
819 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
820 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
821
822 if (samples_per_channel != input_stream.num_frames()) {
823 return kBadDataLengthError;
824 }
825 return ProcessStream(src, input_stream, output_stream, dest);
826}
827
828int AudioProcessingImpl::ProcessStream(const float* const* src,
829 const StreamConfig& input_config,
830 const StreamConfig& output_config,
831 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800832 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800833 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700834 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800835 {
836 // Acquire the capture lock in order to safely call the function
837 // that retrieves the render side data. This function accesses apm
838 // getters that need the capture lock held when being called.
839 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700840 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800841
842 if (!src || !dest) {
843 return kNullPointerError;
844 }
845
846 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700847 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000848 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000849
Michael Graczyk86c6d332015-07-23 11:41:39 -0700850 processing_config.input_stream() = input_config;
851 processing_config.output_stream() = output_config;
852
peahdf3efa82015-11-28 12:35:15 -0800853 {
854 // Do conditional reinitialization.
855 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700856 RETURN_ON_ERR(
857 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800858 }
859 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700860 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
861 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000862
aleloi868f32f2017-05-23 07:20:05 -0700863 if (aec_dump_) {
864 RecordUnprocessedCaptureStream(src);
865 }
866
peahdf3efa82015-11-28 12:35:15 -0800867 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700868 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800869 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000870
aleloi868f32f2017-05-23 07:20:05 -0700871 if (aec_dump_) {
872 RecordProcessedCaptureStream(dest);
873 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000874 return kNoError;
875}
876
Alex Loiko73ec0192018-05-15 10:52:28 +0200877void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200878 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200879 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200880 if (aec_dump_) {
881 aec_dump_->WriteRuntimeSetting(setting);
882 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200883 switch (setting.type()) {
884 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200885 if (config_.pre_amplifier.enabled) {
886 float value;
887 setting.GetFloat(&value);
888 private_submodules_->pre_amplifier->SetGainFactor(value);
889 }
890 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200891 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200892 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
893 RTC_NOTREACHED();
894 break;
895 case RuntimeSetting::Type::kNotSpecified:
896 RTC_NOTREACHED();
897 break;
898 }
899 }
900}
901
902void AudioProcessingImpl::HandleRenderRuntimeSettings() {
903 RuntimeSetting setting;
904 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200905 if (aec_dump_) {
906 aec_dump_->WriteRuntimeSetting(setting);
907 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200908 switch (setting.type()) {
909 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
910 if (private_submodules_->render_pre_processor) {
911 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
912 }
913 break;
914 case RuntimeSetting::Type::kCapturePreGain:
915 RTC_NOTREACHED();
916 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200917 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200918 RTC_NOTREACHED();
919 break;
920 }
921 }
922}
923
peah9e6a2902017-05-15 07:19:21 -0700924void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700925 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
926 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700927 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700928
kwibergaf476c72016-11-28 15:21:39 -0800929 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700930
931 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700932 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700933 // The data queue is full and needs to be emptied.
934 EmptyQueuedRenderAudio();
935
936 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700937 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700938 RTC_DCHECK(result);
939 }
940
941 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
942 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700943 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700944
945 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700946 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700947 // The data queue is full and needs to be emptied.
948 EmptyQueuedRenderAudio();
949
950 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700951 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700952 RTC_DCHECK(result);
953 }
peah701d6282016-10-25 05:42:20 -0700954
955 if (!constants_.use_experimental_agc) {
956 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
957 // Insert the samples into the queue.
958 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
959 // The data queue is full and needs to be emptied.
960 EmptyQueuedRenderAudio();
961
962 // Retry the insert (should always work).
963 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
964 RTC_DCHECK(result);
965 }
966 }
peah9e6a2902017-05-15 07:19:21 -0700967}
ivoc9f4a4a02016-10-28 05:39:16 -0700968
peah9e6a2902017-05-15 07:19:21 -0700969void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700970 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
971
972 // Insert the samples into the queue.
973 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
974 // The data queue is full and needs to be emptied.
975 EmptyQueuedRenderAudio();
976
977 // Retry the insert (should always work).
978 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
979 RTC_DCHECK(result);
980 }
peah764e3642016-10-22 05:04:30 -0700981}
982
983void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700984 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700985 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700986 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700987 EchoCancellationImpl::NumCancellersRequired(
988 num_output_channels(), num_reverse_channels()));
989
peah701d6282016-10-25 05:42:20 -0700990 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700991 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700992 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700993 EchoControlMobileImpl::NumCancellersRequired(
994 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700995
peah701d6282016-10-25 05:42:20 -0700996 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700997 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700998
ivoc9f4a4a02016-10-28 05:39:16 -0700999 const size_t new_red_render_queue_element_max_size =
1000 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1001
peaha0624602016-10-25 04:45:24 -07001002 // Reallocate the queues if the queue item sizes are too small to fit the
1003 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001004 if (aec_render_queue_element_max_size_ <
1005 new_aec_render_queue_element_max_size) {
1006 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001007
peaha0624602016-10-25 04:45:24 -07001008 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001009 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001010
peah701d6282016-10-25 05:42:20 -07001011 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001012 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1013 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001014 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001015 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001016
peah701d6282016-10-25 05:42:20 -07001017 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1018 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001019 } else {
peah701d6282016-10-25 05:42:20 -07001020 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001021 }
1022
peah701d6282016-10-25 05:42:20 -07001023 if (aecm_render_queue_element_max_size_ <
1024 new_aecm_render_queue_element_max_size) {
1025 aecm_render_queue_element_max_size_ =
1026 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001027
1028 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001029 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001030
peah701d6282016-10-25 05:42:20 -07001031 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001032 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1033 kMaxNumFramesToBuffer, template_queue_element,
1034 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001035 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001036
peah701d6282016-10-25 05:42:20 -07001037 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1038 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001039 } else {
peah701d6282016-10-25 05:42:20 -07001040 aecm_render_signal_queue_->Clear();
1041 }
1042
1043 if (agc_render_queue_element_max_size_ <
1044 new_agc_render_queue_element_max_size) {
1045 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1046
1047 std::vector<int16_t> template_queue_element(
1048 agc_render_queue_element_max_size_);
1049
1050 agc_render_signal_queue_.reset(
1051 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1052 kMaxNumFramesToBuffer, template_queue_element,
1053 RenderQueueItemVerifier<int16_t>(
1054 agc_render_queue_element_max_size_)));
1055
1056 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1057 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1058 } else {
1059 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001060 }
ivoc9f4a4a02016-10-28 05:39:16 -07001061
1062 if (red_render_queue_element_max_size_ <
1063 new_red_render_queue_element_max_size) {
1064 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1065
1066 std::vector<float> template_queue_element(
1067 red_render_queue_element_max_size_);
1068
1069 red_render_signal_queue_.reset(
1070 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1071 kMaxNumFramesToBuffer, template_queue_element,
1072 RenderQueueItemVerifier<float>(
1073 red_render_queue_element_max_size_)));
1074
1075 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1076 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1077 } else {
1078 red_render_signal_queue_->Clear();
1079 }
peah764e3642016-10-22 05:04:30 -07001080}
1081
1082void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1083 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001084 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001085 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001086 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001087 }
1088
peah701d6282016-10-25 05:42:20 -07001089 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001090 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001091 aecm_capture_queue_buffer_);
1092 }
1093
1094 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1095 public_submodules_->gain_control->ProcessRenderAudio(
1096 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001097 }
ivoc9f4a4a02016-10-28 05:39:16 -07001098
1099 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001100 RTC_DCHECK(private_submodules_->echo_detector);
1101 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001102 red_capture_queue_buffer_);
1103 }
peah764e3642016-10-22 05:04:30 -07001104}
1105
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001106int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001107 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001108 {
1109 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001110 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001111 // getters that need the capture lock held when being called.
1112 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001113 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001114 // as well.
1115 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001116 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001117 }
peahfa6228e2015-11-16 16:27:42 -08001118
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001119 if (!frame) {
1120 return kNullPointerError;
1121 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001122 // Must be a native rate.
1123 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1124 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001125 frame->sample_rate_hz_ != kSampleRate32kHz &&
1126 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001127 return kBadSampleRateError;
1128 }
peah192164e2015-11-17 02:16:45 -08001129
peahdf3efa82015-11-28 12:35:15 -08001130 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001131 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001132 {
1133 // Aquire lock for the access of api_format.
1134 // The lock is released immediately due to the conditional
1135 // reinitialization.
1136 rtc::CritScope cs_capture(&crit_capture_);
1137 // TODO(ajm): The input and output rates and channels are currently
1138 // constrained to be identical in the int16 interface.
1139 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001140
1141 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001142 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001143 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1144 processing_config.input_stream().set_num_channels(frame->num_channels_);
1145 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1146 processing_config.output_stream().set_num_channels(frame->num_channels_);
1147
peahdf3efa82015-11-28 12:35:15 -08001148 {
1149 // Do conditional reinitialization.
1150 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001151 RETURN_ON_ERR(
1152 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001153 }
1154 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001155 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001156 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001157 return kBadDataLengthError;
1158 }
1159
aleloi868f32f2017-05-23 07:20:05 -07001160 if (aec_dump_) {
1161 RecordUnprocessedCaptureStream(*frame);
1162 }
1163
peahdf3efa82015-11-28 12:35:15 -08001164 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001165 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001166 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001167 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1168 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001169
aleloi868f32f2017-05-23 07:20:05 -07001170 if (aec_dump_) {
1171 RecordProcessedCaptureStream(*frame);
1172 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001173
1174 return kNoError;
1175}
1176
peahde65ddc2016-09-16 15:02:15 -07001177int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001178 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001179
peahb58a1582016-03-15 09:34:24 -07001180 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001181 // TODO(peah): Simplify once the public API Enable functions for these
1182 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001183 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1184 public_submodules_->echo_control_mobile->is_enabled()));
1185
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001186 MaybeUpdateHistograms();
1187
peahde65ddc2016-09-16 15:02:15 -07001188 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001189
Alex Loikob5c9a792018-04-16 16:31:22 +02001190 if (private_submodules_->pre_amplifier) {
1191 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1192 capture_buffer->channels_f(), capture_buffer->num_channels(),
1193 capture_buffer->num_frames()));
1194 }
1195
peah1b08dc32016-12-20 13:45:58 -08001196 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001197 capture_buffer->channels_const()[0],
1198 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001199 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1200 if (log_rms) {
1201 capture_rms_interval_counter_ = 0;
1202 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001203 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1204 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1205 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1206 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001207 }
1208
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001209 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001210 // Detect and flag any change in the analog gain.
1211 int analog_mic_level = gain_control()->stream_analog_level();
1212 capture_.echo_path_gain_change =
1213 capture_.prev_analog_mic_level != analog_mic_level &&
1214 capture_.prev_analog_mic_level != -1;
1215 capture_.prev_analog_mic_level = analog_mic_level;
1216
Per Åhgrend2650d12018-10-02 17:00:59 +02001217 // Detect and flag any change in the pre-amplifier gain.
1218 if (private_submodules_->pre_amplifier) {
1219 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1220 capture_.echo_path_gain_change =
1221 capture_.echo_path_gain_change ||
1222 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001223 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001224 capture_.prev_pre_amp_gain = pre_amp_gain;
1225 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001226 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001227 }
1228
peahbe615622016-02-13 16:40:47 -08001229 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001230 public_submodules_->gain_control->is_enabled()) {
1231 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001232 capture_buffer->channels()[0], capture_buffer->num_channels(),
1233 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001234
1235 if (constants_.use_experimental_agc_process_before_aec) {
1236 private_submodules_->agc_manager->Process(
1237 capture_buffer->channels()[0],
1238 capture_nonlocked_.capture_processing_format.num_frames(),
1239 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1240 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001241 }
1242
peah2ace3f92016-09-10 04:42:27 -07001243 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1244 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001245 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1246 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001247 }
1248
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001249 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001250 // Force down-mixing of the number of channels after the detection of
1251 // capture signal saturation.
1252 // TODO(peah): Look into ensuring that this kind of tampering with the
1253 // AudioBuffer functionality should not be needed.
1254 capture_buffer->set_num_channels(1);
1255 }
1256
peahe0eae3c2016-12-14 01:16:23 -08001257 // TODO(peah): Move the AEC3 low-cut filter to this place.
1258 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001259 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001260 private_submodules_->low_cut_filter->Process(capture_buffer);
1261 }
peahde65ddc2016-09-16 15:02:15 -07001262 RETURN_ON_ERR(
1263 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1264 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001265
1266 // Ensure that the stream delay was set before the call to the
1267 // AEC ProcessCaptureAudio function.
1268 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001269 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001270 return AudioProcessing::kStreamParameterNotSetError;
1271 }
1272
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001273 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001274 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1275
Per Åhgrend0fa8202018-04-18 09:35:13 +02001276 if (was_stream_delay_set()) {
1277 private_submodules_->echo_controller->SetAudioBufferDelay(
1278 stream_delay_ms());
1279 }
1280
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001281 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001282 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001283 } else {
1284 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1285 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001286 }
1287
peahdf3efa82015-11-28 12:35:15 -08001288 if (public_submodules_->echo_control_mobile->is_enabled() &&
1289 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001290 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001291 }
peahde65ddc2016-09-16 15:02:15 -07001292 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001293
1294 // Ensure that the stream delay was set before the call to the
1295 // AECM ProcessCaptureAudio function.
1296 if (public_submodules_->echo_control_mobile->is_enabled() &&
1297 !was_stream_delay_set()) {
1298 return AudioProcessing::kStreamParameterNotSetError;
1299 }
1300
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001301 if (!(private_submodules_->echo_controller ||
1302 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001303 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1304 capture_buffer, stream_delay_ms()));
1305 }
ivoc9f4a4a02016-10-28 05:39:16 -07001306
peahde65ddc2016-09-16 15:02:15 -07001307 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001308
peahbe615622016-02-13 16:40:47 -08001309 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001310 public_submodules_->gain_control->is_enabled() &&
1311 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001312 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001313 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1314 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001315 }
peahb8fbb542016-03-15 02:28:08 -07001316 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001317 capture_buffer,
1318 public_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001319
peah2ace3f92016-09-10 04:42:27 -07001320 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1321 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001322 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1323 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001324 }
1325
peah9e6a2902017-05-15 07:19:21 -07001326 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001327 RTC_DCHECK(private_submodules_->echo_detector);
1328 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001329 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1330 capture_buffer->num_frames()));
1331 }
1332
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001333 // TODO(aluebs): Investigate if the transient suppression placement should be
1334 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001335 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001336 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001337 private_submodules_->agc_manager.get()
1338 ? private_submodules_->agc_manager->voice_probability()
1339 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001340
peahdf3efa82015-11-28 12:35:15 -08001341 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001342 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1343 capture_buffer->num_channels(),
1344 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1345 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1346 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001347 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001348 }
1349
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001350 // Experimental APM sub-module that analyzes |capture_buffer|.
1351 if (private_submodules_->capture_analyzer) {
1352 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1353 }
1354
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001355 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001356 private_submodules_->gain_controller2->NotifyAnalogLevel(
1357 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001358 private_submodules_->gain_controller2->Process(capture_buffer);
1359 }
1360
Sam Zackrisson0beac582017-09-25 12:04:02 +02001361 if (private_submodules_->capture_post_processor) {
1362 private_submodules_->capture_post_processor->Process(capture_buffer);
1363 }
1364
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001365 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001366 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001367
peah1b08dc32016-12-20 13:45:58 -08001368 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1369 capture_buffer->channels_const()[0],
1370 capture_nonlocked_.capture_processing_format.num_frames()));
1371 if (log_rms) {
1372 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1373 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1374 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1375 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1376 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1377 }
1378
peahdf3efa82015-11-28 12:35:15 -08001379 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001380 return kNoError;
1381}
1382
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001383int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001384 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001385 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001386 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001387 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001388 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001389 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001390 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001391 };
1392 if (samples_per_channel != reverse_config.num_frames()) {
1393 return kBadDataLengthError;
1394 }
peahdf3efa82015-11-28 12:35:15 -08001395 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001396}
1397
peahde65ddc2016-09-16 15:02:15 -07001398int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1399 const StreamConfig& input_config,
1400 const StreamConfig& output_config,
1401 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001402 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001403 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001404 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001405 if (submodule_states_.RenderMultiBandProcessingActive() ||
1406 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001407 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1408 dest);
peah2ace3f92016-09-10 04:42:27 -07001409 } else if (formats_.api_format.reverse_input_stream() !=
1410 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001411 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1412 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001413 } else {
peahde65ddc2016-09-16 15:02:15 -07001414 CopyAudioIfNeeded(src, input_config.num_frames(),
1415 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001416 }
1417
1418 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001419}
1420
peahdf3efa82015-11-28 12:35:15 -08001421int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001422 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001423 const StreamConfig& input_config,
1424 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001425 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001426 return kNullPointerError;
1427 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001428
peahde65ddc2016-09-16 15:02:15 -07001429 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001430 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001431 }
1432
peahdf3efa82015-11-28 12:35:15 -08001433 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001434 processing_config.reverse_input_stream() = input_config;
1435 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001436
peahdf3efa82015-11-28 12:35:15 -08001437 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001438 RTC_DCHECK_EQ(input_config.num_frames(),
1439 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001440
aleloi868f32f2017-05-23 07:20:05 -07001441 if (aec_dump_) {
1442 const size_t channel_size =
1443 formats_.api_format.reverse_input_stream().num_frames();
1444 const size_t num_channels =
1445 formats_.api_format.reverse_input_stream().num_channels();
1446 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001447 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001448 }
peahdf3efa82015-11-28 12:35:15 -08001449 render_.render_audio->CopyFrom(src,
1450 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001451 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001452}
1453
1454int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001455 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001456 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001457 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001458 return kNullPointerError;
1459 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001460 // Must be a native rate.
1461 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1462 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001463 frame->sample_rate_hz_ != kSampleRate32kHz &&
1464 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001465 return kBadSampleRateError;
1466 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001467
Michael Graczyk86c6d332015-07-23 11:41:39 -07001468 if (frame->num_channels_ <= 0) {
1469 return kBadNumberChannelsError;
1470 }
1471
peahdf3efa82015-11-28 12:35:15 -08001472 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001473 processing_config.reverse_input_stream().set_sample_rate_hz(
1474 frame->sample_rate_hz_);
1475 processing_config.reverse_input_stream().set_num_channels(
1476 frame->num_channels_);
1477 processing_config.reverse_output_stream().set_sample_rate_hz(
1478 frame->sample_rate_hz_);
1479 processing_config.reverse_output_stream().set_num_channels(
1480 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001481
peahdf3efa82015-11-28 12:35:15 -08001482 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001483 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001484 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001485 return kBadDataLengthError;
1486 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001487
aleloi868f32f2017-05-23 07:20:05 -07001488 if (aec_dump_) {
1489 aec_dump_->WriteRenderStreamMessage(*frame);
1490 }
1491
peahdf3efa82015-11-28 12:35:15 -08001492 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001493 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001494 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001495 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1496 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001497 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001498}
niklase@google.com470e71d2011-07-07 08:21:25 +00001499
peahde65ddc2016-09-16 15:02:15 -07001500int AudioProcessingImpl::ProcessRenderStreamLocked() {
1501 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001502
Alex Loiko73ec0192018-05-15 10:52:28 +02001503 HandleRenderRuntimeSettings();
1504
Alex Loiko5825aa62017-12-18 16:02:40 +01001505 if (private_submodules_->render_pre_processor) {
1506 private_submodules_->render_pre_processor->Process(render_buffer);
1507 }
1508
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001509 QueueNonbandedRenderAudio(render_buffer);
1510
peah2ace3f92016-09-10 04:42:27 -07001511 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001512 SampleRateSupportsMultiBand(
1513 formats_.render_processing_format.sample_rate_hz())) {
1514 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001515 }
1516
peahce4d9152017-05-19 01:28:05 -07001517 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1518 QueueBandedRenderAudio(render_buffer);
1519 }
1520
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001521 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001522 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001523 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001524 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001525
peah2ace3f92016-09-10 04:42:27 -07001526 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001527 SampleRateSupportsMultiBand(
1528 formats_.render_processing_format.sample_rate_hz())) {
1529 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001530 }
1531
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001532 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001533}
1534
1535int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001536 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001537 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001538 capture_.was_stream_delay_set = true;
1539 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001540
niklase@google.com470e71d2011-07-07 08:21:25 +00001541 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001542 delay = 0;
1543 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001544 }
1545
1546 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1547 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001548 delay = 500;
1549 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001550 }
1551
peahdf3efa82015-11-28 12:35:15 -08001552 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001553 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001554}
1555
1556int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001557 // Used as callback from submodules, hence locking is not allowed.
1558 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001559}
1560
1561bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001562 // Used as callback from submodules, hence locking is not allowed.
1563 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001564}
1565
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001566void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001567 rtc::CritScope cs(&crit_capture_);
1568 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001569}
1570
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001571void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001572 rtc::CritScope cs(&crit_capture_);
1573 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001574}
1575
1576int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001577 rtc::CritScope cs(&crit_capture_);
1578 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001579}
1580
aleloi868f32f2017-05-23 07:20:05 -07001581void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1582 RTC_DCHECK(aec_dump);
1583 rtc::CritScope cs_render(&crit_render_);
1584 rtc::CritScope cs_capture(&crit_capture_);
1585
1586 // The previously attached AecDump will be destroyed with the
1587 // 'aec_dump' parameter, which is after locks are released.
1588 aec_dump_.swap(aec_dump);
1589 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001590 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001591}
1592
1593void AudioProcessingImpl::DetachAecDump() {
1594 // The d-tor of a task-queue based AecDump blocks until all pending
1595 // tasks are done. This construction avoids blocking while holding
1596 // the render and capture locks.
1597 std::unique_ptr<AecDump> aec_dump = nullptr;
1598 {
1599 rtc::CritScope cs_render(&crit_render_);
1600 rtc::CritScope cs_capture(&crit_capture_);
1601 aec_dump = std::move(aec_dump_);
1602 }
1603}
1604
Sam Zackrisson4d364492018-03-02 16:03:21 +01001605void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1606 std::unique_ptr<AudioGenerator> audio_generator) {
1607 // TODO(bugs.webrtc.org/8882) Stub.
1608 // Reset internal audio generator with audio_generator.
1609}
1610
1611void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1612 // TODO(bugs.webrtc.org/8882) Stub.
1613 // Delete audio generator, if one is attached.
1614}
1615
ivoc4e477a12017-01-15 08:29:46 -08001616AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1617 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1618 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1619 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1620 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1621}
1622
1623AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1624 const AudioProcessingStatistics& other) = default;
1625
1626AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1627 default;
1628
ivoc3e9a5372016-10-28 07:55:33 -07001629// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1630AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1631 const {
1632 return AudioProcessingStatistics();
1633}
1634
Ivo Creusenae026092017-11-20 13:07:16 +01001635// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001636AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001637 bool has_remote_tracks) const {
1638 return AudioProcessingStats();
1639}
1640
ivoc3e9a5372016-10-28 07:55:33 -07001641AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1642 const {
1643 AudioProcessingStatistics stats;
sazabe490b22018-10-03 17:03:13 +02001644 EchoCancellationImpl::Metrics metrics;
Yves Gerey499bc6c2018-10-10 18:29:07 +02001645 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001646 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001647 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1648 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1649 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1650 // Instant value will also be used for min, max and average.
1651 stats.echo_return_loss.Set(erl, erl, erl, erl);
1652 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1653 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1654 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001655 stats.a_nlp.Set(metrics.a_nlp);
1656 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1657 stats.echo_return_loss.Set(metrics.echo_return_loss);
1658 stats.echo_return_loss_enhancement.Set(
1659 metrics.echo_return_loss_enhancement);
1660 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1661 }
Yves Gerey499bc6c2018-10-10 18:29:07 +02001662 RTC_DCHECK(private_submodules_->echo_detector);
1663 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1664 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1665 stats.residual_echo_likelihood_recent_max =
1666 ed_metrics.echo_likelihood_recent_max;
ivoc3e9a5372016-10-28 07:55:33 -07001667 public_submodules_->echo_cancellation->GetDelayMetrics(
1668 &stats.delay_median, &stats.delay_standard_deviation,
1669 &stats.fraction_poor_delays);
1670 return stats;
1671}
1672
Ivo Creusen56d46092017-11-24 17:29:59 +01001673AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001674 bool has_remote_tracks) const {
1675 AudioProcessingStats stats;
1676 if (has_remote_tracks) {
sazabe490b22018-10-03 17:03:13 +02001677 EchoCancellationImpl::Metrics metrics;
Yves Gerey499bc6c2018-10-10 18:29:07 +02001678 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001679 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001680 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1681 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001682 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001683 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001684 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001685 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1686 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001687 if (metrics.divergent_filter_fraction != -1.0f) {
1688 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001689 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001690 }
1691 if (metrics.echo_return_loss.instant != -100) {
1692 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001693 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001694 }
1695 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001696 stats.echo_return_loss_enhancement = absl::optional<double>(
1697 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001698 }
1699 }
1700 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001701 RTC_DCHECK(private_submodules_->echo_detector);
1702 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1703 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001704 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001705 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001706 }
1707 int delay_median, delay_std;
1708 float fraction_poor_delays;
1709 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1710 &delay_median, &delay_std, &fraction_poor_delays) ==
1711 Error::kNoError) {
1712 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001713 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001714 }
1715 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001716 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001717 }
1718 }
1719 }
1720 return stats;
1721}
1722
niklase@google.com470e71d2011-07-07 08:21:25 +00001723GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001724 if (constants_.use_experimental_agc) {
1725 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001726 }
peahbfa97112016-03-10 21:09:04 -08001727 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001728}
1729
1730HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001731 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001732}
1733
1734LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001735 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001736}
1737
1738NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001739 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001740}
1741
1742VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001743 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001744}
1745
peah8271d042016-11-22 07:24:52 -08001746void AudioProcessingImpl::MutateConfig(
1747 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1748 rtc::CritScope cs_render(&crit_render_);
1749 rtc::CritScope cs_capture(&crit_capture_);
1750 mutator(&config_);
1751 ApplyConfig(config_);
1752}
1753
1754AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1755 rtc::CritScope cs_render(&crit_render_);
1756 rtc::CritScope cs_capture(&crit_capture_);
1757 return config_;
1758}
1759
peah2ace3f92016-09-10 04:42:27 -07001760bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1761 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001762 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001763 public_submodules_->echo_cancellation->is_enabled(),
1764 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001765 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001766 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001767 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001768 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001769 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001770 public_submodules_->voice_detection->is_enabled(),
1771 public_submodules_->level_estimator->is_enabled(),
1772 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001773}
1774
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001775void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001776 if (capture_.transient_suppressor_enabled) {
1777 if (!public_submodules_->transient_suppressor.get()) {
1778 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001779 }
peahdf3efa82015-11-28 12:35:15 -08001780 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001781 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1782 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001783 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001784}
1785
peah8271d042016-11-22 07:24:52 -08001786void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001787 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001788 private_submodules_->low_cut_filter.reset(
1789 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1790 } else {
1791 private_submodules_->low_cut_filter.reset();
1792 }
1793}
alessiob3ec96df2017-05-22 06:57:06 -07001794
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001795void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001796 if (echo_control_factory_) {
1797 private_submodules_->echo_controller =
1798 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001799 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001800 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001801 }
1802}
peah8271d042016-11-22 07:24:52 -08001803
alessiob3ec96df2017-05-22 06:57:06 -07001804void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001805 if (config_.gain_controller2.enabled) {
1806 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001807 }
1808}
1809
Alex Loikob5c9a792018-04-16 16:31:22 +02001810void AudioProcessingImpl::InitializePreAmplifier() {
1811 if (config_.pre_amplifier.enabled) {
1812 private_submodules_->pre_amplifier.reset(
1813 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1814 } else {
1815 private_submodules_->pre_amplifier.reset();
1816 }
1817}
1818
ivoc9f4a4a02016-10-28 05:39:16 -07001819void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001820 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001821 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001822 proc_sample_rate_hz(), 1,
1823 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001824}
1825
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001826void AudioProcessingImpl::InitializeAnalyzer() {
1827 if (private_submodules_->capture_analyzer) {
1828 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1829 num_proc_channels());
1830 }
1831}
1832
Sam Zackrisson0beac582017-09-25 12:04:02 +02001833void AudioProcessingImpl::InitializePostProcessor() {
1834 if (private_submodules_->capture_post_processor) {
1835 private_submodules_->capture_post_processor->Initialize(
1836 proc_sample_rate_hz(), num_proc_channels());
1837 }
1838}
1839
Alex Loiko5825aa62017-12-18 16:02:40 +01001840void AudioProcessingImpl::InitializePreProcessor() {
1841 if (private_submodules_->render_pre_processor) {
1842 private_submodules_->render_pre_processor->Initialize(
1843 formats_.render_processing_format.sample_rate_hz(),
1844 formats_.render_processing_format.num_channels());
1845 }
1846}
1847
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001848void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001849 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001850
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001851 if (public_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001852 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1853 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001854 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001855 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001856 capture_.stream_delay_jumps = 0;
1857 }
1858 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001859 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001860 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001861 }
1862
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001863 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001864 const int diff_stream_delay_ms =
1865 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1866 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1867 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001868 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1869 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001870 if (capture_.stream_delay_jumps == -1) {
1871 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001872 }
peahdf3efa82015-11-28 12:35:15 -08001873 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001874 }
peahdf3efa82015-11-28 12:35:15 -08001875 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001876
1877 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001878 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001879 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001880 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001881 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001882 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1883 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001884 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001885 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001886 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001887 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001888 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1889 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1890 100);
peahdf3efa82015-11-28 12:35:15 -08001891 if (capture_.aec_system_delay_jumps == -1) {
1892 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001893 }
peahdf3efa82015-11-28 12:35:15 -08001894 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001895 }
peahdf3efa82015-11-28 12:35:15 -08001896 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001897 }
1898}
1899
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001900void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001901 // Run in a single-threaded manner.
1902 rtc::CritScope cs_render(&crit_render_);
1903 rtc::CritScope cs_capture(&crit_capture_);
1904
1905 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001906 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001907 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001908 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001909 }
peahdf3efa82015-11-28 12:35:15 -08001910 capture_.stream_delay_jumps = -1;
1911 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001912
peahdf3efa82015-11-28 12:35:15 -08001913 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001914 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1915 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001916 }
peahdf3efa82015-11-28 12:35:15 -08001917 capture_.aec_system_delay_jumps = -1;
1918 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001919}
1920
aleloi868f32f2017-05-23 07:20:05 -07001921void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1922 if (!aec_dump_) {
1923 return;
1924 }
1925 std::string experiments_description =
1926 public_submodules_->echo_cancellation->GetExperimentsDescription();
1927 // TODO(peah): Add semicolon-separated concatenations of experiment
1928 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001929 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1930 experiments_description += "AgcClippingLevelExperiment;";
1931 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001932 if (capture_nonlocked_.echo_controller_enabled) {
1933 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001934 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001935 if (config_.gain_controller2.enabled) {
1936 experiments_description += "GainController2;";
1937 }
aleloi868f32f2017-05-23 07:20:05 -07001938
1939 InternalAPMConfig apm_config;
1940
1941 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1942 apm_config.aec_delay_agnostic_enabled =
1943 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1944 apm_config.aec_drift_compensation_enabled =
1945 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1946 apm_config.aec_extended_filter_enabled =
1947 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1948 apm_config.aec_suppression_level = static_cast<int>(
1949 public_submodules_->echo_cancellation->suppression_level());
1950
1951 apm_config.aecm_enabled =
1952 public_submodules_->echo_control_mobile->is_enabled();
1953 apm_config.aecm_comfort_noise_enabled =
1954 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1955 apm_config.aecm_routing_mode =
1956 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1957
1958 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1959 apm_config.agc_mode =
1960 static_cast<int>(public_submodules_->gain_control->mode());
1961 apm_config.agc_limiter_enabled =
1962 public_submodules_->gain_control->is_limiter_enabled();
1963 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1964
1965 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1966
1967 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1968 apm_config.ns_level =
1969 static_cast<int>(public_submodules_->noise_suppression->level());
1970
1971 apm_config.transient_suppression_enabled =
1972 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001973 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001974 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1975 apm_config.pre_amplifier_fixed_gain_factor =
1976 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001977
1978 if (!forced && apm_config == apm_config_for_aec_dump_) {
1979 return;
1980 }
1981 aec_dump_->WriteConfig(apm_config);
1982 apm_config_for_aec_dump_ = apm_config;
1983}
1984
1985void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1986 const float* const* src) {
1987 RTC_DCHECK(aec_dump_);
1988 WriteAecDumpConfigMessage(false);
1989
1990 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1991 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1992 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001993 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001994 RecordAudioProcessingState();
1995}
1996
1997void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1998 const AudioFrame& capture_frame) {
1999 RTC_DCHECK(aec_dump_);
2000 WriteAecDumpConfigMessage(false);
2001
2002 aec_dump_->AddCaptureStreamInput(capture_frame);
2003 RecordAudioProcessingState();
2004}
2005
2006void AudioProcessingImpl::RecordProcessedCaptureStream(
2007 const float* const* processed_capture_stream) {
2008 RTC_DCHECK(aec_dump_);
2009
2010 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2011 const size_t num_channels =
2012 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002013 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2014 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002015 aec_dump_->WriteCaptureStreamMessage();
2016}
2017
2018void AudioProcessingImpl::RecordProcessedCaptureStream(
2019 const AudioFrame& processed_capture_frame) {
2020 RTC_DCHECK(aec_dump_);
2021
2022 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2023 aec_dump_->WriteCaptureStreamMessage();
2024}
2025
2026void AudioProcessingImpl::RecordAudioProcessingState() {
2027 RTC_DCHECK(aec_dump_);
2028 AecDump::AudioProcessingState audio_proc_state;
2029 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2030 audio_proc_state.drift =
2031 public_submodules_->echo_cancellation->stream_drift_samples();
2032 audio_proc_state.level = gain_control()->stream_analog_level();
2033 audio_proc_state.keypress = capture_.key_pressed;
2034 aec_dump_->AddAudioProcessingState(audio_proc_state);
2035}
2036
kwiberg83ffe452016-08-29 14:46:07 -07002037AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002038 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002039 : aec_system_delay_jumps(-1),
2040 delay_offset_ms(0),
2041 was_stream_delay_set(false),
2042 last_stream_delay_ms(0),
2043 last_aec_system_delay_ms(0),
2044 stream_delay_jumps(-1),
2045 output_will_be_muted(false),
2046 key_pressed(false),
2047 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002048 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002049 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002050 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002051 prev_analog_mic_level(-1),
2052 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002053
2054AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2055
2056AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2057
2058AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2059
niklase@google.com470e71d2011-07-07 08:21:25 +00002060} // namespace webrtc