blob: 5f0d676511275d2bdf84a9b4f1beca8c5f057d10 [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_() {
peahdf3efa82015-11-28 12:35:15 -0800390 {
391 rtc::CritScope cs_render(&crit_render_);
392 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000393
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200394 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000395 capture_nonlocked_.echo_controller_enabled =
396 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200397
peahbfa97112016-03-10 21:09:04 -0800398 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200399 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800400 public_submodules_->level_estimator.reset(
401 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800402 public_submodules_->noise_suppression.reset(
403 new NoiseSuppressionImpl(&crit_capture_));
Sam Zackrisson23513132019-01-11 15:10:32 +0100404 public_submodules_->noise_suppression_proxy.reset(new NoiseSuppressionProxy(
405 this, public_submodules_->noise_suppression.get()));
solenberga29386c2015-12-16 03:31:12 -0800406 public_submodules_->voice_detection.reset(
407 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800408 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800409 new GainControlForExperimentalAgc(
410 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100411
412 // If no echo detector is injected, use the ResidualEchoDetector.
413 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200414 private_submodules_->echo_detector =
415 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100416 }
peahca4cac72016-06-29 15:26:12 -0700417
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100418 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
419 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200420 // TODO(alessiob): Move the injected gain controller once injection is
421 // implemented.
422 private_submodules_->gain_controller2.reset(new GainController2());
423
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200424 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
425 << !!private_submodules_->capture_analyzer
426 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100427 << !!private_submodules_->capture_post_processor
428 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100429 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800430 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000431
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000432 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000433}
434
435AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800436 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800437 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800438 private_submodules_->agc_manager.reset();
439 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800440 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000441}
442
niklase@google.com470e71d2011-07-07 08:21:25 +0000443int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800444 // Run in a single-threaded manner during initialization.
445 rtc::CritScope cs_render(&crit_render_);
446 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000447 return InitializeLocked();
448}
449
peahde65ddc2016-09-16 15:02:15 -0700450int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
451 int capture_output_sample_rate_hz,
452 int render_input_sample_rate_hz,
453 ChannelLayout capture_input_layout,
454 ChannelLayout capture_output_layout,
455 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700456 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700457 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
458 LayoutHasKeyboard(capture_input_layout)},
459 {capture_output_sample_rate_hz,
460 ChannelsFromLayout(capture_output_layout),
461 LayoutHasKeyboard(capture_output_layout)},
462 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
463 LayoutHasKeyboard(render_input_layout)},
464 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
465 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700466
467 return Initialize(processing_config);
468}
469
470int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800471 // Run in a single-threaded manner during initialization.
472 rtc::CritScope cs_render(&crit_render_);
473 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700474 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000475}
476
peahdf3efa82015-11-28 12:35:15 -0800477int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800478 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700479 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800480}
481
peahdf3efa82015-11-28 12:35:15 -0800482int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700483 const ProcessingConfig& processing_config,
484 bool force_initialization) {
485 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800486}
487
peah192164e2015-11-17 02:16:45 -0800488// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800489// their current values (needs to be called while holding the crit_render_lock).
490int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700491 const ProcessingConfig& processing_config,
492 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800493 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700494 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800495 return kNoError;
496 }
peahdf3efa82015-11-28 12:35:15 -0800497
498 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800499 return InitializeLocked(processing_config);
500}
501
niklase@google.com470e71d2011-07-07 08:21:25 +0000502int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200503 UpdateActiveSubmoduleStates();
504
peahde65ddc2016-09-16 15:02:15 -0700505 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800506 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700507 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800508 : formats_.api_format.reverse_output_stream().num_frames();
509 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
510 render_.render_audio.reset(new AudioBuffer(
511 formats_.api_format.reverse_input_stream().num_frames(),
512 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700513 formats_.render_processing_format.num_frames(),
514 formats_.render_processing_format.num_channels(),
515 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700516 if (formats_.api_format.reverse_input_stream() !=
517 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800518 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800519 formats_.api_format.reverse_input_stream().num_channels(),
520 formats_.api_format.reverse_input_stream().num_frames(),
521 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800522 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700523 } else {
peahdf3efa82015-11-28 12:35:15 -0800524 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700525 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700526 } else {
peahdf3efa82015-11-28 12:35:15 -0800527 render_.render_audio.reset(nullptr);
528 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700529 }
peahce4d9152017-05-19 01:28:05 -0700530
peahdf3efa82015-11-28 12:35:15 -0800531 capture_.capture_audio.reset(
532 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
533 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700534 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200535 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800536 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000537
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100538 private_submodules_->echo_cancellation->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700539 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
540 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700541 AllocateRenderQueue();
542
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100543 int success = private_submodules_->echo_cancellation->enable_metrics(true);
ivoc3e9a5372016-10-28 07:55:33 -0700544 RTC_DCHECK_EQ(0, success);
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100545 success = private_submodules_->echo_cancellation->enable_delay_logging(true);
ivoc3e9a5372016-10-28 07:55:33 -0700546 RTC_DCHECK_EQ(0, success);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100547 private_submodules_->echo_control_mobile->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700548 proc_split_sample_rate_hz(), num_reverse_channels(),
549 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700550
551 public_submodules_->gain_control->Initialize(num_proc_channels(),
552 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700553 if (constants_.use_experimental_agc) {
554 if (!private_submodules_->agc_manager.get()) {
555 private_submodules_->agc_manager.reset(new AgcManagerDirect(
556 public_submodules_->gain_control.get(),
557 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200558 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
559 constants_.use_experimental_agc_agc2_level_estimation,
560 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700561 }
562 private_submodules_->agc_manager->Initialize();
563 private_submodules_->agc_manager->SetCaptureMuted(
564 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700565 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700566 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200567 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800568 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700569 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
570 proc_sample_rate_hz());
571 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100572 if (private_submodules_->voice_detector) {
573 private_submodules_->voice_detector->Initialize(
574 proc_split_sample_rate_hz());
575 }
peahde65ddc2016-09-16 15:02:15 -0700576 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700577 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200578 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700579 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200580 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200581 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100582 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800583
aleloi868f32f2017-05-23 07:20:05 -0700584 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200585 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700586 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000587 return kNoError;
588}
589
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200591 UpdateActiveSubmoduleStates();
592
Michael Graczyk86c6d332015-07-23 11:41:39 -0700593 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700594 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
595 return kBadSampleRateError;
596 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000597 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700598
Peter Kasting69558702016-01-12 16:26:35 -0800599 const size_t num_in_channels = config.input_stream().num_channels();
600 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700601
602 // Need at least one input channel.
603 // Need either one output channel or as many outputs as there are inputs.
604 if (num_in_channels == 0 ||
605 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700606 return kBadNumberChannelsError;
607 }
608
peahdf3efa82015-11-28 12:35:15 -0800609 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000610
peahde65ddc2016-09-16 15:02:15 -0700611 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700612 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700613 formats_.api_format.output_stream().sample_rate_hz()),
614 submodule_states_.CaptureMultiBandSubModulesActive() ||
615 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000616
peahde65ddc2016-09-16 15:02:15 -0700617 capture_nonlocked_.capture_processing_format =
618 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700619
peah2ce640f2017-04-07 03:57:48 -0700620 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200621 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700622 render_processing_rate = FindNativeProcessRateToUse(
623 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
624 formats_.api_format.reverse_output_stream().sample_rate_hz()),
625 submodule_states_.CaptureMultiBandSubModulesActive() ||
626 submodule_states_.RenderMultiBandSubModulesActive());
627 } else {
628 render_processing_rate = capture_processing_rate;
629 }
630
aluebseb3603b2016-04-20 15:27:58 -0700631 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
632 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700633 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200634 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700635 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
636 ? kSampleRate32kHz
637 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700638 }
peah2ce640f2017-04-07 03:57:48 -0700639
peahde65ddc2016-09-16 15:02:15 -0700640 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700641 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700642 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
643 kSampleRate8kHz) {
644 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000645 } else {
peahde65ddc2016-09-16 15:02:15 -0700646 render_processing_rate =
647 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000648 }
649
peahde65ddc2016-09-16 15:02:15 -0700650 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000651 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700652 if (submodule_states_.RenderMultiBandSubModulesActive()) {
653 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
654 } else {
655 formats_.render_processing_format = StreamConfig(
656 formats_.api_format.reverse_input_stream().sample_rate_hz(),
657 formats_.api_format.reverse_input_stream().num_channels());
658 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000659
peahde65ddc2016-09-16 15:02:15 -0700660 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
661 kSampleRate32kHz ||
662 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
663 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800664 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000665 } else {
peahdf3efa82015-11-28 12:35:15 -0800666 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700667 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000668 }
669
670 return InitializeLocked();
671}
672
peah88ac8532016-09-12 16:47:25 -0700673void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700674 // Run in a single-threaded manner when applying the settings.
675 rtc::CritScope cs_render(&crit_render_);
676 rtc::CritScope cs_capture(&crit_capture_);
677
Yves Gerey499bc6c2018-10-10 18:29:07 +0200678 config_ = config;
679
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100680 private_submodules_->echo_cancellation->Enable(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200681 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100682 private_submodules_->echo_control_mobile->Enable(
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200683 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200684
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100685 private_submodules_->echo_cancellation->set_suppression_level(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200686 config.echo_canceller.legacy_moderate_suppression_level
sazabe490b22018-10-03 17:03:13 +0200687 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
688 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200689
Sam Zackrisson23513132019-01-11 15:10:32 +0100690 public_submodules_->noise_suppression->Enable(
691 config.noise_suppression.enabled);
692 public_submodules_->noise_suppression->set_level(
693 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
694
peah8271d042016-11-22 07:24:52 -0800695 InitializeLowCutFilter();
696
Mirko Bonadei675513b2017-11-09 11:09:25 +0100697 RTC_LOG(LS_INFO) << "Highpass filter activated: "
698 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800699
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100700 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700701 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100702 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
703 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100704 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100705 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700706 config_.gain_controller2 = AudioProcessing::Config::GainController2();
707 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200708 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200709 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200710 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100711 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
712 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200713 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
714 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100715
716 if (config_.level_estimation.enabled &&
717 !private_submodules_->output_level_estimator) {
718 private_submodules_->output_level_estimator.reset(
719 new LevelEstimatorImpl(&crit_capture_));
720 private_submodules_->output_level_estimator->Enable(true);
721 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100722
723 if (config_.voice_detection.enabled && !private_submodules_->voice_detector) {
724 private_submodules_->voice_detector.reset(
725 new VoiceDetectionImpl(&crit_capture_));
726 private_submodules_->voice_detector->Enable(true);
727 private_submodules_->voice_detector->set_likelihood(
728 VoiceDetection::kVeryLowLikelihood);
729 private_submodules_->voice_detector->Initialize(
730 proc_split_sample_rate_hz());
731 }
peah88ac8532016-09-12 16:47:25 -0700732}
733
734void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800735 // Run in a single-threaded manner when setting the extra options.
736 rtc::CritScope cs_render(&crit_render_);
737 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000738
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100739 private_submodules_->echo_cancellation->SetExtraOptions(config);
peahb624d8c2016-03-05 03:01:14 -0800740
peahdf3efa82015-11-28 12:35:15 -0800741 if (capture_.transient_suppressor_enabled !=
742 config.Get<ExperimentalNs>().enabled) {
743 capture_.transient_suppressor_enabled =
744 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000745 InitializeTransient();
746 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000747}
748
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000749int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800750 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700751 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000752}
753
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000754int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800755 // Used as callback from submodules, hence locking is not allowed.
756 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000757}
758
Peter Kasting69558702016-01-12 16:26:35 -0800759size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800760 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700761 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000762}
763
Peter Kasting69558702016-01-12 16:26:35 -0800764size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800765 // Used as callback from submodules, hence locking is not allowed.
766 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000767}
768
Peter Kasting69558702016-01-12 16:26:35 -0800769size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800770 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200771 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800772}
773
Peter Kasting69558702016-01-12 16:26:35 -0800774size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800775 // Used as callback from submodules, hence locking is not allowed.
776 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000777}
778
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000779void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800780 rtc::CritScope cs(&crit_capture_);
781 capture_.output_will_be_muted = muted;
782 if (private_submodules_->agc_manager.get()) {
783 private_submodules_->agc_manager->SetCaptureMuted(
784 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000785 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000786}
787
Alessio Bazzicac054e782018-04-16 12:10:09 +0200788void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200789 switch (setting.type()) {
790 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
791 render_runtime_settings_enqueuer_.Enqueue(setting);
792 return;
793 case RuntimeSetting::Type::kNotSpecified:
794 RTC_NOTREACHED();
795 return;
796 case RuntimeSetting::Type::kCapturePreGain:
797 capture_runtime_settings_enqueuer_.Enqueue(setting);
798 return;
799 }
800 // The language allows the enum to have a non-enumerator
801 // value. Check that this doesn't happen.
802 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200803}
804
805AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
806 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200807 : runtime_settings_(*runtime_settings) {
808 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200809}
810
811AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
812 default;
813
814void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
815 RuntimeSetting setting) {
816 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200817 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200818 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200819 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200820 RTC_LOG(LS_ERROR)
821 << "The runtime settings queue is full. Oldest setting discarded.";
822 }
823 if (remaining_attempts == 0)
824 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
825}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000826
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000827int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700828 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000829 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000830 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000831 int output_sample_rate_hz,
832 ChannelLayout output_layout,
833 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800834 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800835 StreamConfig input_stream;
836 StreamConfig output_stream;
837 {
838 // Access the formats_.api_format.input_stream beneath the capture lock.
839 // The lock must be released as it is later required in the call
840 // to ProcessStream(,,,);
841 rtc::CritScope cs(&crit_capture_);
842 input_stream = formats_.api_format.input_stream();
843 output_stream = formats_.api_format.output_stream();
844 }
845
Michael Graczyk86c6d332015-07-23 11:41:39 -0700846 input_stream.set_sample_rate_hz(input_sample_rate_hz);
847 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
848 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700849 output_stream.set_sample_rate_hz(output_sample_rate_hz);
850 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
851 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
852
853 if (samples_per_channel != input_stream.num_frames()) {
854 return kBadDataLengthError;
855 }
856 return ProcessStream(src, input_stream, output_stream, dest);
857}
858
859int AudioProcessingImpl::ProcessStream(const float* const* src,
860 const StreamConfig& input_config,
861 const StreamConfig& output_config,
862 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800863 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800864 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700865 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800866 {
867 // Acquire the capture lock in order to safely call the function
868 // that retrieves the render side data. This function accesses apm
869 // getters that need the capture lock held when being called.
870 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700871 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800872
873 if (!src || !dest) {
874 return kNullPointerError;
875 }
876
877 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700878 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000879 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000880
Michael Graczyk86c6d332015-07-23 11:41:39 -0700881 processing_config.input_stream() = input_config;
882 processing_config.output_stream() = output_config;
883
peahdf3efa82015-11-28 12:35:15 -0800884 {
885 // Do conditional reinitialization.
886 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700887 RETURN_ON_ERR(
888 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800889 }
890 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700891 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
892 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000893
aleloi868f32f2017-05-23 07:20:05 -0700894 if (aec_dump_) {
895 RecordUnprocessedCaptureStream(src);
896 }
897
peahdf3efa82015-11-28 12:35:15 -0800898 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700899 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800900 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000901
aleloi868f32f2017-05-23 07:20:05 -0700902 if (aec_dump_) {
903 RecordProcessedCaptureStream(dest);
904 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000905 return kNoError;
906}
907
Alex Loiko73ec0192018-05-15 10:52:28 +0200908void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200909 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200910 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200911 if (aec_dump_) {
912 aec_dump_->WriteRuntimeSetting(setting);
913 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200914 switch (setting.type()) {
915 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200916 if (config_.pre_amplifier.enabled) {
917 float value;
918 setting.GetFloat(&value);
919 private_submodules_->pre_amplifier->SetGainFactor(value);
920 }
921 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200922 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200923 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
924 RTC_NOTREACHED();
925 break;
926 case RuntimeSetting::Type::kNotSpecified:
927 RTC_NOTREACHED();
928 break;
929 }
930 }
931}
932
933void AudioProcessingImpl::HandleRenderRuntimeSettings() {
934 RuntimeSetting setting;
935 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200936 if (aec_dump_) {
937 aec_dump_->WriteRuntimeSetting(setting);
938 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200939 switch (setting.type()) {
940 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
941 if (private_submodules_->render_pre_processor) {
942 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
943 }
944 break;
945 case RuntimeSetting::Type::kCapturePreGain:
946 RTC_NOTREACHED();
947 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200948 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200949 RTC_NOTREACHED();
950 break;
951 }
952 }
953}
954
peah9e6a2902017-05-15 07:19:21 -0700955void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700956 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
957 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700958 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700959
kwibergaf476c72016-11-28 15:21:39 -0800960 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700961
962 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700963 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700964 // The data queue is full and needs to be emptied.
965 EmptyQueuedRenderAudio();
966
967 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700968 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700969 RTC_DCHECK(result);
970 }
971
972 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
973 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700974 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700975
976 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700977 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700978 // The data queue is full and needs to be emptied.
979 EmptyQueuedRenderAudio();
980
981 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700982 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700983 RTC_DCHECK(result);
984 }
peah701d6282016-10-25 05:42:20 -0700985
986 if (!constants_.use_experimental_agc) {
987 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
988 // Insert the samples into the queue.
989 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
990 // The data queue is full and needs to be emptied.
991 EmptyQueuedRenderAudio();
992
993 // Retry the insert (should always work).
994 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
995 RTC_DCHECK(result);
996 }
997 }
peah9e6a2902017-05-15 07:19:21 -0700998}
ivoc9f4a4a02016-10-28 05:39:16 -0700999
peah9e6a2902017-05-15 07:19:21 -07001000void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001001 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1002
1003 // Insert the samples into the queue.
1004 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1005 // The data queue is full and needs to be emptied.
1006 EmptyQueuedRenderAudio();
1007
1008 // Retry the insert (should always work).
1009 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1010 RTC_DCHECK(result);
1011 }
peah764e3642016-10-22 05:04:30 -07001012}
1013
1014void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001015 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -07001016 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001017 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -07001018 EchoCancellationImpl::NumCancellersRequired(
1019 num_output_channels(), num_reverse_channels()));
1020
peah701d6282016-10-25 05:42:20 -07001021 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001022 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001023 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001024 EchoControlMobileImpl::NumCancellersRequired(
1025 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001026
peah701d6282016-10-25 05:42:20 -07001027 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001028 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001029
ivoc9f4a4a02016-10-28 05:39:16 -07001030 const size_t new_red_render_queue_element_max_size =
1031 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1032
peaha0624602016-10-25 04:45:24 -07001033 // Reallocate the queues if the queue item sizes are too small to fit the
1034 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001035 if (aec_render_queue_element_max_size_ <
1036 new_aec_render_queue_element_max_size) {
1037 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001038
peaha0624602016-10-25 04:45:24 -07001039 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001040 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001041
peah701d6282016-10-25 05:42:20 -07001042 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001043 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1044 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001045 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001046 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001047
peah701d6282016-10-25 05:42:20 -07001048 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1049 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001050 } else {
peah701d6282016-10-25 05:42:20 -07001051 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001052 }
1053
peah701d6282016-10-25 05:42:20 -07001054 if (aecm_render_queue_element_max_size_ <
1055 new_aecm_render_queue_element_max_size) {
1056 aecm_render_queue_element_max_size_ =
1057 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001058
1059 std::vector<int16_t> template_queue_element(
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_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001063 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1064 kMaxNumFramesToBuffer, template_queue_element,
1065 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001066 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001067
peah701d6282016-10-25 05:42:20 -07001068 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1069 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001070 } else {
peah701d6282016-10-25 05:42:20 -07001071 aecm_render_signal_queue_->Clear();
1072 }
1073
1074 if (agc_render_queue_element_max_size_ <
1075 new_agc_render_queue_element_max_size) {
1076 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1077
1078 std::vector<int16_t> template_queue_element(
1079 agc_render_queue_element_max_size_);
1080
1081 agc_render_signal_queue_.reset(
1082 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1083 kMaxNumFramesToBuffer, template_queue_element,
1084 RenderQueueItemVerifier<int16_t>(
1085 agc_render_queue_element_max_size_)));
1086
1087 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1088 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1089 } else {
1090 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001091 }
ivoc9f4a4a02016-10-28 05:39:16 -07001092
1093 if (red_render_queue_element_max_size_ <
1094 new_red_render_queue_element_max_size) {
1095 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1096
1097 std::vector<float> template_queue_element(
1098 red_render_queue_element_max_size_);
1099
1100 red_render_signal_queue_.reset(
1101 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1102 kMaxNumFramesToBuffer, template_queue_element,
1103 RenderQueueItemVerifier<float>(
1104 red_render_queue_element_max_size_)));
1105
1106 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1107 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1108 } else {
1109 red_render_signal_queue_->Clear();
1110 }
peah764e3642016-10-22 05:04:30 -07001111}
1112
1113void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1114 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001115 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001116 private_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001117 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001118 }
1119
peah701d6282016-10-25 05:42:20 -07001120 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001121 private_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001122 aecm_capture_queue_buffer_);
1123 }
1124
1125 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1126 public_submodules_->gain_control->ProcessRenderAudio(
1127 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001128 }
ivoc9f4a4a02016-10-28 05:39:16 -07001129
1130 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001131 RTC_DCHECK(private_submodules_->echo_detector);
1132 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001133 red_capture_queue_buffer_);
1134 }
peah764e3642016-10-22 05:04:30 -07001135}
1136
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001137int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001138 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001139 {
1140 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001141 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001142 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001143 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001144 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001145 }
peahfa6228e2015-11-16 16:27:42 -08001146
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001147 if (!frame) {
1148 return kNullPointerError;
1149 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001150 // Must be a native rate.
1151 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1152 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001153 frame->sample_rate_hz_ != kSampleRate32kHz &&
1154 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001155 return kBadSampleRateError;
1156 }
peah192164e2015-11-17 02:16:45 -08001157
peahdf3efa82015-11-28 12:35:15 -08001158 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001159 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001160 {
1161 // Aquire lock for the access of api_format.
1162 // The lock is released immediately due to the conditional
1163 // reinitialization.
1164 rtc::CritScope cs_capture(&crit_capture_);
1165 // TODO(ajm): The input and output rates and channels are currently
1166 // constrained to be identical in the int16 interface.
1167 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001168
1169 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001170 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001171 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1172 processing_config.input_stream().set_num_channels(frame->num_channels_);
1173 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1174 processing_config.output_stream().set_num_channels(frame->num_channels_);
1175
peahdf3efa82015-11-28 12:35:15 -08001176 {
1177 // Do conditional reinitialization.
1178 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001179 RETURN_ON_ERR(
1180 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001181 }
1182 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001183 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001184 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001185 return kBadDataLengthError;
1186 }
1187
aleloi868f32f2017-05-23 07:20:05 -07001188 if (aec_dump_) {
1189 RecordUnprocessedCaptureStream(*frame);
1190 }
1191
peahdf3efa82015-11-28 12:35:15 -08001192 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001193 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001194 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001195 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1196 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001197
aleloi868f32f2017-05-23 07:20:05 -07001198 if (aec_dump_) {
1199 RecordProcessedCaptureStream(*frame);
1200 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001201
1202 return kNoError;
1203}
1204
peahde65ddc2016-09-16 15:02:15 -07001205int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001206 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001207
peahb58a1582016-03-15 09:34:24 -07001208 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001209 // TODO(peah): Simplify once the public API Enable functions for these
1210 // are moved to APM.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001211 RTC_DCHECK(!(private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001212 private_submodules_->echo_control_mobile->is_enabled()));
peahb58a1582016-03-15 09:34:24 -07001213
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001214 MaybeUpdateHistograms();
1215
peahde65ddc2016-09-16 15:02:15 -07001216 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001217
Alex Loikob5c9a792018-04-16 16:31:22 +02001218 if (private_submodules_->pre_amplifier) {
1219 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1220 capture_buffer->channels_f(), capture_buffer->num_channels(),
1221 capture_buffer->num_frames()));
1222 }
1223
peah1b08dc32016-12-20 13:45:58 -08001224 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001225 capture_buffer->channels_const()[0],
1226 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001227 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1228 if (log_rms) {
1229 capture_rms_interval_counter_ = 0;
1230 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001231 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1232 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1233 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1234 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001235 }
1236
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001237 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001238 // Detect and flag any change in the analog gain.
1239 int analog_mic_level = gain_control()->stream_analog_level();
1240 capture_.echo_path_gain_change =
1241 capture_.prev_analog_mic_level != analog_mic_level &&
1242 capture_.prev_analog_mic_level != -1;
1243 capture_.prev_analog_mic_level = analog_mic_level;
1244
Per Åhgrend2650d12018-10-02 17:00:59 +02001245 // Detect and flag any change in the pre-amplifier gain.
1246 if (private_submodules_->pre_amplifier) {
1247 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1248 capture_.echo_path_gain_change =
1249 capture_.echo_path_gain_change ||
1250 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001251 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001252 capture_.prev_pre_amp_gain = pre_amp_gain;
1253 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001254 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001255 }
1256
peahbe615622016-02-13 16:40:47 -08001257 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001258 public_submodules_->gain_control->is_enabled()) {
1259 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001260 capture_buffer->channels()[0], capture_buffer->num_channels(),
1261 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001262
1263 if (constants_.use_experimental_agc_process_before_aec) {
1264 private_submodules_->agc_manager->Process(
1265 capture_buffer->channels()[0],
1266 capture_nonlocked_.capture_processing_format.num_frames(),
1267 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1268 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001269 }
1270
peah2ace3f92016-09-10 04:42:27 -07001271 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1272 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001273 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1274 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001275 }
1276
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001277 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001278 // Force down-mixing of the number of channels after the detection of
1279 // capture signal saturation.
1280 // TODO(peah): Look into ensuring that this kind of tampering with the
1281 // AudioBuffer functionality should not be needed.
1282 capture_buffer->set_num_channels(1);
1283 }
1284
peahe0eae3c2016-12-14 01:16:23 -08001285 // TODO(peah): Move the AEC3 low-cut filter to this place.
1286 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001287 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001288 private_submodules_->low_cut_filter->Process(capture_buffer);
1289 }
peahde65ddc2016-09-16 15:02:15 -07001290 RETURN_ON_ERR(
1291 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1292 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001293
1294 // Ensure that the stream delay was set before the call to the
1295 // AEC ProcessCaptureAudio function.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001296 if (private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001297 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001298 return AudioProcessing::kStreamParameterNotSetError;
1299 }
1300
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001301 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001302 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1303
Per Åhgrend0fa8202018-04-18 09:35:13 +02001304 if (was_stream_delay_set()) {
1305 private_submodules_->echo_controller->SetAudioBufferDelay(
1306 stream_delay_ms());
1307 }
1308
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001309 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001310 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001311 } else {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001312 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
peah61202ac2017-02-06 03:39:42 -08001313 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001314 }
1315
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001316 if (private_submodules_->echo_control_mobile->is_enabled() &&
peahdf3efa82015-11-28 12:35:15 -08001317 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001318 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001319 }
peahde65ddc2016-09-16 15:02:15 -07001320 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001321
1322 // Ensure that the stream delay was set before the call to the
1323 // AECM ProcessCaptureAudio function.
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001324 if (private_submodules_->echo_control_mobile->is_enabled() &&
peah253534d2016-03-15 04:32:28 -07001325 !was_stream_delay_set()) {
1326 return AudioProcessing::kStreamParameterNotSetError;
1327 }
1328
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001329 if (!(private_submodules_->echo_controller ||
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001330 private_submodules_->echo_cancellation->is_enabled())) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001331 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001332 capture_buffer, stream_delay_ms()));
1333 }
ivoc9f4a4a02016-10-28 05:39:16 -07001334
peahde65ddc2016-09-16 15:02:15 -07001335 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001336 if (config_.voice_detection.enabled) {
1337 private_submodules_->voice_detector->ProcessCaptureAudio(capture_buffer);
1338 capture_.stats.voice_detected =
1339 private_submodules_->voice_detector->stream_has_voice();
1340 } else {
1341 capture_.stats.voice_detected = absl::nullopt;
1342 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001343
peahbe615622016-02-13 16:40:47 -08001344 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001345 public_submodules_->gain_control->is_enabled() &&
1346 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001347 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001348 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1349 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001350 }
peahb8fbb542016-03-15 02:28:08 -07001351 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001352 capture_buffer,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001353 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001354
peah2ace3f92016-09-10 04:42:27 -07001355 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1356 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001357 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1358 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001359 }
1360
peah9e6a2902017-05-15 07:19:21 -07001361 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001362 RTC_DCHECK(private_submodules_->echo_detector);
1363 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001364 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1365 capture_buffer->num_frames()));
1366 }
1367
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001368 // TODO(aluebs): Investigate if the transient suppression placement should be
1369 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001370 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001371 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001372 private_submodules_->agc_manager.get()
1373 ? private_submodules_->agc_manager->voice_probability()
1374 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001375
peahdf3efa82015-11-28 12:35:15 -08001376 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001377 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1378 capture_buffer->num_channels(),
1379 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1380 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1381 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001382 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001383 }
1384
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001385 // Experimental APM sub-module that analyzes |capture_buffer|.
1386 if (private_submodules_->capture_analyzer) {
1387 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1388 }
1389
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001390 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001391 private_submodules_->gain_controller2->NotifyAnalogLevel(
1392 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001393 private_submodules_->gain_controller2->Process(capture_buffer);
1394 }
1395
Sam Zackrisson0beac582017-09-25 12:04:02 +02001396 if (private_submodules_->capture_post_processor) {
1397 private_submodules_->capture_post_processor->Process(capture_buffer);
1398 }
1399
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001400 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001401 public_submodules_->level_estimator->ProcessStream(capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001402 if (config_.level_estimation.enabled) {
1403 private_submodules_->output_level_estimator->ProcessStream(capture_buffer);
1404 capture_.stats.output_rms_dbfs =
1405 private_submodules_->output_level_estimator->RMS();
1406 } else {
1407 capture_.stats.output_rms_dbfs = absl::nullopt;
1408 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001409
peah1b08dc32016-12-20 13:45:58 -08001410 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1411 capture_buffer->channels_const()[0],
1412 capture_nonlocked_.capture_processing_format.num_frames()));
1413 if (log_rms) {
1414 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1415 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1416 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1417 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1418 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1419 }
1420
peahdf3efa82015-11-28 12:35:15 -08001421 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001422 return kNoError;
1423}
1424
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001425int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001426 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001427 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001428 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001429 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001430 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001431 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001432 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001433 };
1434 if (samples_per_channel != reverse_config.num_frames()) {
1435 return kBadDataLengthError;
1436 }
peahdf3efa82015-11-28 12:35:15 -08001437 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001438}
1439
peahde65ddc2016-09-16 15:02:15 -07001440int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1441 const StreamConfig& input_config,
1442 const StreamConfig& output_config,
1443 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001444 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001445 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001446 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001447 if (submodule_states_.RenderMultiBandProcessingActive() ||
1448 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001449 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1450 dest);
peah2ace3f92016-09-10 04:42:27 -07001451 } else if (formats_.api_format.reverse_input_stream() !=
1452 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001453 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1454 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001455 } else {
peahde65ddc2016-09-16 15:02:15 -07001456 CopyAudioIfNeeded(src, input_config.num_frames(),
1457 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001458 }
1459
1460 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001461}
1462
peahdf3efa82015-11-28 12:35:15 -08001463int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001464 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001465 const StreamConfig& input_config,
1466 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001467 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001468 return kNullPointerError;
1469 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001470
peahde65ddc2016-09-16 15:02:15 -07001471 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001472 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001473 }
1474
peahdf3efa82015-11-28 12:35:15 -08001475 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001476 processing_config.reverse_input_stream() = input_config;
1477 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001478
peahdf3efa82015-11-28 12:35:15 -08001479 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001480 RTC_DCHECK_EQ(input_config.num_frames(),
1481 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001482
aleloi868f32f2017-05-23 07:20:05 -07001483 if (aec_dump_) {
1484 const size_t channel_size =
1485 formats_.api_format.reverse_input_stream().num_frames();
1486 const size_t num_channels =
1487 formats_.api_format.reverse_input_stream().num_channels();
1488 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001489 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001490 }
peahdf3efa82015-11-28 12:35:15 -08001491 render_.render_audio->CopyFrom(src,
1492 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001493 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001494}
1495
1496int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001497 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001498 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001499 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001500 return kNullPointerError;
1501 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001502 // Must be a native rate.
1503 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1504 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001505 frame->sample_rate_hz_ != kSampleRate32kHz &&
1506 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001507 return kBadSampleRateError;
1508 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001509
Michael Graczyk86c6d332015-07-23 11:41:39 -07001510 if (frame->num_channels_ <= 0) {
1511 return kBadNumberChannelsError;
1512 }
1513
peahdf3efa82015-11-28 12:35:15 -08001514 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001515 processing_config.reverse_input_stream().set_sample_rate_hz(
1516 frame->sample_rate_hz_);
1517 processing_config.reverse_input_stream().set_num_channels(
1518 frame->num_channels_);
1519 processing_config.reverse_output_stream().set_sample_rate_hz(
1520 frame->sample_rate_hz_);
1521 processing_config.reverse_output_stream().set_num_channels(
1522 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001523
peahdf3efa82015-11-28 12:35:15 -08001524 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001525 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001526 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001527 return kBadDataLengthError;
1528 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001529
aleloi868f32f2017-05-23 07:20:05 -07001530 if (aec_dump_) {
1531 aec_dump_->WriteRenderStreamMessage(*frame);
1532 }
1533
peahdf3efa82015-11-28 12:35:15 -08001534 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001535 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001536 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001537 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1538 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001539 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001540}
niklase@google.com470e71d2011-07-07 08:21:25 +00001541
peahde65ddc2016-09-16 15:02:15 -07001542int AudioProcessingImpl::ProcessRenderStreamLocked() {
1543 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001544
Alex Loiko73ec0192018-05-15 10:52:28 +02001545 HandleRenderRuntimeSettings();
1546
Alex Loiko5825aa62017-12-18 16:02:40 +01001547 if (private_submodules_->render_pre_processor) {
1548 private_submodules_->render_pre_processor->Process(render_buffer);
1549 }
1550
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001551 QueueNonbandedRenderAudio(render_buffer);
1552
peah2ace3f92016-09-10 04:42:27 -07001553 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001554 SampleRateSupportsMultiBand(
1555 formats_.render_processing_format.sample_rate_hz())) {
1556 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001557 }
1558
peahce4d9152017-05-19 01:28:05 -07001559 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1560 QueueBandedRenderAudio(render_buffer);
1561 }
1562
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001563 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001564 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001565 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001566 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001567
peah2ace3f92016-09-10 04:42:27 -07001568 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001569 SampleRateSupportsMultiBand(
1570 formats_.render_processing_format.sample_rate_hz())) {
1571 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001572 }
1573
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001574 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001575}
1576
1577int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001578 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001579 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001580 capture_.was_stream_delay_set = true;
1581 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001582
niklase@google.com470e71d2011-07-07 08:21:25 +00001583 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001584 delay = 0;
1585 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001586 }
1587
1588 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1589 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001590 delay = 500;
1591 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001592 }
1593
peahdf3efa82015-11-28 12:35:15 -08001594 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001595 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001596}
1597
1598int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001599 // Used as callback from submodules, hence locking is not allowed.
1600 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001601}
1602
1603bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001604 // Used as callback from submodules, hence locking is not allowed.
1605 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001606}
1607
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001608void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001609 rtc::CritScope cs(&crit_capture_);
1610 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001611}
1612
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001613void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001614 rtc::CritScope cs(&crit_capture_);
1615 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001616}
1617
1618int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001619 rtc::CritScope cs(&crit_capture_);
1620 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001621}
1622
aleloi868f32f2017-05-23 07:20:05 -07001623void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1624 RTC_DCHECK(aec_dump);
1625 rtc::CritScope cs_render(&crit_render_);
1626 rtc::CritScope cs_capture(&crit_capture_);
1627
1628 // The previously attached AecDump will be destroyed with the
1629 // 'aec_dump' parameter, which is after locks are released.
1630 aec_dump_.swap(aec_dump);
1631 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001632 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001633}
1634
1635void AudioProcessingImpl::DetachAecDump() {
1636 // The d-tor of a task-queue based AecDump blocks until all pending
1637 // tasks are done. This construction avoids blocking while holding
1638 // the render and capture locks.
1639 std::unique_ptr<AecDump> aec_dump = nullptr;
1640 {
1641 rtc::CritScope cs_render(&crit_render_);
1642 rtc::CritScope cs_capture(&crit_capture_);
1643 aec_dump = std::move(aec_dump_);
1644 }
1645}
1646
Sam Zackrisson4d364492018-03-02 16:03:21 +01001647void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1648 std::unique_ptr<AudioGenerator> audio_generator) {
1649 // TODO(bugs.webrtc.org/8882) Stub.
1650 // Reset internal audio generator with audio_generator.
1651}
1652
1653void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1654 // TODO(bugs.webrtc.org/8882) Stub.
1655 // Delete audio generator, if one is attached.
1656}
1657
Ivo Creusen56d46092017-11-24 17:29:59 +01001658AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001659 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001660 rtc::CritScope cs_capture(&crit_capture_);
1661 if (!has_remote_tracks) {
1662 return capture_.stats;
1663 }
1664 AudioProcessingStats stats = capture_.stats;
1665 EchoCancellationImpl::Metrics metrics;
1666 if (private_submodules_->echo_controller) {
1667 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1668 stats.echo_return_loss = ec_metrics.echo_return_loss;
1669 stats.echo_return_loss_enhancement =
1670 ec_metrics.echo_return_loss_enhancement;
1671 stats.delay_ms = ec_metrics.delay_ms;
1672 } else if (private_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1673 Error::kNoError) {
1674 if (metrics.divergent_filter_fraction != -1.0f) {
1675 stats.divergent_filter_fraction =
1676 absl::optional<double>(metrics.divergent_filter_fraction);
1677 }
1678 if (metrics.echo_return_loss.instant != -100) {
1679 stats.echo_return_loss =
1680 absl::optional<double>(metrics.echo_return_loss.instant);
1681 }
1682 if (metrics.echo_return_loss_enhancement.instant != -100) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001683 stats.echo_return_loss_enhancement =
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001684 absl::optional<double>(metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001685 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001686 }
1687 if (config_.residual_echo_detector.enabled) {
1688 RTC_DCHECK(private_submodules_->echo_detector);
1689 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1690 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1691 stats.residual_echo_likelihood_recent_max =
1692 ed_metrics.echo_likelihood_recent_max;
1693 }
1694 int delay_median, delay_std;
1695 float fraction_poor_delays;
1696 if (private_submodules_->echo_cancellation->GetDelayMetrics(
1697 &delay_median, &delay_std, &fraction_poor_delays) ==
1698 Error::kNoError) {
1699 if (delay_median >= 0) {
1700 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001701 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001702 if (delay_std >= 0) {
1703 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001704 }
1705 }
1706 return stats;
1707}
1708
niklase@google.com470e71d2011-07-07 08:21:25 +00001709GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001710 if (constants_.use_experimental_agc) {
1711 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001712 }
peahbfa97112016-03-10 21:09:04 -08001713 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001714}
1715
niklase@google.com470e71d2011-07-07 08:21:25 +00001716LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001717 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001718}
1719
1720NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001721 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001722}
1723
1724VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001725 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001726}
1727
peah8271d042016-11-22 07:24:52 -08001728void AudioProcessingImpl::MutateConfig(
1729 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1730 rtc::CritScope cs_render(&crit_render_);
1731 rtc::CritScope cs_capture(&crit_capture_);
1732 mutator(&config_);
1733 ApplyConfig(config_);
1734}
1735
1736AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1737 rtc::CritScope cs_render(&crit_render_);
1738 rtc::CritScope cs_capture(&crit_capture_);
1739 return config_;
1740}
1741
peah2ace3f92016-09-10 04:42:27 -07001742bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1743 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001744 config_.high_pass_filter.enabled,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001745 private_submodules_->echo_cancellation->is_enabled(),
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001746 private_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001747 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001748 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001749 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001750 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001751 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001752 public_submodules_->voice_detection->is_enabled(),
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001753 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001754 public_submodules_->level_estimator->is_enabled(),
1755 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001756}
1757
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001758void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001759 if (capture_.transient_suppressor_enabled) {
1760 if (!public_submodules_->transient_suppressor.get()) {
1761 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001762 }
peahdf3efa82015-11-28 12:35:15 -08001763 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001764 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1765 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001766 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001767}
1768
peah8271d042016-11-22 07:24:52 -08001769void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001770 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001771 private_submodules_->low_cut_filter.reset(
1772 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1773 } else {
1774 private_submodules_->low_cut_filter.reset();
1775 }
1776}
alessiob3ec96df2017-05-22 06:57:06 -07001777
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001778void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001779 if (echo_control_factory_) {
1780 private_submodules_->echo_controller =
1781 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001782 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001783 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001784 }
1785}
peah8271d042016-11-22 07:24:52 -08001786
alessiob3ec96df2017-05-22 06:57:06 -07001787void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001788 if (config_.gain_controller2.enabled) {
1789 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001790 }
1791}
1792
Alex Loikob5c9a792018-04-16 16:31:22 +02001793void AudioProcessingImpl::InitializePreAmplifier() {
1794 if (config_.pre_amplifier.enabled) {
1795 private_submodules_->pre_amplifier.reset(
1796 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1797 } else {
1798 private_submodules_->pre_amplifier.reset();
1799 }
1800}
1801
ivoc9f4a4a02016-10-28 05:39:16 -07001802void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001803 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001804 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001805 proc_sample_rate_hz(), 1,
1806 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001807}
1808
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001809void AudioProcessingImpl::InitializeAnalyzer() {
1810 if (private_submodules_->capture_analyzer) {
1811 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1812 num_proc_channels());
1813 }
1814}
1815
Sam Zackrisson0beac582017-09-25 12:04:02 +02001816void AudioProcessingImpl::InitializePostProcessor() {
1817 if (private_submodules_->capture_post_processor) {
1818 private_submodules_->capture_post_processor->Initialize(
1819 proc_sample_rate_hz(), num_proc_channels());
1820 }
1821}
1822
Alex Loiko5825aa62017-12-18 16:02:40 +01001823void AudioProcessingImpl::InitializePreProcessor() {
1824 if (private_submodules_->render_pre_processor) {
1825 private_submodules_->render_pre_processor->Initialize(
1826 formats_.render_processing_format.sample_rate_hz(),
1827 formats_.render_processing_format.num_channels());
1828 }
1829}
1830
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001831void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001832 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001833
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001834 if (private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001835 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1836 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001837 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001838 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001839 capture_.stream_delay_jumps = 0;
1840 }
1841 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001842 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001843 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001844 }
1845
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001846 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001847 const int diff_stream_delay_ms =
1848 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1849 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1850 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001851 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1852 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001853 if (capture_.stream_delay_jumps == -1) {
1854 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001855 }
peahdf3efa82015-11-28 12:35:15 -08001856 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001857 }
peahdf3efa82015-11-28 12:35:15 -08001858 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001859
1860 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001861 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001862 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001863 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001864 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001865 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001866 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001867 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001868 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001869 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001870 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001871 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1872 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1873 100);
peahdf3efa82015-11-28 12:35:15 -08001874 if (capture_.aec_system_delay_jumps == -1) {
1875 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001876 }
peahdf3efa82015-11-28 12:35:15 -08001877 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001878 }
peahdf3efa82015-11-28 12:35:15 -08001879 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001880 }
1881}
1882
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001883void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001884 // Run in a single-threaded manner.
1885 rtc::CritScope cs_render(&crit_render_);
1886 rtc::CritScope cs_capture(&crit_capture_);
1887
1888 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001889 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001890 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001891 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001892 }
peahdf3efa82015-11-28 12:35:15 -08001893 capture_.stream_delay_jumps = -1;
1894 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001895
peahdf3efa82015-11-28 12:35:15 -08001896 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001897 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1898 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001899 }
peahdf3efa82015-11-28 12:35:15 -08001900 capture_.aec_system_delay_jumps = -1;
1901 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001902}
1903
aleloi868f32f2017-05-23 07:20:05 -07001904void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1905 if (!aec_dump_) {
1906 return;
1907 }
1908 std::string experiments_description =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001909 private_submodules_->echo_cancellation->GetExperimentsDescription();
aleloi868f32f2017-05-23 07:20:05 -07001910 // TODO(peah): Add semicolon-separated concatenations of experiment
1911 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001912 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1913 experiments_description += "AgcClippingLevelExperiment;";
1914 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001915 if (capture_nonlocked_.echo_controller_enabled) {
1916 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001917 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001918 if (config_.gain_controller2.enabled) {
1919 experiments_description += "GainController2;";
1920 }
aleloi868f32f2017-05-23 07:20:05 -07001921
1922 InternalAPMConfig apm_config;
1923
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001924 apm_config.aec_enabled = private_submodules_->echo_cancellation->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001925 apm_config.aec_delay_agnostic_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001926 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001927 apm_config.aec_drift_compensation_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001928 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001929 apm_config.aec_extended_filter_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001930 private_submodules_->echo_cancellation->is_extended_filter_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001931 apm_config.aec_suppression_level = static_cast<int>(
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001932 private_submodules_->echo_cancellation->suppression_level());
aleloi868f32f2017-05-23 07:20:05 -07001933
1934 apm_config.aecm_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001935 private_submodules_->echo_control_mobile->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001936 apm_config.aecm_comfort_noise_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001937 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1938 apm_config.aecm_routing_mode = static_cast<int>(
1939 private_submodules_->echo_control_mobile->routing_mode());
aleloi868f32f2017-05-23 07:20:05 -07001940
1941 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1942 apm_config.agc_mode =
1943 static_cast<int>(public_submodules_->gain_control->mode());
1944 apm_config.agc_limiter_enabled =
1945 public_submodules_->gain_control->is_limiter_enabled();
1946 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1947
1948 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1949
1950 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1951 apm_config.ns_level =
1952 static_cast<int>(public_submodules_->noise_suppression->level());
1953
1954 apm_config.transient_suppression_enabled =
1955 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001956 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001957 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1958 apm_config.pre_amplifier_fixed_gain_factor =
1959 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001960
1961 if (!forced && apm_config == apm_config_for_aec_dump_) {
1962 return;
1963 }
1964 aec_dump_->WriteConfig(apm_config);
1965 apm_config_for_aec_dump_ = apm_config;
1966}
1967
1968void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1969 const float* const* src) {
1970 RTC_DCHECK(aec_dump_);
1971 WriteAecDumpConfigMessage(false);
1972
1973 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1974 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1975 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001976 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001977 RecordAudioProcessingState();
1978}
1979
1980void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1981 const AudioFrame& capture_frame) {
1982 RTC_DCHECK(aec_dump_);
1983 WriteAecDumpConfigMessage(false);
1984
1985 aec_dump_->AddCaptureStreamInput(capture_frame);
1986 RecordAudioProcessingState();
1987}
1988
1989void AudioProcessingImpl::RecordProcessedCaptureStream(
1990 const float* const* processed_capture_stream) {
1991 RTC_DCHECK(aec_dump_);
1992
1993 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1994 const size_t num_channels =
1995 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001996 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1997 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001998 aec_dump_->WriteCaptureStreamMessage();
1999}
2000
2001void AudioProcessingImpl::RecordProcessedCaptureStream(
2002 const AudioFrame& processed_capture_frame) {
2003 RTC_DCHECK(aec_dump_);
2004
2005 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2006 aec_dump_->WriteCaptureStreamMessage();
2007}
2008
2009void AudioProcessingImpl::RecordAudioProcessingState() {
2010 RTC_DCHECK(aec_dump_);
2011 AecDump::AudioProcessingState audio_proc_state;
2012 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2013 audio_proc_state.drift =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002014 private_submodules_->echo_cancellation->stream_drift_samples();
aleloi868f32f2017-05-23 07:20:05 -07002015 audio_proc_state.level = gain_control()->stream_analog_level();
2016 audio_proc_state.keypress = capture_.key_pressed;
2017 aec_dump_->AddAudioProcessingState(audio_proc_state);
2018}
2019
kwiberg83ffe452016-08-29 14:46:07 -07002020AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002021 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002022 : aec_system_delay_jumps(-1),
2023 delay_offset_ms(0),
2024 was_stream_delay_set(false),
2025 last_stream_delay_ms(0),
2026 last_aec_system_delay_ms(0),
2027 stream_delay_jumps(-1),
2028 output_will_be_muted(false),
2029 key_pressed(false),
2030 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002031 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002032 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002033 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002034 prev_analog_mic_level(-1),
2035 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002036
2037AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2038
2039AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2040
2041AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2042
niklase@google.com470e71d2011-07-07 08:21:25 +00002043} // namespace webrtc