blob: 3400abf6f21afba3c8a0f8997dc6890324d82ace [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
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <type_traits>
17#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000018
Yves Gerey988cc082018-10-23 12:03:01 +020019#include "absl/types/optional.h"
20#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/include/audio_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020024#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/common.h"
27#include "modules/audio_processing/echo_cancellation_impl.h"
28#include "modules/audio_processing/echo_control_mobile_impl.h"
29#include "modules/audio_processing/gain_control_for_experimental_agc.h"
30#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010031#include "modules/audio_processing/gain_controller2.h"
Yves Gerey988cc082018-10-23 12:03:01 +020032#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020033#include "modules/audio_processing/level_estimator_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010034#include "modules/audio_processing/logging/apm_data_dumper.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020035#include "modules/audio_processing/low_cut_filter.h"
36#include "modules/audio_processing/noise_suppression_impl.h"
Sam Zackrisson23513132019-01-11 15:10:32 +010037#include "modules/audio_processing/noise_suppression_proxy.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020038#include "modules/audio_processing/residual_echo_detector.h"
39#include "modules/audio_processing/transient/transient_suppressor.h"
40#include "modules/audio_processing/voice_detection_impl.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080043#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "rtc_base/ref_counted_object.h"
46#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/trace_event.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000049
Michael Graczyk86c6d332015-07-23 11:41:39 -070050#define RETURN_ON_ERR(expr) \
51 do { \
52 int err = (expr); \
53 if (err != kNoError) { \
54 return err; \
55 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000056 } while (0)
57
niklase@google.com470e71d2011-07-07 08:21:25 +000058namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070059
kwibergd59d3bb2016-09-13 07:49:33 -070060constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020061constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070062
Michael Graczyk86c6d332015-07-23 11:41:39 -070063namespace {
64
65static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
66 switch (layout) {
67 case AudioProcessing::kMono:
68 case AudioProcessing::kStereo:
69 return false;
70 case AudioProcessing::kMonoAndKeyboard:
71 case AudioProcessing::kStereoAndKeyboard:
72 return true;
73 }
74
kwiberg9e2be5f2016-09-14 05:23:22 -070075 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070076 return false;
77}
aluebsdf6416a2016-03-16 18:26:35 -070078
peah2ace3f92016-09-10 04:42:27 -070079bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070080 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
81 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
82}
83
peah2ace3f92016-09-10 04:42:27 -070084int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
85#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070086 constexpr int kMaxSplittingNativeProcessRate =
87 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070088#else
kwibergd59d3bb2016-09-13 07:49:33 -070089 constexpr int kMaxSplittingNativeProcessRate =
90 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070091#endif
kwibergd59d3bb2016-09-13 07:49:33 -070092 static_assert(
93 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
94 "");
peah2ace3f92016-09-10 04:42:27 -070095 const int uppermost_native_rate = band_splitting_required
96 ? kMaxSplittingNativeProcessRate
97 : AudioProcessing::kSampleRate48kHz;
98
99 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
100 if (rate >= uppermost_native_rate) {
101 return uppermost_native_rate;
102 }
103 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700104 return rate;
105 }
106 }
peah2ace3f92016-09-10 04:42:27 -0700107 RTC_NOTREACHED();
108 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700109}
110
Sam Zackrisson23513132019-01-11 15:10:32 +0100111NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
112 AudioProcessing::Config::NoiseSuppression::Level level) {
113 using NsConfig = AudioProcessing::Config::NoiseSuppression;
114 switch (level) {
115 case NsConfig::kLow:
116 return NoiseSuppression::kLow;
117 case NsConfig::kModerate:
118 return NoiseSuppression::kModerate;
119 case NsConfig::kHigh:
120 return NoiseSuppression::kHigh;
121 case NsConfig::kVeryHigh:
122 return NoiseSuppression::kVeryHigh;
123 default:
124 RTC_NOTREACHED();
125 }
126}
127
peah9e6a2902017-05-15 07:19:21 -0700128// Maximum lengths that frame of samples being passed from the render side to
129// the capture side can have (does not apply to AEC3).
130static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
131static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
132
peah764e3642016-10-22 05:04:30 -0700133// Maximum number of frames to buffer in the render queue.
134// TODO(peah): Decrease this once we properly handle hugely unbalanced
135// reverse and forward call numbers.
136static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700137} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000138
139// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000140static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000141
Sam Zackrisson0beac582017-09-25 12:04:02 +0200142AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100143 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200144 bool render_pre_processor_enabled,
145 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100146 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200147 render_pre_processor_enabled_(render_pre_processor_enabled),
148 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700149
150bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200151 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700152 bool echo_canceller_enabled,
153 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700154 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700155 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700156 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700157 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200158 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200159 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700160 bool voice_activity_detector_enabled,
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100161 bool private_voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700162 bool level_estimator_enabled,
163 bool transient_suppressor_enabled) {
164 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200165 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700166 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
167 changed |=
168 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700169 changed |=
170 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700171 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
172 changed |=
peah2ace3f92016-09-10 04:42:27 -0700173 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700174 changed |=
175 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200176 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200177 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700178 changed |= (level_estimator_enabled != level_estimator_enabled_);
179 changed |=
180 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100181 changed |=
182 (private_voice_detector_enabled != private_voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700183 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
184 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200185 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700186 echo_canceller_enabled_ = echo_canceller_enabled;
187 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700188 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700189 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700190 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700191 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200192 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200193 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700194 level_estimator_enabled_ = level_estimator_enabled;
195 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100196 private_voice_detector_enabled_ = private_voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700197 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 {
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100207 return CaptureMultiBandProcessingActive() ||
208 voice_activity_detector_enabled_ || private_voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700209}
210
211bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
212 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200213 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700214 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200215 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700216}
217
peah23ac8b42017-05-23 05:33:56 -0700218bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
219 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200220 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
221 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700222}
223
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200224bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
225 return capture_analyzer_enabled_;
226}
227
peah2ace3f92016-09-10 04:42:27 -0700228bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
229 const {
230 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800231 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200232 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700233}
234
Alex Loiko5825aa62017-12-18 16:02:40 +0100235bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
236 const {
237 return render_pre_processor_enabled_;
238}
239
peah2ace3f92016-09-10 04:42:27 -0700240bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
241 const {
peah2ace3f92016-09-10 04:42:27 -0700242 return false;
peah2ace3f92016-09-10 04:42:27 -0700243}
244
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200245bool AudioProcessingImpl::ApmSubmoduleStates::LowCutFilteringRequired() const {
246 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
247 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
248}
249
solenberg5e465c32015-12-08 13:22:33 -0800250struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800251 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800252 // Accessed externally of APM without any lock acquired.
Sam Zackrisson23513132019-01-11 15:10:32 +0100253 // TODO(bugs.webrtc.org/9947): Move these submodules into private_submodules_
254 // when their pointer-to-submodule API functions are gone.
peahbfa97112016-03-10 21:09:04 -0800255 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800256 std::unique_ptr<LevelEstimatorImpl> level_estimator;
257 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
Sam Zackrisson23513132019-01-11 15:10:32 +0100258 std::unique_ptr<NoiseSuppressionProxy> noise_suppression_proxy;
kwiberg88788ad2016-02-19 07:04:49 -0800259 std::unique_ptr<VoiceDetectionImpl> voice_detection;
260 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800261 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800262
263 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800264 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800265};
266
267struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200268 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100269 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200270 rtc::scoped_refptr<EchoDetector> echo_detector,
271 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200272 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100273 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200274 render_pre_processor(std::move(render_pre_processor)),
275 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800276 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800277 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700278 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800279 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200280 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100281 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100282 std::unique_ptr<EchoControl> echo_controller;
283 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100284 std::unique_ptr<CustomProcessing> capture_post_processor;
285 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200286 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200287 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100288 std::unique_ptr<LevelEstimatorImpl> output_level_estimator;
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100289 std::unique_ptr<VoiceDetectionImpl> voice_detector;
solenberg5e465c32015-12-08 13:22:33 -0800290};
291
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100292AudioProcessingBuilder::AudioProcessingBuilder() = default;
293AudioProcessingBuilder::~AudioProcessingBuilder() = default;
294
295AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
296 std::unique_ptr<CustomProcessing> capture_post_processing) {
297 capture_post_processing_ = std::move(capture_post_processing);
298 return *this;
299}
300
301AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
302 std::unique_ptr<CustomProcessing> render_pre_processing) {
303 render_pre_processing_ = std::move(render_pre_processing);
304 return *this;
305}
306
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200307AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
308 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
309 capture_analyzer_ = std::move(capture_analyzer);
310 return *this;
311}
312
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100313AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
314 std::unique_ptr<EchoControlFactory> echo_control_factory) {
315 echo_control_factory_ = std::move(echo_control_factory);
316 return *this;
317}
318
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100319AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200320 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100321 echo_detector_ = std::move(echo_detector);
322 return *this;
323}
324
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100325AudioProcessing* AudioProcessingBuilder::Create() {
326 webrtc::Config config;
327 return Create(config);
328}
329
330AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100331 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
332 config, std::move(capture_post_processing_),
333 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200334 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100335 if (apm->Initialize() != AudioProcessing::kNoError) {
336 delete apm;
337 apm = nullptr;
338 }
339 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100340}
341
peah88ac8532016-09-12 16:47:25 -0700342AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200343 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
344}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000345
Per Åhgren13735822018-02-12 21:42:56 +0100346int AudioProcessingImpl::instance_count_ = 0;
347
Sam Zackrisson0beac582017-09-25 12:04:02 +0200348AudioProcessingImpl::AudioProcessingImpl(
349 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100350 std::unique_ptr<CustomProcessing> capture_post_processor,
351 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200352 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200353 rtc::scoped_refptr<EchoDetector> echo_detector,
354 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100355 : data_dumper_(
356 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200357 capture_runtime_settings_(kRuntimeSettingQueueSize),
358 render_runtime_settings_(kRuntimeSettingQueueSize),
359 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
360 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200361 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200362 submodule_states_(!!capture_post_processor,
363 !!render_pre_processor,
364 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800365 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200366 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200367 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100368 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200369 std::move(echo_detector),
370 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800371 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800372 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000373#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200374 /* enabled= */ false,
375 /* enabled_agc2_level_estimator= */ false,
376 /* digital_adaptive_disabled= */ false,
377 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000378#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200379 config.Get<ExperimentalAgc>().enabled,
380 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200381 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
382 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000383#endif
andrew1c7075f2015-06-24 18:14:14 -0700384#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200385 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700386#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200387 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700388#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200389 capture_nonlocked_() {
Sam Zackrisson421c8592019-02-11 13:39:46 +0100390 // Mark Echo Controller enabled if a factory is injected.
391 capture_nonlocked_.echo_controller_enabled =
392 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000393
Sam Zackrisson421c8592019-02-11 13:39:46 +0100394 public_submodules_->gain_control.reset(new GainControlImpl(&crit_capture_));
395 public_submodules_->level_estimator.reset(
396 new LevelEstimatorImpl(&crit_capture_));
397 public_submodules_->noise_suppression.reset(
398 new NoiseSuppressionImpl(&crit_capture_));
399 public_submodules_->noise_suppression_proxy.reset(new NoiseSuppressionProxy(
400 this, public_submodules_->noise_suppression.get()));
401 public_submodules_->voice_detection.reset(
402 new VoiceDetectionImpl(&crit_capture_));
403 public_submodules_->gain_control_for_experimental_agc.reset(
404 new GainControlForExperimentalAgc(public_submodules_->gain_control.get(),
405 &crit_capture_));
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200406
Sam Zackrisson421c8592019-02-11 13:39:46 +0100407 // If no echo detector is injected, use the ResidualEchoDetector.
408 if (!private_submodules_->echo_detector) {
409 private_submodules_->echo_detector =
410 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800411 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000412
Sam Zackrisson421c8592019-02-11 13:39:46 +0100413 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
414 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
415 // TODO(alessiob): Move the injected gain controller once injection is
416 // implemented.
417 private_submodules_->gain_controller2.reset(new GainController2());
418
419 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
420 << !!private_submodules_->capture_analyzer
421 << "\nCapture post processor activated: "
422 << !!private_submodules_->capture_post_processor
423 << "\nRender pre processor activated: "
424 << !!private_submodules_->render_pre_processor;
425
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000426 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000427}
428
429AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800430 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800431 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800432 private_submodules_->agc_manager.reset();
433 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800434 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000435}
436
niklase@google.com470e71d2011-07-07 08:21:25 +0000437int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800438 // Run in a single-threaded manner during initialization.
439 rtc::CritScope cs_render(&crit_render_);
440 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000441 return InitializeLocked();
442}
443
peahde65ddc2016-09-16 15:02:15 -0700444int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
445 int capture_output_sample_rate_hz,
446 int render_input_sample_rate_hz,
447 ChannelLayout capture_input_layout,
448 ChannelLayout capture_output_layout,
449 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700450 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700451 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
452 LayoutHasKeyboard(capture_input_layout)},
453 {capture_output_sample_rate_hz,
454 ChannelsFromLayout(capture_output_layout),
455 LayoutHasKeyboard(capture_output_layout)},
456 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
457 LayoutHasKeyboard(render_input_layout)},
458 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
459 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700460
461 return Initialize(processing_config);
462}
463
464int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800465 // Run in a single-threaded manner during initialization.
466 rtc::CritScope cs_render(&crit_render_);
467 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700468 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000469}
470
peahdf3efa82015-11-28 12:35:15 -0800471int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800472 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700473 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800474}
475
peahdf3efa82015-11-28 12:35:15 -0800476int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700477 const ProcessingConfig& processing_config,
478 bool force_initialization) {
479 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800480}
481
peah192164e2015-11-17 02:16:45 -0800482// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800483// their current values (needs to be called while holding the crit_render_lock).
484int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700485 const ProcessingConfig& processing_config,
486 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800487 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700488 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800489 return kNoError;
490 }
peahdf3efa82015-11-28 12:35:15 -0800491
492 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800493 return InitializeLocked(processing_config);
494}
495
niklase@google.com470e71d2011-07-07 08:21:25 +0000496int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200497 UpdateActiveSubmoduleStates();
498
peahde65ddc2016-09-16 15:02:15 -0700499 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800500 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700501 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800502 : formats_.api_format.reverse_output_stream().num_frames();
503 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
504 render_.render_audio.reset(new AudioBuffer(
505 formats_.api_format.reverse_input_stream().num_frames(),
506 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700507 formats_.render_processing_format.num_frames(),
508 formats_.render_processing_format.num_channels(),
509 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700510 if (formats_.api_format.reverse_input_stream() !=
511 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800512 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800513 formats_.api_format.reverse_input_stream().num_channels(),
514 formats_.api_format.reverse_input_stream().num_frames(),
515 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800516 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700517 } else {
peahdf3efa82015-11-28 12:35:15 -0800518 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700519 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700520 } else {
peahdf3efa82015-11-28 12:35:15 -0800521 render_.render_audio.reset(nullptr);
522 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700523 }
peahce4d9152017-05-19 01:28:05 -0700524
peahdf3efa82015-11-28 12:35:15 -0800525 capture_.capture_audio.reset(
526 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
527 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700528 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200529 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800530 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000531
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100532 private_submodules_->echo_cancellation->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700533 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
534 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700535 AllocateRenderQueue();
536
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100537 int success = private_submodules_->echo_cancellation->enable_metrics(true);
ivoc3e9a5372016-10-28 07:55:33 -0700538 RTC_DCHECK_EQ(0, success);
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100539 success = private_submodules_->echo_cancellation->enable_delay_logging(true);
ivoc3e9a5372016-10-28 07:55:33 -0700540 RTC_DCHECK_EQ(0, success);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100541 private_submodules_->echo_control_mobile->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700542 proc_split_sample_rate_hz(), num_reverse_channels(),
543 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700544
545 public_submodules_->gain_control->Initialize(num_proc_channels(),
546 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700547 if (constants_.use_experimental_agc) {
548 if (!private_submodules_->agc_manager.get()) {
549 private_submodules_->agc_manager.reset(new AgcManagerDirect(
550 public_submodules_->gain_control.get(),
551 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200552 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
553 constants_.use_experimental_agc_agc2_level_estimation,
554 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700555 }
556 private_submodules_->agc_manager->Initialize();
557 private_submodules_->agc_manager->SetCaptureMuted(
558 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700559 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700560 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200561 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800562 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700563 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
564 proc_sample_rate_hz());
565 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100566 if (private_submodules_->voice_detector) {
567 private_submodules_->voice_detector->Initialize(
568 proc_split_sample_rate_hz());
569 }
peahde65ddc2016-09-16 15:02:15 -0700570 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700571 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200572 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700573 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200574 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200575 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100576 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800577
aleloi868f32f2017-05-23 07:20:05 -0700578 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200579 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700580 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000581 return kNoError;
582}
583
Michael Graczyk86c6d332015-07-23 11:41:39 -0700584int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200585 UpdateActiveSubmoduleStates();
586
Michael Graczyk86c6d332015-07-23 11:41:39 -0700587 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700588 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
589 return kBadSampleRateError;
590 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000591 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700592
Peter Kasting69558702016-01-12 16:26:35 -0800593 const size_t num_in_channels = config.input_stream().num_channels();
594 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700595
596 // Need at least one input channel.
597 // Need either one output channel or as many outputs as there are inputs.
598 if (num_in_channels == 0 ||
599 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700600 return kBadNumberChannelsError;
601 }
602
peahdf3efa82015-11-28 12:35:15 -0800603 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000604
peahde65ddc2016-09-16 15:02:15 -0700605 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700606 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700607 formats_.api_format.output_stream().sample_rate_hz()),
608 submodule_states_.CaptureMultiBandSubModulesActive() ||
609 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000610
peahde65ddc2016-09-16 15:02:15 -0700611 capture_nonlocked_.capture_processing_format =
612 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700613
peah2ce640f2017-04-07 03:57:48 -0700614 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200615 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700616 render_processing_rate = FindNativeProcessRateToUse(
617 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
618 formats_.api_format.reverse_output_stream().sample_rate_hz()),
619 submodule_states_.CaptureMultiBandSubModulesActive() ||
620 submodule_states_.RenderMultiBandSubModulesActive());
621 } else {
622 render_processing_rate = capture_processing_rate;
623 }
624
aluebseb3603b2016-04-20 15:27:58 -0700625 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
626 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700627 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200628 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700629 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
630 ? kSampleRate32kHz
631 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700632 }
peah2ce640f2017-04-07 03:57:48 -0700633
peahde65ddc2016-09-16 15:02:15 -0700634 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700635 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700636 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
637 kSampleRate8kHz) {
638 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000639 } else {
peahde65ddc2016-09-16 15:02:15 -0700640 render_processing_rate =
641 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000642 }
643
peahde65ddc2016-09-16 15:02:15 -0700644 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000645 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700646 if (submodule_states_.RenderMultiBandSubModulesActive()) {
647 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
648 } else {
649 formats_.render_processing_format = StreamConfig(
650 formats_.api_format.reverse_input_stream().sample_rate_hz(),
651 formats_.api_format.reverse_input_stream().num_channels());
652 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000653
peahde65ddc2016-09-16 15:02:15 -0700654 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
655 kSampleRate32kHz ||
656 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
657 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800658 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000659 } else {
peahdf3efa82015-11-28 12:35:15 -0800660 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700661 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000662 }
663
664 return InitializeLocked();
665}
666
peah88ac8532016-09-12 16:47:25 -0700667void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700668 // Run in a single-threaded manner when applying the settings.
669 rtc::CritScope cs_render(&crit_render_);
670 rtc::CritScope cs_capture(&crit_capture_);
671
Yves Gerey499bc6c2018-10-10 18:29:07 +0200672 config_ = config;
673
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100674 private_submodules_->echo_cancellation->Enable(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200675 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100676 private_submodules_->echo_control_mobile->Enable(
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200677 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200678
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100679 private_submodules_->echo_cancellation->set_suppression_level(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200680 config.echo_canceller.legacy_moderate_suppression_level
sazabe490b22018-10-03 17:03:13 +0200681 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
682 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200683
Sam Zackrisson23513132019-01-11 15:10:32 +0100684 public_submodules_->noise_suppression->Enable(
685 config.noise_suppression.enabled);
686 public_submodules_->noise_suppression->set_level(
687 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
688
peah8271d042016-11-22 07:24:52 -0800689 InitializeLowCutFilter();
690
Mirko Bonadei675513b2017-11-09 11:09:25 +0100691 RTC_LOG(LS_INFO) << "Highpass filter activated: "
692 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800693
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100694 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700695 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100696 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
697 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100698 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100699 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700700 config_.gain_controller2 = AudioProcessing::Config::GainController2();
701 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200702 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200703 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200704 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100705 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
706 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200707 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
708 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100709
710 if (config_.level_estimation.enabled &&
711 !private_submodules_->output_level_estimator) {
712 private_submodules_->output_level_estimator.reset(
713 new LevelEstimatorImpl(&crit_capture_));
714 private_submodules_->output_level_estimator->Enable(true);
715 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100716
717 if (config_.voice_detection.enabled && !private_submodules_->voice_detector) {
718 private_submodules_->voice_detector.reset(
719 new VoiceDetectionImpl(&crit_capture_));
720 private_submodules_->voice_detector->Enable(true);
721 private_submodules_->voice_detector->set_likelihood(
722 VoiceDetection::kVeryLowLikelihood);
723 private_submodules_->voice_detector->Initialize(
724 proc_split_sample_rate_hz());
725 }
peah88ac8532016-09-12 16:47:25 -0700726}
727
728void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800729 // Run in a single-threaded manner when setting the extra options.
730 rtc::CritScope cs_render(&crit_render_);
731 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000732
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100733 private_submodules_->echo_cancellation->SetExtraOptions(config);
peahb624d8c2016-03-05 03:01:14 -0800734
peahdf3efa82015-11-28 12:35:15 -0800735 if (capture_.transient_suppressor_enabled !=
736 config.Get<ExperimentalNs>().enabled) {
737 capture_.transient_suppressor_enabled =
738 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000739 InitializeTransient();
740 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000741}
742
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000743int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800744 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700745 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000746}
747
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000748int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800749 // Used as callback from submodules, hence locking is not allowed.
750 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000751}
752
Peter Kasting69558702016-01-12 16:26:35 -0800753size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800754 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700755 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000756}
757
Peter Kasting69558702016-01-12 16:26:35 -0800758size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800759 // Used as callback from submodules, hence locking is not allowed.
760 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000761}
762
Peter Kasting69558702016-01-12 16:26:35 -0800763size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800764 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200765 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800766}
767
Peter Kasting69558702016-01-12 16:26:35 -0800768size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800769 // Used as callback from submodules, hence locking is not allowed.
770 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000771}
772
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000773void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800774 rtc::CritScope cs(&crit_capture_);
775 capture_.output_will_be_muted = muted;
776 if (private_submodules_->agc_manager.get()) {
777 private_submodules_->agc_manager->SetCaptureMuted(
778 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000779 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000780}
781
Alessio Bazzicac054e782018-04-16 12:10:09 +0200782void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200783 switch (setting.type()) {
784 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
785 render_runtime_settings_enqueuer_.Enqueue(setting);
786 return;
787 case RuntimeSetting::Type::kNotSpecified:
788 RTC_NOTREACHED();
789 return;
790 case RuntimeSetting::Type::kCapturePreGain:
791 capture_runtime_settings_enqueuer_.Enqueue(setting);
792 return;
793 }
794 // The language allows the enum to have a non-enumerator
795 // value. Check that this doesn't happen.
796 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200797}
798
799AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
800 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200801 : runtime_settings_(*runtime_settings) {
802 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200803}
804
805AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
806 default;
807
808void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
809 RuntimeSetting setting) {
810 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200811 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200812 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200813 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200814 RTC_LOG(LS_ERROR)
815 << "The runtime settings queue is full. Oldest setting discarded.";
816 }
817 if (remaining_attempts == 0)
818 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
819}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000820
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000821int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700822 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000823 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000824 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000825 int output_sample_rate_hz,
826 ChannelLayout output_layout,
827 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800828 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800829 StreamConfig input_stream;
830 StreamConfig output_stream;
831 {
832 // Access the formats_.api_format.input_stream beneath the capture lock.
833 // The lock must be released as it is later required in the call
834 // to ProcessStream(,,,);
835 rtc::CritScope cs(&crit_capture_);
836 input_stream = formats_.api_format.input_stream();
837 output_stream = formats_.api_format.output_stream();
838 }
839
Michael Graczyk86c6d332015-07-23 11:41:39 -0700840 input_stream.set_sample_rate_hz(input_sample_rate_hz);
841 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
842 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700843 output_stream.set_sample_rate_hz(output_sample_rate_hz);
844 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
845 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
846
847 if (samples_per_channel != input_stream.num_frames()) {
848 return kBadDataLengthError;
849 }
850 return ProcessStream(src, input_stream, output_stream, dest);
851}
852
853int AudioProcessingImpl::ProcessStream(const float* const* src,
854 const StreamConfig& input_config,
855 const StreamConfig& output_config,
856 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800857 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800858 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700859 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800860 {
861 // Acquire the capture lock in order to safely call the function
862 // that retrieves the render side data. This function accesses apm
863 // getters that need the capture lock held when being called.
864 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700865 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800866
867 if (!src || !dest) {
868 return kNullPointerError;
869 }
870
871 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700872 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000873 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000874
Michael Graczyk86c6d332015-07-23 11:41:39 -0700875 processing_config.input_stream() = input_config;
876 processing_config.output_stream() = output_config;
877
peahdf3efa82015-11-28 12:35:15 -0800878 {
879 // Do conditional reinitialization.
880 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700881 RETURN_ON_ERR(
882 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800883 }
884 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700885 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
886 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000887
aleloi868f32f2017-05-23 07:20:05 -0700888 if (aec_dump_) {
889 RecordUnprocessedCaptureStream(src);
890 }
891
peahdf3efa82015-11-28 12:35:15 -0800892 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700893 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800894 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000895
aleloi868f32f2017-05-23 07:20:05 -0700896 if (aec_dump_) {
897 RecordProcessedCaptureStream(dest);
898 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000899 return kNoError;
900}
901
Alex Loiko73ec0192018-05-15 10:52:28 +0200902void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200903 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200904 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200905 if (aec_dump_) {
906 aec_dump_->WriteRuntimeSetting(setting);
907 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200908 switch (setting.type()) {
909 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200910 if (config_.pre_amplifier.enabled) {
911 float value;
912 setting.GetFloat(&value);
913 private_submodules_->pre_amplifier->SetGainFactor(value);
914 }
915 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200916 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200917 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
918 RTC_NOTREACHED();
919 break;
920 case RuntimeSetting::Type::kNotSpecified:
921 RTC_NOTREACHED();
922 break;
923 }
924 }
925}
926
927void AudioProcessingImpl::HandleRenderRuntimeSettings() {
928 RuntimeSetting setting;
929 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200930 if (aec_dump_) {
931 aec_dump_->WriteRuntimeSetting(setting);
932 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200933 switch (setting.type()) {
934 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
935 if (private_submodules_->render_pre_processor) {
936 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
937 }
938 break;
939 case RuntimeSetting::Type::kCapturePreGain:
940 RTC_NOTREACHED();
941 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200942 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200943 RTC_NOTREACHED();
944 break;
945 }
946 }
947}
948
peah9e6a2902017-05-15 07:19:21 -0700949void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700950 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
951 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700952 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700953
kwibergaf476c72016-11-28 15:21:39 -0800954 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700955
956 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700957 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700958 // The data queue is full and needs to be emptied.
959 EmptyQueuedRenderAudio();
960
961 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700962 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700963 RTC_DCHECK(result);
964 }
965
966 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
967 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700968 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700969
970 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700971 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700972 // The data queue is full and needs to be emptied.
973 EmptyQueuedRenderAudio();
974
975 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700976 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700977 RTC_DCHECK(result);
978 }
peah701d6282016-10-25 05:42:20 -0700979
980 if (!constants_.use_experimental_agc) {
981 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
982 // Insert the samples into the queue.
983 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
984 // The data queue is full and needs to be emptied.
985 EmptyQueuedRenderAudio();
986
987 // Retry the insert (should always work).
988 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
989 RTC_DCHECK(result);
990 }
991 }
peah9e6a2902017-05-15 07:19:21 -0700992}
ivoc9f4a4a02016-10-28 05:39:16 -0700993
peah9e6a2902017-05-15 07:19:21 -0700994void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700995 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
996
997 // Insert the samples into the queue.
998 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
999 // The data queue is full and needs to be emptied.
1000 EmptyQueuedRenderAudio();
1001
1002 // Retry the insert (should always work).
1003 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1004 RTC_DCHECK(result);
1005 }
peah764e3642016-10-22 05:04:30 -07001006}
1007
1008void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001009 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -07001010 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001011 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -07001012 EchoCancellationImpl::NumCancellersRequired(
1013 num_output_channels(), num_reverse_channels()));
1014
peah701d6282016-10-25 05:42:20 -07001015 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001016 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001017 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001018 EchoControlMobileImpl::NumCancellersRequired(
1019 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001020
peah701d6282016-10-25 05:42:20 -07001021 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001022 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001023
ivoc9f4a4a02016-10-28 05:39:16 -07001024 const size_t new_red_render_queue_element_max_size =
1025 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1026
peaha0624602016-10-25 04:45:24 -07001027 // Reallocate the queues if the queue item sizes are too small to fit the
1028 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001029 if (aec_render_queue_element_max_size_ <
1030 new_aec_render_queue_element_max_size) {
1031 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001032
peaha0624602016-10-25 04:45:24 -07001033 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001034 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001035
peah701d6282016-10-25 05:42:20 -07001036 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001037 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1038 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001039 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001040 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001041
peah701d6282016-10-25 05:42:20 -07001042 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1043 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001044 } else {
peah701d6282016-10-25 05:42:20 -07001045 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001046 }
1047
peah701d6282016-10-25 05:42:20 -07001048 if (aecm_render_queue_element_max_size_ <
1049 new_aecm_render_queue_element_max_size) {
1050 aecm_render_queue_element_max_size_ =
1051 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001052
1053 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001054 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001055
peah701d6282016-10-25 05:42:20 -07001056 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001057 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1058 kMaxNumFramesToBuffer, template_queue_element,
1059 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001060 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001061
peah701d6282016-10-25 05:42:20 -07001062 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1063 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001064 } else {
peah701d6282016-10-25 05:42:20 -07001065 aecm_render_signal_queue_->Clear();
1066 }
1067
1068 if (agc_render_queue_element_max_size_ <
1069 new_agc_render_queue_element_max_size) {
1070 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1071
1072 std::vector<int16_t> template_queue_element(
1073 agc_render_queue_element_max_size_);
1074
1075 agc_render_signal_queue_.reset(
1076 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1077 kMaxNumFramesToBuffer, template_queue_element,
1078 RenderQueueItemVerifier<int16_t>(
1079 agc_render_queue_element_max_size_)));
1080
1081 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1082 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1083 } else {
1084 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001085 }
ivoc9f4a4a02016-10-28 05:39:16 -07001086
1087 if (red_render_queue_element_max_size_ <
1088 new_red_render_queue_element_max_size) {
1089 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1090
1091 std::vector<float> template_queue_element(
1092 red_render_queue_element_max_size_);
1093
1094 red_render_signal_queue_.reset(
1095 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1096 kMaxNumFramesToBuffer, template_queue_element,
1097 RenderQueueItemVerifier<float>(
1098 red_render_queue_element_max_size_)));
1099
1100 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1101 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1102 } else {
1103 red_render_signal_queue_->Clear();
1104 }
peah764e3642016-10-22 05:04:30 -07001105}
1106
1107void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1108 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001109 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001110 private_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001111 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001112 }
1113
peah701d6282016-10-25 05:42:20 -07001114 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001115 private_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001116 aecm_capture_queue_buffer_);
1117 }
1118
1119 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1120 public_submodules_->gain_control->ProcessRenderAudio(
1121 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001122 }
ivoc9f4a4a02016-10-28 05:39:16 -07001123
1124 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001125 RTC_DCHECK(private_submodules_->echo_detector);
1126 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001127 red_capture_queue_buffer_);
1128 }
peah764e3642016-10-22 05:04:30 -07001129}
1130
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001131int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001132 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001133 {
1134 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001135 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001136 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001137 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001138 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001139 }
peahfa6228e2015-11-16 16:27:42 -08001140
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001141 if (!frame) {
1142 return kNullPointerError;
1143 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001144 // Must be a native rate.
1145 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1146 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001147 frame->sample_rate_hz_ != kSampleRate32kHz &&
1148 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001149 return kBadSampleRateError;
1150 }
peah192164e2015-11-17 02:16:45 -08001151
peahdf3efa82015-11-28 12:35:15 -08001152 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001153 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001154 {
1155 // Aquire lock for the access of api_format.
1156 // The lock is released immediately due to the conditional
1157 // reinitialization.
1158 rtc::CritScope cs_capture(&crit_capture_);
1159 // TODO(ajm): The input and output rates and channels are currently
1160 // constrained to be identical in the int16 interface.
1161 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001162
1163 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001164 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001165 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1166 processing_config.input_stream().set_num_channels(frame->num_channels_);
1167 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1168 processing_config.output_stream().set_num_channels(frame->num_channels_);
1169
peahdf3efa82015-11-28 12:35:15 -08001170 {
1171 // Do conditional reinitialization.
1172 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001173 RETURN_ON_ERR(
1174 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001175 }
1176 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001177 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001178 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001179 return kBadDataLengthError;
1180 }
1181
aleloi868f32f2017-05-23 07:20:05 -07001182 if (aec_dump_) {
1183 RecordUnprocessedCaptureStream(*frame);
1184 }
1185
peahdf3efa82015-11-28 12:35:15 -08001186 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001187 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001188 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001189 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1190 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001191
aleloi868f32f2017-05-23 07:20:05 -07001192 if (aec_dump_) {
1193 RecordProcessedCaptureStream(*frame);
1194 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001195
1196 return kNoError;
1197}
1198
peahde65ddc2016-09-16 15:02:15 -07001199int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001200 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001201
peahb58a1582016-03-15 09:34:24 -07001202 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001203 // TODO(peah): Simplify once the public API Enable functions for these
1204 // are moved to APM.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001205 RTC_DCHECK(!(private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001206 private_submodules_->echo_control_mobile->is_enabled()));
peahb58a1582016-03-15 09:34:24 -07001207
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001208 MaybeUpdateHistograms();
1209
peahde65ddc2016-09-16 15:02:15 -07001210 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001211
Alex Loikob5c9a792018-04-16 16:31:22 +02001212 if (private_submodules_->pre_amplifier) {
1213 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1214 capture_buffer->channels_f(), capture_buffer->num_channels(),
1215 capture_buffer->num_frames()));
1216 }
1217
peah1b08dc32016-12-20 13:45:58 -08001218 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001219 capture_buffer->channels_const()[0],
1220 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001221 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1222 if (log_rms) {
1223 capture_rms_interval_counter_ = 0;
1224 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001225 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1226 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1227 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1228 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001229 }
1230
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001231 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001232 // Detect and flag any change in the analog gain.
1233 int analog_mic_level = gain_control()->stream_analog_level();
1234 capture_.echo_path_gain_change =
1235 capture_.prev_analog_mic_level != analog_mic_level &&
1236 capture_.prev_analog_mic_level != -1;
1237 capture_.prev_analog_mic_level = analog_mic_level;
1238
Per Åhgrend2650d12018-10-02 17:00:59 +02001239 // Detect and flag any change in the pre-amplifier gain.
1240 if (private_submodules_->pre_amplifier) {
1241 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1242 capture_.echo_path_gain_change =
1243 capture_.echo_path_gain_change ||
1244 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001245 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001246 capture_.prev_pre_amp_gain = pre_amp_gain;
1247 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001248 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001249 }
1250
peahbe615622016-02-13 16:40:47 -08001251 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001252 public_submodules_->gain_control->is_enabled()) {
1253 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001254 capture_buffer->channels()[0], capture_buffer->num_channels(),
1255 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001256
1257 if (constants_.use_experimental_agc_process_before_aec) {
1258 private_submodules_->agc_manager->Process(
1259 capture_buffer->channels()[0],
1260 capture_nonlocked_.capture_processing_format.num_frames(),
1261 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1262 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001263 }
1264
peah2ace3f92016-09-10 04:42:27 -07001265 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1266 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001267 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1268 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001269 }
1270
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001271 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001272 // Force down-mixing of the number of channels after the detection of
1273 // capture signal saturation.
1274 // TODO(peah): Look into ensuring that this kind of tampering with the
1275 // AudioBuffer functionality should not be needed.
1276 capture_buffer->set_num_channels(1);
1277 }
1278
peahe0eae3c2016-12-14 01:16:23 -08001279 // TODO(peah): Move the AEC3 low-cut filter to this place.
1280 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001281 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001282 private_submodules_->low_cut_filter->Process(capture_buffer);
1283 }
peahde65ddc2016-09-16 15:02:15 -07001284 RETURN_ON_ERR(
1285 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1286 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001287
1288 // Ensure that the stream delay was set before the call to the
1289 // AEC ProcessCaptureAudio function.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001290 if (private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001291 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001292 return AudioProcessing::kStreamParameterNotSetError;
1293 }
1294
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001295 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001296 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1297
Per Åhgrend0fa8202018-04-18 09:35:13 +02001298 if (was_stream_delay_set()) {
1299 private_submodules_->echo_controller->SetAudioBufferDelay(
1300 stream_delay_ms());
1301 }
1302
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001303 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001304 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001305 } else {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001306 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
peah61202ac2017-02-06 03:39:42 -08001307 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001308 }
1309
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001310 if (private_submodules_->echo_control_mobile->is_enabled() &&
peahdf3efa82015-11-28 12:35:15 -08001311 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001312 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001313 }
peahde65ddc2016-09-16 15:02:15 -07001314 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001315
1316 // Ensure that the stream delay was set before the call to the
1317 // AECM ProcessCaptureAudio function.
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001318 if (private_submodules_->echo_control_mobile->is_enabled() &&
peah253534d2016-03-15 04:32:28 -07001319 !was_stream_delay_set()) {
1320 return AudioProcessing::kStreamParameterNotSetError;
1321 }
1322
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001323 if (!(private_submodules_->echo_controller ||
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001324 private_submodules_->echo_cancellation->is_enabled())) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001325 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001326 capture_buffer, stream_delay_ms()));
1327 }
ivoc9f4a4a02016-10-28 05:39:16 -07001328
peahde65ddc2016-09-16 15:02:15 -07001329 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001330 if (config_.voice_detection.enabled) {
1331 private_submodules_->voice_detector->ProcessCaptureAudio(capture_buffer);
1332 capture_.stats.voice_detected =
1333 private_submodules_->voice_detector->stream_has_voice();
1334 } else {
1335 capture_.stats.voice_detected = absl::nullopt;
1336 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001337
peahbe615622016-02-13 16:40:47 -08001338 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001339 public_submodules_->gain_control->is_enabled() &&
1340 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001341 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001342 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1343 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001344 }
peahb8fbb542016-03-15 02:28:08 -07001345 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001346 capture_buffer,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001347 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001348
peah2ace3f92016-09-10 04:42:27 -07001349 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1350 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001351 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1352 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001353 }
1354
peah9e6a2902017-05-15 07:19:21 -07001355 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001356 RTC_DCHECK(private_submodules_->echo_detector);
1357 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001358 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1359 capture_buffer->num_frames()));
1360 }
1361
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001362 // TODO(aluebs): Investigate if the transient suppression placement should be
1363 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001364 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001365 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001366 private_submodules_->agc_manager.get()
1367 ? private_submodules_->agc_manager->voice_probability()
1368 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001369
peahdf3efa82015-11-28 12:35:15 -08001370 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001371 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1372 capture_buffer->num_channels(),
1373 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1374 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1375 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001376 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001377 }
1378
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001379 // Experimental APM sub-module that analyzes |capture_buffer|.
1380 if (private_submodules_->capture_analyzer) {
1381 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1382 }
1383
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001384 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001385 private_submodules_->gain_controller2->NotifyAnalogLevel(
1386 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001387 private_submodules_->gain_controller2->Process(capture_buffer);
1388 }
1389
Sam Zackrisson0beac582017-09-25 12:04:02 +02001390 if (private_submodules_->capture_post_processor) {
1391 private_submodules_->capture_post_processor->Process(capture_buffer);
1392 }
1393
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001394 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001395 public_submodules_->level_estimator->ProcessStream(capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001396 if (config_.level_estimation.enabled) {
1397 private_submodules_->output_level_estimator->ProcessStream(capture_buffer);
1398 capture_.stats.output_rms_dbfs =
1399 private_submodules_->output_level_estimator->RMS();
1400 } else {
1401 capture_.stats.output_rms_dbfs = absl::nullopt;
1402 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001403
peah1b08dc32016-12-20 13:45:58 -08001404 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1405 capture_buffer->channels_const()[0],
1406 capture_nonlocked_.capture_processing_format.num_frames()));
1407 if (log_rms) {
1408 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1409 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1410 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1411 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1412 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1413 }
1414
peahdf3efa82015-11-28 12:35:15 -08001415 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001416 return kNoError;
1417}
1418
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001419int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001420 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001421 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001422 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001423 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001424 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001425 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001426 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001427 };
1428 if (samples_per_channel != reverse_config.num_frames()) {
1429 return kBadDataLengthError;
1430 }
peahdf3efa82015-11-28 12:35:15 -08001431 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001432}
1433
peahde65ddc2016-09-16 15:02:15 -07001434int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1435 const StreamConfig& input_config,
1436 const StreamConfig& output_config,
1437 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001438 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001439 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001440 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001441 if (submodule_states_.RenderMultiBandProcessingActive() ||
1442 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001443 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1444 dest);
peah2ace3f92016-09-10 04:42:27 -07001445 } else if (formats_.api_format.reverse_input_stream() !=
1446 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001447 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1448 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001449 } else {
peahde65ddc2016-09-16 15:02:15 -07001450 CopyAudioIfNeeded(src, input_config.num_frames(),
1451 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001452 }
1453
1454 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001455}
1456
peahdf3efa82015-11-28 12:35:15 -08001457int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001458 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001459 const StreamConfig& input_config,
1460 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001461 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001462 return kNullPointerError;
1463 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001464
peahde65ddc2016-09-16 15:02:15 -07001465 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001466 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001467 }
1468
peahdf3efa82015-11-28 12:35:15 -08001469 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001470 processing_config.reverse_input_stream() = input_config;
1471 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001472
peahdf3efa82015-11-28 12:35:15 -08001473 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001474 RTC_DCHECK_EQ(input_config.num_frames(),
1475 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001476
aleloi868f32f2017-05-23 07:20:05 -07001477 if (aec_dump_) {
1478 const size_t channel_size =
1479 formats_.api_format.reverse_input_stream().num_frames();
1480 const size_t num_channels =
1481 formats_.api_format.reverse_input_stream().num_channels();
1482 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001483 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001484 }
peahdf3efa82015-11-28 12:35:15 -08001485 render_.render_audio->CopyFrom(src,
1486 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001487 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001488}
1489
1490int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001491 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001492 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001493 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001494 return kNullPointerError;
1495 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001496 // Must be a native rate.
1497 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1498 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001499 frame->sample_rate_hz_ != kSampleRate32kHz &&
1500 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001501 return kBadSampleRateError;
1502 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001503
Michael Graczyk86c6d332015-07-23 11:41:39 -07001504 if (frame->num_channels_ <= 0) {
1505 return kBadNumberChannelsError;
1506 }
1507
peahdf3efa82015-11-28 12:35:15 -08001508 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001509 processing_config.reverse_input_stream().set_sample_rate_hz(
1510 frame->sample_rate_hz_);
1511 processing_config.reverse_input_stream().set_num_channels(
1512 frame->num_channels_);
1513 processing_config.reverse_output_stream().set_sample_rate_hz(
1514 frame->sample_rate_hz_);
1515 processing_config.reverse_output_stream().set_num_channels(
1516 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001517
peahdf3efa82015-11-28 12:35:15 -08001518 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001519 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001520 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001521 return kBadDataLengthError;
1522 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001523
aleloi868f32f2017-05-23 07:20:05 -07001524 if (aec_dump_) {
1525 aec_dump_->WriteRenderStreamMessage(*frame);
1526 }
1527
peahdf3efa82015-11-28 12:35:15 -08001528 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001529 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001530 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001531 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1532 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001533 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001534}
niklase@google.com470e71d2011-07-07 08:21:25 +00001535
peahde65ddc2016-09-16 15:02:15 -07001536int AudioProcessingImpl::ProcessRenderStreamLocked() {
1537 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001538
Alex Loiko73ec0192018-05-15 10:52:28 +02001539 HandleRenderRuntimeSettings();
1540
Alex Loiko5825aa62017-12-18 16:02:40 +01001541 if (private_submodules_->render_pre_processor) {
1542 private_submodules_->render_pre_processor->Process(render_buffer);
1543 }
1544
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001545 QueueNonbandedRenderAudio(render_buffer);
1546
peah2ace3f92016-09-10 04:42:27 -07001547 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001548 SampleRateSupportsMultiBand(
1549 formats_.render_processing_format.sample_rate_hz())) {
1550 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001551 }
1552
peahce4d9152017-05-19 01:28:05 -07001553 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1554 QueueBandedRenderAudio(render_buffer);
1555 }
1556
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001557 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001558 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001559 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001560 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001561
peah2ace3f92016-09-10 04:42:27 -07001562 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001563 SampleRateSupportsMultiBand(
1564 formats_.render_processing_format.sample_rate_hz())) {
1565 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001566 }
1567
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001568 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001569}
1570
1571int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001572 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001573 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001574 capture_.was_stream_delay_set = true;
1575 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001576
niklase@google.com470e71d2011-07-07 08:21:25 +00001577 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001578 delay = 0;
1579 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001580 }
1581
1582 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1583 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001584 delay = 500;
1585 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001586 }
1587
peahdf3efa82015-11-28 12:35:15 -08001588 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001589 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001590}
1591
1592int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001593 // Used as callback from submodules, hence locking is not allowed.
1594 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001595}
1596
1597bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001598 // Used as callback from submodules, hence locking is not allowed.
1599 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001600}
1601
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001602void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001603 rtc::CritScope cs(&crit_capture_);
1604 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001605}
1606
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001607void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001608 rtc::CritScope cs(&crit_capture_);
1609 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001610}
1611
1612int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001613 rtc::CritScope cs(&crit_capture_);
1614 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001615}
1616
aleloi868f32f2017-05-23 07:20:05 -07001617void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1618 RTC_DCHECK(aec_dump);
1619 rtc::CritScope cs_render(&crit_render_);
1620 rtc::CritScope cs_capture(&crit_capture_);
1621
1622 // The previously attached AecDump will be destroyed with the
1623 // 'aec_dump' parameter, which is after locks are released.
1624 aec_dump_.swap(aec_dump);
1625 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001626 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001627}
1628
1629void AudioProcessingImpl::DetachAecDump() {
1630 // The d-tor of a task-queue based AecDump blocks until all pending
1631 // tasks are done. This construction avoids blocking while holding
1632 // the render and capture locks.
1633 std::unique_ptr<AecDump> aec_dump = nullptr;
1634 {
1635 rtc::CritScope cs_render(&crit_render_);
1636 rtc::CritScope cs_capture(&crit_capture_);
1637 aec_dump = std::move(aec_dump_);
1638 }
1639}
1640
Sam Zackrisson4d364492018-03-02 16:03:21 +01001641void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1642 std::unique_ptr<AudioGenerator> audio_generator) {
1643 // TODO(bugs.webrtc.org/8882) Stub.
1644 // Reset internal audio generator with audio_generator.
1645}
1646
1647void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1648 // TODO(bugs.webrtc.org/8882) Stub.
1649 // Delete audio generator, if one is attached.
1650}
1651
Ivo Creusen56d46092017-11-24 17:29:59 +01001652AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001653 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001654 rtc::CritScope cs_capture(&crit_capture_);
1655 if (!has_remote_tracks) {
1656 return capture_.stats;
1657 }
1658 AudioProcessingStats stats = capture_.stats;
1659 EchoCancellationImpl::Metrics metrics;
1660 if (private_submodules_->echo_controller) {
1661 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1662 stats.echo_return_loss = ec_metrics.echo_return_loss;
1663 stats.echo_return_loss_enhancement =
1664 ec_metrics.echo_return_loss_enhancement;
1665 stats.delay_ms = ec_metrics.delay_ms;
1666 } else if (private_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1667 Error::kNoError) {
1668 if (metrics.divergent_filter_fraction != -1.0f) {
1669 stats.divergent_filter_fraction =
1670 absl::optional<double>(metrics.divergent_filter_fraction);
1671 }
1672 if (metrics.echo_return_loss.instant != -100) {
1673 stats.echo_return_loss =
1674 absl::optional<double>(metrics.echo_return_loss.instant);
1675 }
1676 if (metrics.echo_return_loss_enhancement.instant != -100) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001677 stats.echo_return_loss_enhancement =
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001678 absl::optional<double>(metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001679 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001680 }
1681 if (config_.residual_echo_detector.enabled) {
1682 RTC_DCHECK(private_submodules_->echo_detector);
1683 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1684 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1685 stats.residual_echo_likelihood_recent_max =
1686 ed_metrics.echo_likelihood_recent_max;
1687 }
1688 int delay_median, delay_std;
1689 float fraction_poor_delays;
1690 if (private_submodules_->echo_cancellation->GetDelayMetrics(
1691 &delay_median, &delay_std, &fraction_poor_delays) ==
1692 Error::kNoError) {
1693 if (delay_median >= 0) {
1694 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001695 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001696 if (delay_std >= 0) {
1697 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001698 }
1699 }
1700 return stats;
1701}
1702
niklase@google.com470e71d2011-07-07 08:21:25 +00001703GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001704 if (constants_.use_experimental_agc) {
1705 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001706 }
peahbfa97112016-03-10 21:09:04 -08001707 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001708}
1709
niklase@google.com470e71d2011-07-07 08:21:25 +00001710LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001711 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001712}
1713
1714NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001715 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001716}
1717
1718VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001719 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001720}
1721
peah8271d042016-11-22 07:24:52 -08001722void AudioProcessingImpl::MutateConfig(
1723 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1724 rtc::CritScope cs_render(&crit_render_);
1725 rtc::CritScope cs_capture(&crit_capture_);
1726 mutator(&config_);
1727 ApplyConfig(config_);
1728}
1729
1730AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1731 rtc::CritScope cs_render(&crit_render_);
1732 rtc::CritScope cs_capture(&crit_capture_);
1733 return config_;
1734}
1735
peah2ace3f92016-09-10 04:42:27 -07001736bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1737 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001738 config_.high_pass_filter.enabled,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001739 private_submodules_->echo_cancellation->is_enabled(),
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001740 private_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001741 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001742 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001743 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001744 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001745 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001746 public_submodules_->voice_detection->is_enabled(),
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001747 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001748 public_submodules_->level_estimator->is_enabled(),
1749 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001750}
1751
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001752void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001753 if (capture_.transient_suppressor_enabled) {
1754 if (!public_submodules_->transient_suppressor.get()) {
1755 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001756 }
peahdf3efa82015-11-28 12:35:15 -08001757 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001758 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1759 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001760 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001761}
1762
peah8271d042016-11-22 07:24:52 -08001763void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001764 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001765 private_submodules_->low_cut_filter.reset(
1766 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1767 } else {
1768 private_submodules_->low_cut_filter.reset();
1769 }
1770}
alessiob3ec96df2017-05-22 06:57:06 -07001771
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001772void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001773 if (echo_control_factory_) {
1774 private_submodules_->echo_controller =
1775 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001776 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001777 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001778 }
1779}
peah8271d042016-11-22 07:24:52 -08001780
alessiob3ec96df2017-05-22 06:57:06 -07001781void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001782 if (config_.gain_controller2.enabled) {
1783 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001784 }
1785}
1786
Alex Loikob5c9a792018-04-16 16:31:22 +02001787void AudioProcessingImpl::InitializePreAmplifier() {
1788 if (config_.pre_amplifier.enabled) {
1789 private_submodules_->pre_amplifier.reset(
1790 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1791 } else {
1792 private_submodules_->pre_amplifier.reset();
1793 }
1794}
1795
ivoc9f4a4a02016-10-28 05:39:16 -07001796void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001797 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001798 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001799 proc_sample_rate_hz(), 1,
1800 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001801}
1802
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001803void AudioProcessingImpl::InitializeAnalyzer() {
1804 if (private_submodules_->capture_analyzer) {
1805 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1806 num_proc_channels());
1807 }
1808}
1809
Sam Zackrisson0beac582017-09-25 12:04:02 +02001810void AudioProcessingImpl::InitializePostProcessor() {
1811 if (private_submodules_->capture_post_processor) {
1812 private_submodules_->capture_post_processor->Initialize(
1813 proc_sample_rate_hz(), num_proc_channels());
1814 }
1815}
1816
Alex Loiko5825aa62017-12-18 16:02:40 +01001817void AudioProcessingImpl::InitializePreProcessor() {
1818 if (private_submodules_->render_pre_processor) {
1819 private_submodules_->render_pre_processor->Initialize(
1820 formats_.render_processing_format.sample_rate_hz(),
1821 formats_.render_processing_format.num_channels());
1822 }
1823}
1824
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001825void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001826 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001827
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001828 if (private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001829 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1830 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001831 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001832 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001833 capture_.stream_delay_jumps = 0;
1834 }
1835 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001836 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001837 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001838 }
1839
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001840 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001841 const int diff_stream_delay_ms =
1842 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1843 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1844 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001845 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1846 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001847 if (capture_.stream_delay_jumps == -1) {
1848 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001849 }
peahdf3efa82015-11-28 12:35:15 -08001850 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001851 }
peahdf3efa82015-11-28 12:35:15 -08001852 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001853
1854 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001855 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001856 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001857 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001858 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001859 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001860 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001861 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001862 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001863 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001864 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001865 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1866 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1867 100);
peahdf3efa82015-11-28 12:35:15 -08001868 if (capture_.aec_system_delay_jumps == -1) {
1869 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001870 }
peahdf3efa82015-11-28 12:35:15 -08001871 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001872 }
peahdf3efa82015-11-28 12:35:15 -08001873 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001874 }
1875}
1876
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001877void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001878 // Run in a single-threaded manner.
1879 rtc::CritScope cs_render(&crit_render_);
1880 rtc::CritScope cs_capture(&crit_capture_);
1881
1882 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001883 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001884 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001885 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001886 }
peahdf3efa82015-11-28 12:35:15 -08001887 capture_.stream_delay_jumps = -1;
1888 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001889
peahdf3efa82015-11-28 12:35:15 -08001890 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001891 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1892 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001893 }
peahdf3efa82015-11-28 12:35:15 -08001894 capture_.aec_system_delay_jumps = -1;
1895 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001896}
1897
aleloi868f32f2017-05-23 07:20:05 -07001898void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1899 if (!aec_dump_) {
1900 return;
1901 }
1902 std::string experiments_description =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001903 private_submodules_->echo_cancellation->GetExperimentsDescription();
aleloi868f32f2017-05-23 07:20:05 -07001904 // TODO(peah): Add semicolon-separated concatenations of experiment
1905 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001906 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1907 experiments_description += "AgcClippingLevelExperiment;";
1908 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001909 if (capture_nonlocked_.echo_controller_enabled) {
1910 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001911 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001912 if (config_.gain_controller2.enabled) {
1913 experiments_description += "GainController2;";
1914 }
aleloi868f32f2017-05-23 07:20:05 -07001915
1916 InternalAPMConfig apm_config;
1917
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001918 apm_config.aec_enabled = private_submodules_->echo_cancellation->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001919 apm_config.aec_delay_agnostic_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001920 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001921 apm_config.aec_drift_compensation_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001922 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001923 apm_config.aec_extended_filter_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001924 private_submodules_->echo_cancellation->is_extended_filter_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001925 apm_config.aec_suppression_level = static_cast<int>(
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001926 private_submodules_->echo_cancellation->suppression_level());
aleloi868f32f2017-05-23 07:20:05 -07001927
1928 apm_config.aecm_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001929 private_submodules_->echo_control_mobile->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001930 apm_config.aecm_comfort_noise_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001931 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1932 apm_config.aecm_routing_mode = static_cast<int>(
1933 private_submodules_->echo_control_mobile->routing_mode());
aleloi868f32f2017-05-23 07:20:05 -07001934
1935 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1936 apm_config.agc_mode =
1937 static_cast<int>(public_submodules_->gain_control->mode());
1938 apm_config.agc_limiter_enabled =
1939 public_submodules_->gain_control->is_limiter_enabled();
1940 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1941
1942 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1943
1944 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1945 apm_config.ns_level =
1946 static_cast<int>(public_submodules_->noise_suppression->level());
1947
1948 apm_config.transient_suppression_enabled =
1949 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001950 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001951 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1952 apm_config.pre_amplifier_fixed_gain_factor =
1953 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001954
1955 if (!forced && apm_config == apm_config_for_aec_dump_) {
1956 return;
1957 }
1958 aec_dump_->WriteConfig(apm_config);
1959 apm_config_for_aec_dump_ = apm_config;
1960}
1961
1962void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1963 const float* const* src) {
1964 RTC_DCHECK(aec_dump_);
1965 WriteAecDumpConfigMessage(false);
1966
1967 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1968 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1969 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001970 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001971 RecordAudioProcessingState();
1972}
1973
1974void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1975 const AudioFrame& capture_frame) {
1976 RTC_DCHECK(aec_dump_);
1977 WriteAecDumpConfigMessage(false);
1978
1979 aec_dump_->AddCaptureStreamInput(capture_frame);
1980 RecordAudioProcessingState();
1981}
1982
1983void AudioProcessingImpl::RecordProcessedCaptureStream(
1984 const float* const* processed_capture_stream) {
1985 RTC_DCHECK(aec_dump_);
1986
1987 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1988 const size_t num_channels =
1989 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001990 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1991 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001992 aec_dump_->WriteCaptureStreamMessage();
1993}
1994
1995void AudioProcessingImpl::RecordProcessedCaptureStream(
1996 const AudioFrame& processed_capture_frame) {
1997 RTC_DCHECK(aec_dump_);
1998
1999 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2000 aec_dump_->WriteCaptureStreamMessage();
2001}
2002
2003void AudioProcessingImpl::RecordAudioProcessingState() {
2004 RTC_DCHECK(aec_dump_);
2005 AecDump::AudioProcessingState audio_proc_state;
2006 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2007 audio_proc_state.drift =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002008 private_submodules_->echo_cancellation->stream_drift_samples();
aleloi868f32f2017-05-23 07:20:05 -07002009 audio_proc_state.level = gain_control()->stream_analog_level();
2010 audio_proc_state.keypress = capture_.key_pressed;
2011 aec_dump_->AddAudioProcessingState(audio_proc_state);
2012}
2013
kwiberg83ffe452016-08-29 14:46:07 -07002014AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002015 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002016 : aec_system_delay_jumps(-1),
2017 delay_offset_ms(0),
2018 was_stream_delay_set(false),
2019 last_stream_delay_ms(0),
2020 last_aec_system_delay_ms(0),
2021 stream_delay_jumps(-1),
2022 output_will_be_muted(false),
2023 key_pressed(false),
2024 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002025 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002026 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002027 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002028 prev_analog_mic_level(-1),
2029 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002030
2031AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2032
2033AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2034
2035AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2036
niklase@google.com470e71d2011-07-07 08:21:25 +00002037} // namespace webrtc